Skip to content

Projection#

The class ANNarchy.Projection defines projections at the population level. A projection is an ensemble of connections (or synapses) between a subset of a population (called the pre-synaptic population) and a subset of another population (the post-synaptic population), with a specific connection type. The pre- and post-synaptic populations may be the same.

The connectors are methods of the projections, for example:

proj = Projection(pop, pop, 'exc)
proj.connect_all_to_all(weights=Normal(0, 1))

ANNarchy.core.Projection.Projection #

Bases: object

Container for all the synapses of the same type between two populations.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
  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
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
class Projection(object):
    """
    Container for all the synapses of the same type between two populations.
    """

    def __init__(self, pre, post, target, synapse=None, name=None, disable_omp=True, copied=False):
        """
        By default, the synapse only ensures linear synaptic transmission:

        * For rate-coded populations: ``psp = w * pre.r``
        * For spiking populations: ``g_target += w``

        to modify this behavior one need to provide a Synapse object.

        :param pre: pre-synaptic population (either its name or a ``Population`` object).
        :param post: post-synaptic population (either its name or a ``Population`` object).
        :param target: type of the connection.
        :param synapse: a ``Synapse`` instance.
        :param name: unique name of the projection (optional, it defaults to ``proj0``, ``proj1``, etc).
        :param disable_omp: especially for small- and mid-scale sparse spiking networks the parallelization of spike propagation is not scalable. But it can be enabled by setting this parameter to `False`.
        """
        # Check if the network has already been compiled
        if Global._network[0]['compiled'] and not copied:
            Global._error('you cannot add a projection after the network has been compiled.')

        # Store the pre and post synaptic populations
        # the user provide either a string or a population object
        # in case of string, we need to search for the corresponding object
        if isinstance(pre, str):
            for pop in Global._network[0]['populations']:
                if pop.name == pre:
                    self.pre = pop
        else:
            self.pre = pre

        if isinstance(post, str):
            for pop in Global._network[0]['populations']:
                if pop.name == post:
                    self.post = pop
        else:
            self.post = post

        # Store the arguments
        if isinstance(target, list) and len(target) == 1:
            self.target = target[0]
        else:
            self.target = target

        # Add the target(s) to the postsynaptic population
        if isinstance(self.target, list):
            for _target in self.target:
                self.post.targets.append(_target)
        else:
            self.post.targets.append(self.target)

        # check if a synapse description is attached
        if not synapse:
            # No synapse attached assume default synapse based on
            # presynaptic population.
            if self.pre.neuron_type.type == 'rate':
                from ANNarchy.models.Synapses import DefaultRateCodedSynapse
                self.synapse_type = DefaultRateCodedSynapse()
                self.synapse_type.type = 'rate'
            else:
                from ANNarchy.models.Synapses import DefaultSpikingSynapse
                self.synapse_type = DefaultSpikingSynapse()
                self.synapse_type.type = 'spike'

        elif inspect.isclass(synapse):
            self.synapse_type = synapse()
            self.synapse_type.type = self.pre.neuron_type.type
        else:
            self.synapse_type = copy.deepcopy(synapse)
            self.synapse_type.type = self.pre.neuron_type.type

        # Disable omp for spiking networks
        self.disable_omp = disable_omp

        # Analyse the parameters and variables
        self.synapse_type._analyse()

        # Create a default name
        self.id = len(Global._network[0]['projections'])
        if name:
            self.name = name
        else:
            self.name = 'proj'+str(self.id)

        # Container for control/attribute states
        self.init = {}

        # Control-flow variables
        self.init["transmission"] = True
        self.init["update"] = True
        self.init["plasticity"] = True

        # Get a list of parameters and variables
        self.parameters = []
        for param in self.synapse_type.description['parameters']:
            self.parameters.append(param['name'])
            self.init[param['name']] = param['init']

        self.variables = []
        for var in self.synapse_type.description['variables']:
            self.variables.append(var['name'])
            self.init[var['name']] = var['init']

        self.attributes = self.parameters + self.variables

        # Get a list of user-defined functions
        self.functions = [func['name'] for func in self.synapse_type.description['functions']]

        # Add the population to the global network
        Global._network[0]['projections'].append(self)

        # Finalize initialization
        self.initialized = False

        # Cython instance
        self.cyInstance = None

        # Connectivity
        self._synapses = None
        self._connection_method = None
        self._connection_args = None
        self._connection_delay = None
        self._connector = None
        self._lil_connectivity = None

        # Default configuration for connectivity
        self._storage_format = "lil"
        self._storage_order = "post_to_pre"

        # If a single weight value is used
        self._single_constant_weight = False

        # Are random distribution used for weights/delays
        self.connector_weight_dist = None
        self.connector_delay_dist = None

        # Reporting
        self.connector_name = "Specific"
        self.connector_description = "Specific"

        # Overwritten by derived classes, to add
        # additional code
        self._specific_template = {}

        # Set to False by derived classes to prevent saving of
        # data, e. g. in case of weight-sharing projections
        self._saveable = True

        # To allow case-specific adjustment of parallelization
        # parameters, e. g. openMP schedule, we introduce a
        # dictionary read by the ProjectionGenerator.
        #
        # Will be overwritten either by inherited classes or
        # by an omp_config provided to the compile() method.
        self._omp_config = {
            #'psp_schedule': 'schedule(dynamic)'
        }

        # If set to true, the code generator is not allowed to
        # split the matrix. This will be the case for many
        # SpecificProjections defined by the user or is disabled
        # globally.
        if self.synapse_type.type == "rate":
            # Normally, the split should not be used for rate-coded models
            # but maybe there are cases where we want to enable it ...
            self._no_split_matrix = Global.config["disable_split_matrix"]

            # If the number of elements is too small, the split
            # might not be efficient.
            if self.post.size < Global.OMP_MIN_NB_NEURONS:
                self._no_split_matrix = True

        else:
            # If the number of elements is too small, the split
            # might not be efficient.
            if self.post.size < Global.OMP_MIN_NB_NEURONS:
                self._no_split_matrix = True
            else:
                self._no_split_matrix = Global.config["disable_split_matrix"]

        # In particular for spiking models, the parallelization on the
        # inner or outer loop can make a performance difference
        if self._no_split_matrix:
            # LIL and CSR are parallelized on inner loop
            # to prevent cost of atomic operations
            self._parallel_pattern = 'inner_loop'
        else:
            # splitted matrices are always parallelized on outer loop!
            self._parallel_pattern = 'outer_loop'

        # For dense matrix format: do we use an optimization for population views?
        if self.synapse_type.type == "rate":
            # HD (9th Nov. 2022): currently this optimization is only intended for spiking models
            self._has_pop_view = False
        else:
            # HD (9th Nov. 2022): currently disabled, more testing is required ...
            self._has_pop_view = False #isinstance(self.pre, PopulationView) or isinstance(self.post, PopulationView)

    # Add defined connectors
    connect_one_to_one = ConnectorMethods.connect_one_to_one
    connect_all_to_all = ConnectorMethods.connect_all_to_all
    connect_gaussian = ConnectorMethods.connect_gaussian
    connect_dog = ConnectorMethods.connect_dog
    connect_fixed_probability = ConnectorMethods.connect_fixed_probability
    connect_fixed_number_pre = ConnectorMethods.connect_fixed_number_pre
    connect_fixed_number_post = ConnectorMethods.connect_fixed_number_post
    connect_with_func = ConnectorMethods.connect_with_func
    connect_from_matrix = ConnectorMethods.connect_from_matrix
    connect_from_matrix_market = ConnectorMethods.connect_from_matrix_market
    _load_from_matrix = ConnectorMethods._load_from_matrix
    connect_from_sparse = ConnectorMethods.connect_from_sparse
    _load_from_sparse = ConnectorMethods._load_from_sparse
    connect_from_file = ConnectorMethods.connect_from_file
    _load_from_lil = ConnectorMethods._load_from_lil

    def _copy(self, pre, post):
        "Returns a copy of the projection when creating networks.  Internal use only."
        copied_proj = Projection(pre=pre, post=post, target=self.target, synapse=self.synapse_type, name=self.name, disable_omp=self.disable_omp, copied=True)

        # these flags are modified during connect_XXX called before Network()
        copied_proj._single_constant_weight = self._single_constant_weight
        copied_proj.connector_weight_dist = self.connector_weight_dist
        copied_proj.connector_delay_dist = self.connector_delay_dist
        copied_proj.connector_name = self.connector_name

        # Control flags for code generation (maybe modified by connect_XXX())
        copied_proj._storage_format = self._storage_format
        copied_proj._storage_order = self._storage_order
        copied_proj._no_split_matrix = self._no_split_matrix

        # for some projection types saving is not allowed (e. g. Convolution, Pooling)
        copied_proj._saveable = self._saveable

        # optional flags
        if hasattr(self, "_bsr_size"):
            copied_proj._bsr_size = self._bsr_size

        return copied_proj

    def _generate(self):
        "Overriden by specific projections to generate the code"
        pass

    def _instantiate(self, module):
        """
        Instantiates the projection after compilation. The function should be
        called by Compiler._instantiate().

        :param:     module  cython module (ANNarchyCore instance)
        """
        if Global.config["profiling"]:
            import time
            t1 = time.time()

        self.initialized = self._connect(module)

        if Global.config["profiling"]:
            t2 = time.time()
            Global._profiler.add_entry(t1, t2, "proj"+str(self.id), "instantiate")

    def _init_attributes(self):
        """
        Method used after compilation to initialize the attributes. The function
        should be called by Compiler._instantiate
        """
        for name, val in self.init.items():
            # the weights ('w') are already inited by the _connect() method.
            if not name in ['w']:
                self.__setattr__(name, val)

    def _connect(self, module):
        """
        Builds up dendrites either from list or dictionary. Called by instantiate().

        :param:     module  cython module (ANNarchyCore instance)
        :return:    True, if the connector was successfully instantiated. Potential errors are kept by 
                    Python exceptions. If the Cython - connector call fails (return False) the most likely
                    reason is that there was not enough memory available.
        """
        # Local import to prevent circular import (HD: 28th June 2021)
        from ANNarchy.generator.Utils import cpp_connector_available

        # Sanity check
        if not self._connection_method:
            Global._error('The projection between ' + self.pre.name + ' and ' + self.post.name + ' is declared but not connected.')

        # Debug printout
        if Global.config["verbose"]:
            print("Connectivity parameter ("+self.name+"):", self._connection_args )

        # Instantiate the Cython wrapper
        if not self.cyInstance:
            cy_wrapper = getattr(module, 'proj'+str(self.id)+'_wrapper')
            self.cyInstance = cy_wrapper()

        # Check if there is a specialized CPP connector
        if not cpp_connector_available(self.connector_name, self._storage_format, self._storage_order):
            # No default connector -> initialize from LIL
            if self._lil_connectivity:
                return self.cyInstance.init_from_lil_connectivity(self._lil_connectivity)
            else:
                return self.cyInstance.init_from_lil_connectivity(self._connection_method(*((self.pre, self.post,) + self._connection_args)))

        else:
            # fixed probability pattern
            if self.connector_name == "Random":
                p = self._connection_args[0]
                allow_self_connections = self._connection_args[3]
                if isinstance(self._connection_args[1], RandomDistribution):
                    #some kind of distribution
                    w_dist_arg1, w_dist_arg2 = self._connection_args[1].get_cpp_args()
                else:
                    # constant
                    w_dist_arg1 = self._connection_args[1]
                    w_dist_arg2 = self._connection_args[1]

                if isinstance(self._connection_args[2], RandomDistribution):
                    #some kind of distribution
                    d_dist_arg1, d_dist_arg2 = self._connection_args[2].get_cpp_args()
                else:
                    # constant
                    d_dist_arg1 = self._connection_args[2]
                    d_dist_arg2 = self._connection_args[2]

                return self.cyInstance.fixed_probability(self.post.ranks, self.pre.ranks, p, w_dist_arg1, w_dist_arg2, d_dist_arg1, d_dist_arg2, allow_self_connections)

            # fixed number pre prattern
            elif self.connector_name== "Random Convergent":
                number_nonzero = self._connection_args[0]
                if isinstance(self._connection_args[1], RandomDistribution):
                    #some kind of distribution
                    w_dist_arg1, w_dist_arg2 = self._connection_args[1].get_cpp_args()
                else:
                    # constant
                    w_dist_arg1 = self._connection_args[1]
                    w_dist_arg2 = self._connection_args[1]

                if isinstance(self._connection_args[2], RandomDistribution):
                    #some kind of distribution
                    d_dist_arg1, d_dist_arg2 = self._connection_args[2].get_cpp_args()
                else:
                    # constant
                    d_dist_arg1 = self._connection_args[2]
                    d_dist_arg2 = self._connection_args[2]

                return self.cyInstance.fixed_number_pre(self.post.ranks, self.pre.ranks, number_nonzero, w_dist_arg1, w_dist_arg2, d_dist_arg1, d_dist_arg2)

            else:
                # This should never happen ...
                Global._error("No initialization for CPP-connector defined ...")

        # should be never reached ...
        return False

    def _store_connectivity(self, method, args, delay, storage_format, storage_order):
        """
        Store connectivity data. This function is called from cython_ext.Connectors module.
        """
        # No format specified for this projection by the user, so fall-back to Global setting
        if storage_format is None:
            if Global.config['sparse_matrix_format'] == "default":
                if Global._check_paradigm("openmp"):
                    storage_format = "lil"
                elif Global._check_paradigm("cuda"):
                    storage_format = "csr"
                else:
                    raise NotImplementedError

            else:
                storage_format = Global.config["sparse_matrix_format"]

        # Sanity checks
        if self._connection_method != None:
            Global._warning("Projection ", self.name, " was already connected ... data will be overwritten.")

        # Store connectivity pattern parameters
        self._connection_method = method
        self._connection_args = args
        self._connection_delay = delay
        self._storage_format = storage_format
        self._storage_order = storage_order

        # The user selected nothing therefore we use the standard since ANNarchy 4.4.0
        if storage_format == None:
            self._storage_format = "lil"
        if storage_order == None:
            if storage_format == "auto":
                storage_order = "auto"
            else:
                self._storage_order = "post_to_pre"

        # The user selected automatic format selection using heuristics
        if storage_format == "auto":
            self._storage_format = self._automatic_format_selection()
        if storage_order == "auto":
            self._storage_order = self._automatic_order_selection()

        # Analyse the delay
        if isinstance(delay, (int, float)): # Uniform delay
            self.max_delay = round(delay/Global.config['dt'])
            self.uniform_delay = round(delay/Global.config['dt'])

        elif isinstance(delay, RandomDistribution): # Non-uniform delay
            self.uniform_delay = -1
            # Ensure no negative delays are generated
            if delay.min is None or delay.min < Global.config['dt']:
                delay.min = Global.config['dt']
            # The user needs to provide a max in order to compute max_delay
            if delay.max is None:
                Global._error('Projection.connect_xxx(): if you use a non-bounded random distribution for the delays (e.g. Normal), you need to set the max argument to limit the maximal delay.')

            self.max_delay = round(delay.max/Global.config['dt'])

        elif isinstance(delay, (list, np.ndarray)): # connect_from_matrix/sparse
            if len(delay) > 0:
                self.uniform_delay = -1
                self.max_delay = round(max([max(l) for l in delay])/Global.config['dt'])
            else: # list is empty, no delay
                self.max_delay = -1
                self.uniform_delay = -1

        else:
            Global._error('Projection.connect_xxx(): delays are not valid!')

        # Transmit the max delay to the pre pop
        if isinstance(self.pre, PopulationView):
            self.pre.population.max_delay = max(self.max_delay, self.pre.population.max_delay)
        else:
            self.pre.max_delay = max(self.max_delay, self.pre.max_delay)

    def _automatic_format_selection(self):
        """
        We check some heuristics to select a specific format implemented as decision tree:

            - If the filling degree is high enough a full matrix representation might be better
            - if the average row length is below a threshold the ELLPACK-R might be better
            - if the average row length is higher than a threshold the CSR might be better

        HD (17th Jan. 2022): Currently structural plasticity is only usable with LIL. But one could also
                             apply it for dense matrices in the future. For CSR and in particular the ELL-
                             like formats the potential memory-reallocations make the structural plasticity
                             a costly operation.
        """
        # Connection pattern / Feature specific selection
        if Global.config["structural_plasticity"]:
            storage_format = "lil"

        elif self.connector_name == "All-to-All":
            storage_format = "dense"

        elif self.connector_name == "One-to-One":
            if Global._check_paradigm("cuda"):
                storage_format = "csr"
            else:
                storage_format = "lil"

        else:
            if self.synapse_type.type == "spike":
                # we need to build up the matrix to analyze
                self._lil_connectivity = self._connection_method(*((self.pre, self.post,) + self._connection_args))

                # get the decision parameter
                density = float(self._lil_connectivity.nb_synapses) / float(self.pre.size * self.post.size)
                if density >= 0.6:
                    if Global._check_paradigm("cuda"):
                        storage_format = "csr"  # HD (11th Nov. 2022): there is no Dense_T for spiking and CUDA yet
                    else:
                        storage_format = "dense"
                else:
                    storage_format = "csr"

            else:
                # we need to build up the matrix to analyze
                self._lil_connectivity = self._connection_method(*((self.pre, self.post,) + self._connection_args))

                # get the decision parameter
                density = float(self._lil_connectivity.nb_synapses) / float(self.pre.size * self.post.size)
                avg_nnz_per_row, _ = self._lil_connectivity.compute_average_row_length()

                # heuristic decision tree
                if density >= 0.6:
                    storage_format = "dense"
                else:
                    if Global._check_paradigm("cuda"):
                        if avg_nnz_per_row <= 128:
                            storage_format = "ellr"
                        else:
                            storage_format = "csr"
                    else:
                        storage_format = "csr"

        Global._info("Automatic format selection for", self.name, ":", storage_format)
        return storage_format

    def _automatic_order_selection(self):
        """
        Contrary to the matrix format, the decision for the matrix order is majorly dependent on
        the synapse type.
        """
        if self.synapse_type.type == "rate":
            storage_order = "post_to_pre"
        else:
            if Global._check_paradigm("cuda"):
                # HD (11th Nov. 2022): there is no Dense_T / CSRC_T for spiking and CUDA yet
                storage_order = "post_to_pre"
            else:
                # pre-to-post is not implemented for all formats
                if self._storage_format in ["dense", "csr"]:
                    storage_order = "pre_to_post"
                else:
                    storage_order = "post_to_pre"

        Global._info("Automatic matrix order selection for", self.name, ":", storage_order)
        return storage_order

    def _has_single_weight(self):
        "If a single weight should be generated instead of a LIL"
        is_cpu = Global.config['paradigm']=="openmp"
        has_constant_weight = self._single_constant_weight
        not_dense = not (self._storage_format == "dense")
        no_structural_plasticity = not Global.config['structural_plasticity']
        no_synaptic_plasticity = not self.synapse_type.description['plasticity']

        return has_constant_weight and no_structural_plasticity and no_synaptic_plasticity and is_cpu and not_dense

    def reset(self, attributes=-1, synapses=False):
        """
        Resets all parameters and variables of the projection to their initial value (before the call to compile()).

        :param attributes: list of attributes (parameter or variable) which should be reinitialized. Default: all attributes (-1).
        :param synapses: defines if the weights and delays should also be recreated. Default: False
        """
        if attributes == -1:
            attributes = self.attributes

        if synapses:
            # destroy the previous C++ content
            self._clear()
            # call the init connectivity again
            self.initialized = self._connect(None)

        for var in attributes:
            # Skip w
            if var=='w':
                continue
            # check it exists
            if not var in self.attributes:
                Global._warning("Projection.reset():", var, "is not an attribute of the population, won't reset.")
                continue
            # Set the value
            try:
                self.__setattr__(var, self.init[var])
            except Exception as e:
                Global._print(e)
                Global._warning("Projection.reset(): something went wrong while resetting", var)

    ################################
    ## Dendrite access
    ################################
    @property
    def size(self):
        "Number of post-synaptic neurons receiving synapses."
        if self.cyInstance == None:
            Global._warning("Access 'size or len()' attribute of a Projection is only valid after compile()")
            return 0

        return len(self.cyInstance.post_rank())

    def __len__(self):
        # Number of postsynaptic neurons receiving synapses in this projection.
        return self.size

    @property
    def nb_synapses(self):
        "Total number of synapses in the projection."
        if self.cyInstance is None:
            Global._warning("Access 'nb_synapses' attribute of a Projection is only valid after compile()")
            return 0
        return self.cyInstance.nb_synapses()

    def nb_synapses_per_dendrite(self):
        "Total number of synapses for each dendrite as a list."
        if self.cyInstance is None:
            Global._warning("Access 'nb_synapses_per_dendrite' attribute of a Projection is only valid after compile()")
            return []
        return [self.cyInstance.dendrite_size(n) for n in range(self.size)]

    def nb_efferent_synapses(self):
        "Number of efferent connections. Intended only for spiking models."
        if self.cyInstance is None:
             Global._warning("Access 'nb_efferent_synapses()' of a Projection is only valid after compile()")
             return None
        if self.synapse_type.type == "rate":
            Global._error("Projection.nb_efferent_synapses() is not available for rate-coded projections.")

        return self.cyInstance.nb_efferent_synapses()

    @property
    def post_ranks(self):
        if self.cyInstance is None:
             Global._warning("Access 'post_ranks' attribute of a Projection is only valid after compile()")
             return None

        return self.cyInstance.post_rank()

    @property
    def dendrites(self):
        """
        Iteratively returns the dendrites corresponding to this projection.
        """
        for idx, n in enumerate(self.post_ranks):
            yield Dendrite(self, n, idx)

    def dendrite(self, post):
        """
        Returns the dendrite of a postsynaptic neuron according to its rank.

        :param post: can be either the rank or the coordinates of the post-synaptic neuron.
        """
        if not self.initialized:
            Global._error('dendrites can only be accessed after compilation.')

        if isinstance(post, int):
            rank = post
        else:
            rank = self.post.rank_from_coordinates(post)

        if rank in self.post_ranks:
            return Dendrite(self, rank, self.post_ranks.index(rank))
        else:
            Global._error(" The neuron of rank "+ str(rank) + " has no dendrite in this projection.", exit=True)


    def synapse(self, pre, post):
        """
        Returns the synapse between a pre- and a post-synaptic neuron if it exists, None otherwise.

        :param pre: rank of the pre-synaptic neuron.
        :param post: rank of the post-synaptic neuron.
        """
        if not isinstance(pre, int) or not isinstance(post, int):
            Global._error('Projection.synapse() only accepts ranks for the pre and post neurons.')

        return self.dendrite(post).synapse(pre)


    # Iterators
    def __getitem__(self, *args, **kwds):
        # Returns dendrite of the given position in the postsynaptic population.
        # If only one argument is given, it is a rank. If it is a tuple, it is coordinates.

        if len(args) == 1:
            return self.dendrite(args[0])
        return self.dendrite(args)

    def __iter__(self):
        # Returns iteratively each dendrite in the population in ascending postsynaptic rank order.
        for idx, n in enumerate(self.post_ranks):
            yield Dendrite(self, n, idx)

    ################################
    ## Access to attributes
    ################################
    def get(self, name):
        """
        Returns a list of parameters/variables values for each dendrite in the projection.

        The list will have the same length as the number of actual dendrites (self.size), so it can be smaller than the size of the postsynaptic population. Use self.post_ranks to indice it.

        :param name: the name of the parameter or variable
        """
        return self.__getattr__(name)

    def set(self, value):
        """
        Sets the parameters/variables values for each dendrite in the projection.

        For parameters, you can provide:

        * a single value, which will be the same for all dendrites.

        * a list or 1D numpy array of the same length as the number of actual dendrites (self.size).

        For variables, you can provide:

        * a single value, which will be the same for all synapses of all dendrites.

        * a list or 1D numpy array of the same length as the number of actual dendrites (self.size). The synapses of each postsynaptic neuron will take the same value.

        **Warning:** it is not possible to set different values to each synapse using this method. One should iterate over the dendrites:

        ```python
        for dendrite in proj.dendrites:
            dendrite.w = np.ones(dendrite.size)
        ```

        :param value: a dictionary with the name of the parameter/variable as key.

        """

        for name, val in value.items():
            self.__setattr__(name, val)

    def __getattr__(self, name):
        # Method called when accessing an attribute.
        if name == 'initialized' or not hasattr(self, 'initialized'): # Before the end of the constructor
            return object.__getattribute__(self, name)
        elif hasattr(self, 'attributes'):
            if name in ['plasticity', 'transmission', 'update']:
                return self._get_flag(name)
            if name in ['delay']:
                return self._get_delay()
            if name in self.attributes:
                if not self.initialized:
                    return self.init[name]
                else:
                    return self._get_cython_attribute( name )
            elif name in self.functions:
                return self._function(name)
            else:
                return object.__getattribute__(self, name)
        return object.__getattribute__(self, name)

    def __setattr__(self, name, value):
        # Method called when setting an attribute.
        if name == 'initialized' or not hasattr(self, 'initialized'): # Before the end of the constructor
            object.__setattr__(self, name, value)
        elif hasattr(self, 'attributes'):
            if name in ['plasticity', 'transmission', 'update']:
                self._set_flag(name, bool(value))
                return
            if name in ['delay']:
                self._set_delay(value)
                return
            if name in self.attributes:
                if not self.initialized:
                    self.init[name] = value
                else:
                    self._set_cython_attribute(name, value)
            else:
                object.__setattr__(self, name, value)
        else:
            object.__setattr__(self, name, value)

    def _get_cython_attribute(self, attribute):
        """
        Returns the value of the given attribute for all neurons in the population,
        as a list of lists having the same geometry as the population if it is local.

        :param attribute: a string representing the variables's name.

        """
        # Determine C++ data type
        ctype = self._get_attribute_cpp_type(attribute=attribute)

        # retrieve the value from C++ core
        if attribute == "w" and self._has_single_weight():
            return self.cyInstance.get_global_attribute(attribute, ctype)
        elif attribute in self.synapse_type.description['local']:
            return self.cyInstance.get_local_attribute_all(attribute, ctype)
        elif attribute in self.synapse_type.description['semiglobal']:
            return self.cyInstance.get_semiglobal_attribute_all(attribute, ctype)
        else:
            return self.cyInstance.get_global_attribute(attribute, ctype)

    def _set_cython_attribute(self, attribute, value):
        """
        Sets the value of the given attribute for all post-synaptic neurons in the projection,
        as a NumPy array having the same geometry as the population if it is local.

        :param attribute: a string representing the variables's name.
        :param value: the value it should take.

        """
        # Determine C++ data type
        ctype = self._get_attribute_cpp_type(attribute=attribute)

        # Convert np.arrays into lists/constants for better iteration
        if isinstance(value, np.ndarray):
            if np.ndim(value) == 0:
                value = float(value)
            else:
                value = list(value)

        # A list is given
        if isinstance(value, list):
            if len(value) == len(self.post_ranks):
                if attribute in self.synapse_type.description['local']:
                    for idx, n in enumerate(self.post_ranks):
                        if not len(value[idx]) == self.cyInstance.dendrite_size(idx):
                            Global._error('The postynaptic neuron ' + str(n) + ' receives '+ str(self.cyInstance.dendrite_size(idx))+ ' synapses.')
                        self.cyInstance.set_local_attribute_row(attribute, idx, value[idx], ctype)
                elif attribute in self.synapse_type.description['semiglobal']:
                    self.cyInstance.set_semiglobal_attribute_all(attribute, value, ctype)
                else:
                    Global._error('The parameter', attribute, 'is global to the population, cannot assign a list.')
            else:
                Global._error('The projection has', self.size, 'post-synaptic neurons, the list must have the same size.')

        # A Random Distribution is given
        elif isinstance(value, RandomDistribution):
            if attribute == "w" and self._has_single_weight():
                self.cyInstance.set_global_attribute(attribute, value.get_values(1), ctype)
            elif attribute in self.synapse_type.description['local']:
                for idx, n in enumerate(self.post_ranks):
                    self.cyInstance.set_local_attribute_row(attribute, idx, value.get_values(self.cyInstance.dendrite_size(idx)), ctype)
            elif attribute in self.synapse_type.description['semiglobal']:
                self.cyInstance.set_semiglobal_attribute_all(attribute, value.get_values(len(self.post_ranks)), ctype)
            elif attribute in self.synapse_type.description['global']:
                self.cyInstance.set_global_attribute(attribute, value.get_values(1), ctype)
        # A single value is given
        else:
            if attribute == "w" and self._has_single_weight():
                self.cyInstance.set_global_attribute(attribute, value, ctype)
            elif attribute in self.synapse_type.description['local']:
                for idx, n in enumerate(self.post_ranks):
                    self.cyInstance.set_local_attribute_row(attribute, idx, value*np.ones(self.cyInstance.dendrite_size(idx)), ctype)
            elif attribute in self.synapse_type.description['semiglobal']:
                self.cyInstance.set_semiglobal_attribute_all(attribute, value*np.ones(len(self.post_ranks)), ctype)
            else:
                self.cyInstance.set_global_attribute(attribute, value, ctype)

    def _get_attribute_cpp_type(self, attribute):
        """
        Determine C++ data type for a given attribute
        """
        ctype = None
        for var in self.synapse_type.description['variables']+self.synapse_type.description['parameters']:
            if var['name'] == attribute:
                ctype = var['ctype']

        return ctype

    def _get_flag(self, attribute):
        "control flow flags such as learning, transmission"
        if self.cyInstance is not None:
            return getattr(self.cyInstance, '_get_'+attribute)()
        else:
            return self.init[attribute]

    def _set_flag(self, attribute, value):
        "control flow flags such as learning, transmission"
        if self.cyInstance is not None:
            getattr(self.cyInstance, '_set_'+attribute)(value)
        else:
            self.init[attribute] = value


    ################################
    ## Access to delays
    ################################
    def _get_delay(self):
        if not hasattr(self.cyInstance, 'get_delay'):
            if self.max_delay <= 1 :
                return Global.config['dt']
        elif self.uniform_delay != -1:
                return self.uniform_delay * Global.config['dt']
        else:
            return [[pre * Global.config['dt'] for pre in post] for post in self.cyInstance.get_delay()]

    def _set_delay(self, value):

        if self.cyInstance: # After compile()
            if not hasattr(self.cyInstance, 'get_delay'):
                if self.max_delay <= 1 and value != Global.config['dt']:
                    Global._error("set_delay: the projection was instantiated without delays, it is too late to create them...")

            elif self.uniform_delay != -1:
                if isinstance(value, np.ndarray):
                    if value.ndim > 0:
                        Global._error("set_delay: the projection was instantiated with uniform delays, it is too late to load non-uniform values...")
                    else:
                        value = max(1, round(float(value)/Global.config['dt']))
                elif isinstance(value, (float, int)):
                    value = max(1, round(float(value)/Global.config['dt']))
                else:
                    Global._error("set_delay: only float, int or np.array values are possible.")

                # The new max_delay is higher than before
                if value > self.max_delay:
                    self.max_delay = value
                    self.uniform_delay = value
                    self.cyInstance.set_delay(value)
                    if isinstance(self.pre, PopulationView):
                        self.pre.population.max_delay = max(self.max_delay, self.pre.population.max_delay)
                        self.pre.population.cyInstance.update_max_delay(self.pre.population.max_delay)
                    else:
                        self.pre.max_delay = max(self.max_delay, self.pre.max_delay)
                        self.pre.cyInstance.update_max_delay(self.pre.max_delay)
                    return
                else:
                    self.uniform_delay = value
                    self.cyInstance.set_delay(value)

            else: # variable delays
                if not isinstance(value, (np.ndarray, list)):
                    Global._error("set_delay with variable delays: you must provide a list of lists of exactly the same size as before.")

                # Check the number of delays
                nb_values = sum([len(s) for s in value])
                if nb_values != self.nb_synapses:
                    Global._error("set_delay with variable delays: the sizes do not match. You have to provide one value for each existing synapse.")
                if len(value) != len(self.post_ranks):
                    Global._error("set_delay with variable delays: the sizes do not match. You have to provide one value for each existing synapse.")

                # Convert to steps
                if isinstance(value, np.ndarray):
                    delays = [[max(1, round(value[i, j]/Global.config['dt'])) for j in range(value.shape[1])] for i in range(value.shape[0])]
                else:
                    delays = [[max(1, round(v/Global.config['dt'])) for v in c] for c in value]

                # Max delay
                max_delay = max([max(l) for l in delays])

                if max_delay > self.max_delay:
                    self.max_delay = max_delay

                    # Send the max delay to the pre population
                    if isinstance(self.pre, PopulationView):
                        self.pre.population.max_delay = max(self.max_delay, self.pre.population.max_delay)
                        self.pre.population.cyInstance.update_max_delay(self.pre.population.max_delay)
                    else:
                        self.pre.max_delay = max(self.max_delay, self.pre.max_delay)
                        self.pre.cyInstance.update_max_delay(self.pre.max_delay)

                # Send the new values to the projection
                self.cyInstance.set_delay(delays)

                # Update ring buffers (if there exist)
                self.cyInstance.update_max_delay(self.max_delay)

        else: # before compile()
            Global._error("set_delay before compile(): not implemented yet.")


    ################################
    ## Access to functions
    ################################
    def _function(self, func):
        "Access a user defined function"
        if not self.initialized:
            Global._error('the network is not compiled yet, cannot access the function ' + func)

        return getattr(self.cyInstance, func)

    ################################
    ## Learning flags
    ################################
    def enable_learning(self, period=None, offset=None):
        """
        Enables learning for all the synapses of this projection.

        For example, providing the following parameters at time 10 ms:

        ```python
        enable_learning(period=10., offset=5.)
        ```

        would call the updating methods at times 15, 25, 35, etc...

        The default behaviour is that the synaptic variables are updated at each time step. The parameters must be multiple of ``dt``.

        :param period: determines how often the synaptic variables will be updated.
        :param offset: determines the offset at which the synaptic variables will be updated relative to the current time.

        """
        # Check arguments
        if not period is None and not offset is None:
            if offset >= period:
                Global._error('enable_learning(): the offset must be smaller than the period.')

        if period is None and not offset is None:
            Global._error('enable_learning(): if you define an offset, you have to define a period.')

        try:
            self.cyInstance._set_update(True)
            self.cyInstance._set_plasticity(True)
            if period != None:
                self.cyInstance._set_update_period(int(period/Global.config['dt']))
            else:
                self.cyInstance._set_update_period(int(1))
                period = Global.config['dt']
            if offset != None:
                relative_offset = Global.get_time() % period + offset
                self.cyInstance._set_update_offset(int(int(relative_offset%period)/Global.config['dt']))
            else:
                self.cyInstance._set_update_offset(int(0))
        except:
            Global._warning('Enable_learning() is only possible after compile()')

    def disable_learning(self, update=None):
        """
        Disables learning for all synapses of this projection.

        The effect depends on the rate-coded or spiking nature of the projection:

        * **Rate-coded**: the updating of all synaptic variables is disabled (including the weights ``w``). This is equivalent to ``proj.update = False``.

        * **Spiking**: the updating of the weights ``w`` is disabled, but all other variables are updated. This is equivalent to ``proj.plasticity = False``.

        This method is useful when performing some tests on a trained network without messing with the learned weights.
        """
        try:
            if self.synapse_type.type == 'rate':
                self.cyInstance._set_update(False)
            else:
                self.cyInstance._set_plasticity(False)
        except:
            Global._warning('disabling learning is only possible after compile().')


    ################################
    ## Methods on connectivity matrix
    ################################

    def save_connectivity(self, filename):
        """
        Saves the connectivity of the projection into a file.

        Only the connectivity matrix, the weights and delays are saved, not the other synaptic variables.

        The generated data can be used to create a projection in another network:

        ```python
        proj.connect_from_file(filename)
        ```

        * If the file name is '.npz', the data will be saved and compressed using `np.savez_compressed` (recommended).

        * If the file name ends with '.gz', the data will be pickled into a binary file and compressed using gzip.

        * If the file name is '.mat', the data will be saved as a Matlab 7.2 file. Scipy must be installed.

        * Otherwise, the data will be pickled into a simple binary text file using pickle.

        :param filename: file name, may contain relative or absolute path.

        """
        # Check that the network is compiled
        if not self.initialized:
            Global._error('save_connectivity(): the network has not been compiled yet.')
            return

        # Check if the repertory exist
        (path, fname) = os.path.split(filename)

        if not path == '':
            if not os.path.isdir(path):
                Global._print('Creating folder', path)
                os.mkdir(path)

        extension = os.path.splitext(fname)[1]

        # Gathering the data
        data = {
            'name': self.name,
            'post_ranks': self.post_ranks,
            'pre_ranks': np.array(self.cyInstance.pre_rank_all(), dtype=object),
            'w': np.array(self.w, dtype=object),
            'delay': np.array(self.cyInstance.get_delay(), dtype=object) if hasattr(self.cyInstance, 'get_delay') else None,
            'max_delay': self.max_delay,
            'uniform_delay': self.uniform_delay,
            'size': self.size,
            'nb_synapses': self.cyInstance.nb_synapses()
        }

        # Save the data
        if extension == '.gz':
            Global._print("Saving connectivity in gunzipped binary format...")
            try:
                import gzip
            except:
                Global._error('gzip is not installed.')
                return
            with gzip.open(filename, mode = 'wb') as w_file:
                try:
                    pickle.dump(data, w_file, protocol=pickle.HIGHEST_PROTOCOL)
                except Exception as e:
                    Global._print('Error while saving in gzipped binary format.')
                    Global._print(e)
                    return

        elif extension == '.npz':
            Global._print("Saving connectivity in Numpy format...")
            np.savez_compressed(filename, **data )

        elif extension == '.mat':
            Global._print("Saving connectivity in Matlab format...")
            if data['delay'] is None:
                data['delay'] = 0
            try:
                import scipy.io as sio
                sio.savemat(filename, data)
            except Exception as e:
                Global._error('Error while saving in Matlab format.')
                Global._print(e)
                return

        else:
            Global._print("Saving connectivity in text format...")
            # save in Pythons pickle format
            with open(filename, mode = 'wb') as w_file:
                try:
                    pickle.dump(data, w_file, protocol=pickle.HIGHEST_PROTOCOL)
                except Exception as e:
                    Global._print('Error while saving in text format.')
                    Global._print(e)
                    return
            return

    def receptive_fields(self, variable = 'w', in_post_geometry = True):
        """
        Gathers all receptive fields within this projection.

        :param variable: name of the variable
        :param in_post_geometry: if False, the data will be plotted as square grid. (default = True)
        """
        if in_post_geometry:
            x_size = self.post.geometry[1]
            y_size = self.post.geometry[0]
        else:
            x_size = int( math.floor(math.sqrt(self.post.size)) )
            y_size = int( math.ceil(math.sqrt(self.post.size)) )


        def get_rf(rank): # TODO: IMPROVE
            res = np.zeros( self.pre.size )
            for n in range(len(self.post_ranks)):
                if self.post_ranks[n] == n:
                    pre_ranks = self.cyInstance.pre_rank(n)
                    data = self.cyInstance.get_local_attribute_row(variable, rank, Global.config["precision"])
                    for j in range(len(pre_ranks)):
                        res[pre_ranks[j]] = data[j]
            return res.reshape(self.pre.geometry)

        res = np.zeros((1, x_size*self.pre.geometry[1]))
        for y in range ( y_size ):
            row = np.concatenate(  [ get_rf(self.post.rank_from_coordinates( (y, x) ) ) for x in range ( x_size ) ], axis = 1)
            res = np.concatenate((res, row))

        return res

    def connectivity_matrix(self, fill=0.0):
        """
        Returns a dense connectivity matrix (2D Numpy array) representing the connections between the pre- and post-populations.

        The first index of the matrix represents post-synaptic neurons, the second the pre-synaptic ones.

        If PopulationViews were used for creating the projection, the matrix is expanded to the whole populations by default.

        :param fill: value to put in the matrix when there is no connection (default: 0.0).
        """
        if not self.initialized:
            Global._error('The connectivity matrix can only be accessed after compilation')

        # get correct dimensions for dense matrix
        if isinstance(self.pre, PopulationView):
            size_pre = self.pre.population.size
        else:
            size_pre = self.pre.size
        if isinstance(self.post, PopulationView):
            size_post = self.post.population.size
        else:
            size_post = self.post.size

        # create empty dense matrix with default values
        res = np.ones((size_post, size_pre)) * fill

        # fill row-by-row with real values
        for rank in self.post_ranks:
            # row-rank
            if self._storage_format == "dense":
                idx = rank
            else:
                idx =  self.post_ranks.index(rank)
            # pre-ranks
            preranks = self.cyInstance.pre_rank(idx)
            # get the values
            if "w" in self.synapse_type.description['local'] and (not self._has_single_weight()):
                w = self.cyInstance.get_local_attribute_row("w", idx, Global.config["precision"])
            elif "w" in self.synapse_type.description['semiglobal']:
                w = self.cyInstance.get_semiglobal_attribute("w", idx, Global.config["precision"])*np.ones(self.cyInstance.dendrite_size(idx))
            else:
                w = self.cyInstance.get_global_attribute("w", Global.config["precision"])*np.ones(self.cyInstance.dendrite_size(idx))
            res[rank, preranks] = w
        return res


    ################################
    ## Save/load methods
    ################################

    def _data(self):
        "Method gathering all info about the projection when calling save()"

        if not self.initialized:
            Global._error('save_connectivity(): the network has not been compiled yet.')

        desc = {}
        desc['name'] = self.name
        desc['pre'] = self.pre.name
        desc['post'] = self.post.name
        desc['target'] = self.target
        desc['post_ranks'] = self.post_ranks
        desc['attributes'] = self.attributes
        desc['parameters'] = self.parameters
        desc['variables'] = self.variables
        desc['delays'] = self._get_delay()

        # Determine if we have varying number of elements per row
        # based on the pre-synaptic ranks
        pre_ranks = self.cyInstance.pre_rank_all()
        dend_size = len(pre_ranks[0])
        ragged_list = False
        for i in range(1, len(pre_ranks)):
            if len(pre_ranks[i]) != dend_size:
                ragged_list = True
                break

        # Save pre_ranks
        if ragged_list:
            desc['pre_ranks'] = np.array(self.cyInstance.pre_rank_all(), dtype=object)
        else:
            desc['pre_ranks'] = np.array(self.cyInstance.pre_rank_all())

        # Attributes to save
        attributes = self.attributes
        if not 'w' in self.attributes:
            attributes.append('w')

        # Save all attributes
        for var in attributes:
            try:
                ctype = self._get_attribute_cpp_type(var)
                if var == "w" and self._has_single_weight():
                    desc[var] = self.cyInstance.get_global_attribute("w", ctype)

                elif var in self.synapse_type.description['local']:
                    if ragged_list:
                        desc[var] = np.array(self.cyInstance.get_local_attribute_all(var, ctype), dtype=object)
                    else:
                        desc[var] = self.cyInstance.get_local_attribute_all(var, ctype)
                elif var in self.synapse_type.description['semiglobal']:
                    desc[var] = self.cyInstance.get_semiglobal_attribute_all(var, ctype)
                else:
                    desc[var] = self.cyInstance.get_global_attribute(var, ctype) # linear array or single constant
            except:
                Global._warning('Can not save the attribute ' + var + ' in the projection.')

        return desc

    def save(self, filename):
        """
        Saves all information about the projection (connectivity, current value of parameters and variables) into a file.

        * If the file name is '.npz', the data will be saved and compressed using `np.savez_compressed` (recommended).

        * If the file name ends with '.gz', the data will be pickled into a binary file and compressed using gzip.

        * If the file name is '.mat', the data will be saved as a Matlab 7.2 file. Scipy must be installed.

        * Otherwise, the data will be pickled into a simple binary text file using pickle.

        :param filename: file name, may contain relative or absolute path.

        **Warning:** the '.mat' data will not be loadable by ANNarchy, it is only for external analysis purpose.

        Example:

        ```python
        proj.save('proj1.npz')
        proj.save('proj1.txt')
        proj.save('proj1.txt.gz')
        proj.save('proj1.mat')
        ```
        """
        from ANNarchy.core.IO import _save_data
        _save_data(filename, self._data())


    def load(self, filename, pickle_encoding=None):
        """
        Loads the saved state of the projection by `Projection.save()`.

        Warning: Matlab data can not be loaded.

        Example:

        ```python
        proj.load('proj1.npz')
        proj.load('proj1.txt')
        proj.load('proj1.txt.gz')
        ```

        :param filename: the file name with relative or absolute path.
        """
        from ANNarchy.core.IO import _load_connectivity_data
        self._load_proj_data(_load_connectivity_data(filename, pickle_encoding))


    def _load_proj_data(self, desc):
        """
        Updates the projection with the stored data set.
        """
        # Sanity check
        if desc == None:
            # _load_proj should have printed an error message
            return

        # If it's not saveable there is nothing to load
        if not self._saveable:
            return

        # Check deprecation
        if not 'attributes' in desc.keys():
            Global._error('The file was saved using a deprecated version of ANNarchy.')
            return
        if 'dendrites' in desc: # Saved before 4.5.3
            Global._error("The file was saved using a deprecated version of ANNarchy.")
            return

        # If the post ranks and/or pre-ranks have changed, overwrite
        connectivity_changed=False
        if 'post_ranks' in desc and not np.all((desc['post_ranks']) == self.post_ranks):
            connectivity_changed=True
        if 'pre_ranks' in desc and not np.all((desc['pre_ranks']) == np.array(self.cyInstance.pre_rank_all(), dtype=object)):
            connectivity_changed=True

        # synaptic weights
        weights = desc["w"]

        # Delays can be either uniform (int, float) or non-uniform (np.ndarray).
        # HD (30th May 2022):
        #   Unfortunately, the storage of constants changed over the time. At the
        #   end of this code block, we should have either a single constant or a
        #   numpy nd-array
        delays = 0
        if 'delays' in desc:
            delays = desc['delays']

            if isinstance(delays, (float, int)):
                # will be handled below
                pass

            elif isinstance(delays, np.ndarray):
                # constants are stored as 0-darray
                if delays.ndim == 0:
                    # transform into single float
                    delays = float(delays)
                else:
                    # nothing to do as it is numpy nd-array
                    pass

            else:
                # ragged list to nd-array
                delays = np.array(delays, dtype=object)

        # Some patterns like fixed_number_pre/post or fixed_probability change the
        # connectivity. If this is not the case, we can simply set the values.
        if connectivity_changed:
            # (re-)initialize connectivity
            if isinstance(delays, (float, int)):
                delays = [[delays]] # wrapper expects list from list

            self.cyInstance.init_from_lil(desc['post_ranks'], desc['pre_ranks'], weights, delays)
        else:
            # set weights
            self._set_cython_attribute("w", weights)

            # set delays if there were some
            self._set_delay(delays)

        # Other variables
        for var in desc['attributes']:
            if var == "w":
                continue # already done

            try:
                self._set_cython_attribute(var, desc[var])
            except Exception as e:
                Global._print(e)
                Global._warning('load(): the variable', var, 'does not exist in the current version of the network, skipping it.')
                continue

    ################################
    ## Structural plasticity
    ################################
    def start_pruning(self, period=None):
        """
        Starts pruning the synapses in the projection if the synapse defines a 'pruning' argument.

        'structural_plasticity' must be set to True in setup().

        :param period: how often pruning should be evaluated (default: dt, i.e. each step)
        """
        if not period:
            period = Global.config['dt']
        if not self.cyInstance:
            Global._error('Can not start pruning if the network is not compiled.')

        if Global.config['structural_plasticity']:
            try:
                self.cyInstance.start_pruning(int(period/Global.config['dt']), Global.get_current_step())
            except :
                Global._error("The synapse does not define a 'pruning' argument.")

        else:
            Global._error("You must set 'structural_plasticity' to True in setup() to start pruning connections.")


    def stop_pruning(self):
        """
        Stops pruning the synapses in the projection if the synapse defines a 'pruning' argument.

        'structural_plasticity' must be set to True in setup().
        """
        if not self.cyInstance:
            Global._error('Can not stop pruning if the network is not compiled.')

        if Global.config['structural_plasticity']:
            try:
                self.cyInstance.stop_pruning()
            except:
                Global._error("The synapse does not define a 'pruning' argument.")

        else:
            Global._error("You must set 'structural_plasticity' to True in setup() to start pruning connections.")

    def start_creating(self, period=None):
        """
        Starts creating the synapses in the projection if the synapse defines a 'creating' argument.

        'structural_plasticity' must be set to True in setup().

        :param period: how often creating should be evaluated (default: dt, i.e. each step)
        """
        if not period:
            period = Global.config['dt']
        if not self.cyInstance:
            Global._error('Can not start creating if the network is not compiled.')

        if Global.config['structural_plasticity']:
            try:
                self.cyInstance.start_creating(int(period/Global.config['dt']), Global.get_current_step())
            except:
                Global._error("The synapse does not define a 'creating' argument.")

        else:
            Global._error("You must set 'structural_plasticity' to True in setup() to start creating connections.")

    def stop_creating(self):
        """
        Stops creating the synapses in the projection if the synapse defines a 'creating' argument.

        'structural_plasticity' must be set to True in setup().
        """
        if not self.cyInstance:
            Global._error('Can not stop creating if the network is not compiled.')

        if Global.config['structural_plasticity']:
            try:
                self.cyInstance.stop_creating()
            except:
                Global._error("The synapse does not define a 'creating' argument.")

        else:
            Global._error("You must set 'structural_plasticity' to True in setup() to start creating connections.")

    ################################
    # Paradigm specific functions
    ################################
    def update_launch_config(self, nb_blocks=-1, threads_per_block=32):
        """
        Since ANNarchy 4.7.2 we allow the adjustment of the CUDA launch config.

        Parameters:

        :nb_blocks:         number of CUDA blocks which can be 65535 at maximum. If set to -1 the number
                            of launched blocks is computed by ANNarchy.
        :threads_per_block: number of CUDA threads for one block which can be maximum 1024.
        """
        if not Global._check_paradigm("cuda"):
            Global._warning("Projection.update_launch_config() is intended for usage on CUDA devices")
            return

        if self.initialized:
            self.cyInstance.update_launch_config(nb_blocks=nb_blocks, threads_per_block=threads_per_block)
        else:
            Global._error("Projection.update_launch_config() should be called after compile()")

    ################################
    ## Memory Management
    ################################
    def size_in_bytes(self):
        """
        Returns the size in bytes of the allocated memory on C++ side. Note that this does not reflect monitored data and that it only works after compile() was invoked.
        """
        if self.initialized:
            return self.cyInstance.size_in_bytes()
        else:
            return 0

    def _clear(self):
        """
        Deallocates the container within the C++ instance. The population object is not usable anymore after calling this function.

        Warning: should be only called by the net deconstructor (in the context of parallel_run).
        """
        if self.initialized:
            self.cyInstance.clear()
            self.initialized = False

dendrites property #

Iteratively returns the dendrites corresponding to this projection.

nb_synapses property #

Total number of synapses in the projection.

size property #

Number of post-synaptic neurons receiving synapses.

__init__(pre, post, target, synapse=None, name=None, disable_omp=True, copied=False) #

By default, the synapse only ensures linear synaptic transmission:

  • For rate-coded populations: psp = w * pre.r
  • For spiking populations: g_target += w

to modify this behavior one need to provide a Synapse object.

Parameters:

  • pre

    pre-synaptic population (either its name or a Population object).

  • post

    post-synaptic population (either its name or a Population object).

  • target

    type of the connection.

  • synapse

    a Synapse instance.

  • name

    unique name of the projection (optional, it defaults to proj0, proj1, etc).

  • disable_omp

    especially for small- and mid-scale sparse spiking networks the parallelization of spike propagation is not scalable. But it can be enabled by setting this parameter to False.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
 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
def __init__(self, pre, post, target, synapse=None, name=None, disable_omp=True, copied=False):
    """
    By default, the synapse only ensures linear synaptic transmission:

    * For rate-coded populations: ``psp = w * pre.r``
    * For spiking populations: ``g_target += w``

    to modify this behavior one need to provide a Synapse object.

    :param pre: pre-synaptic population (either its name or a ``Population`` object).
    :param post: post-synaptic population (either its name or a ``Population`` object).
    :param target: type of the connection.
    :param synapse: a ``Synapse`` instance.
    :param name: unique name of the projection (optional, it defaults to ``proj0``, ``proj1``, etc).
    :param disable_omp: especially for small- and mid-scale sparse spiking networks the parallelization of spike propagation is not scalable. But it can be enabled by setting this parameter to `False`.
    """
    # Check if the network has already been compiled
    if Global._network[0]['compiled'] and not copied:
        Global._error('you cannot add a projection after the network has been compiled.')

    # Store the pre and post synaptic populations
    # the user provide either a string or a population object
    # in case of string, we need to search for the corresponding object
    if isinstance(pre, str):
        for pop in Global._network[0]['populations']:
            if pop.name == pre:
                self.pre = pop
    else:
        self.pre = pre

    if isinstance(post, str):
        for pop in Global._network[0]['populations']:
            if pop.name == post:
                self.post = pop
    else:
        self.post = post

    # Store the arguments
    if isinstance(target, list) and len(target) == 1:
        self.target = target[0]
    else:
        self.target = target

    # Add the target(s) to the postsynaptic population
    if isinstance(self.target, list):
        for _target in self.target:
            self.post.targets.append(_target)
    else:
        self.post.targets.append(self.target)

    # check if a synapse description is attached
    if not synapse:
        # No synapse attached assume default synapse based on
        # presynaptic population.
        if self.pre.neuron_type.type == 'rate':
            from ANNarchy.models.Synapses import DefaultRateCodedSynapse
            self.synapse_type = DefaultRateCodedSynapse()
            self.synapse_type.type = 'rate'
        else:
            from ANNarchy.models.Synapses import DefaultSpikingSynapse
            self.synapse_type = DefaultSpikingSynapse()
            self.synapse_type.type = 'spike'

    elif inspect.isclass(synapse):
        self.synapse_type = synapse()
        self.synapse_type.type = self.pre.neuron_type.type
    else:
        self.synapse_type = copy.deepcopy(synapse)
        self.synapse_type.type = self.pre.neuron_type.type

    # Disable omp for spiking networks
    self.disable_omp = disable_omp

    # Analyse the parameters and variables
    self.synapse_type._analyse()

    # Create a default name
    self.id = len(Global._network[0]['projections'])
    if name:
        self.name = name
    else:
        self.name = 'proj'+str(self.id)

    # Container for control/attribute states
    self.init = {}

    # Control-flow variables
    self.init["transmission"] = True
    self.init["update"] = True
    self.init["plasticity"] = True

    # Get a list of parameters and variables
    self.parameters = []
    for param in self.synapse_type.description['parameters']:
        self.parameters.append(param['name'])
        self.init[param['name']] = param['init']

    self.variables = []
    for var in self.synapse_type.description['variables']:
        self.variables.append(var['name'])
        self.init[var['name']] = var['init']

    self.attributes = self.parameters + self.variables

    # Get a list of user-defined functions
    self.functions = [func['name'] for func in self.synapse_type.description['functions']]

    # Add the population to the global network
    Global._network[0]['projections'].append(self)

    # Finalize initialization
    self.initialized = False

    # Cython instance
    self.cyInstance = None

    # Connectivity
    self._synapses = None
    self._connection_method = None
    self._connection_args = None
    self._connection_delay = None
    self._connector = None
    self._lil_connectivity = None

    # Default configuration for connectivity
    self._storage_format = "lil"
    self._storage_order = "post_to_pre"

    # If a single weight value is used
    self._single_constant_weight = False

    # Are random distribution used for weights/delays
    self.connector_weight_dist = None
    self.connector_delay_dist = None

    # Reporting
    self.connector_name = "Specific"
    self.connector_description = "Specific"

    # Overwritten by derived classes, to add
    # additional code
    self._specific_template = {}

    # Set to False by derived classes to prevent saving of
    # data, e. g. in case of weight-sharing projections
    self._saveable = True

    # To allow case-specific adjustment of parallelization
    # parameters, e. g. openMP schedule, we introduce a
    # dictionary read by the ProjectionGenerator.
    #
    # Will be overwritten either by inherited classes or
    # by an omp_config provided to the compile() method.
    self._omp_config = {
        #'psp_schedule': 'schedule(dynamic)'
    }

    # If set to true, the code generator is not allowed to
    # split the matrix. This will be the case for many
    # SpecificProjections defined by the user or is disabled
    # globally.
    if self.synapse_type.type == "rate":
        # Normally, the split should not be used for rate-coded models
        # but maybe there are cases where we want to enable it ...
        self._no_split_matrix = Global.config["disable_split_matrix"]

        # If the number of elements is too small, the split
        # might not be efficient.
        if self.post.size < Global.OMP_MIN_NB_NEURONS:
            self._no_split_matrix = True

    else:
        # If the number of elements is too small, the split
        # might not be efficient.
        if self.post.size < Global.OMP_MIN_NB_NEURONS:
            self._no_split_matrix = True
        else:
            self._no_split_matrix = Global.config["disable_split_matrix"]

    # In particular for spiking models, the parallelization on the
    # inner or outer loop can make a performance difference
    if self._no_split_matrix:
        # LIL and CSR are parallelized on inner loop
        # to prevent cost of atomic operations
        self._parallel_pattern = 'inner_loop'
    else:
        # splitted matrices are always parallelized on outer loop!
        self._parallel_pattern = 'outer_loop'

    # For dense matrix format: do we use an optimization for population views?
    if self.synapse_type.type == "rate":
        # HD (9th Nov. 2022): currently this optimization is only intended for spiking models
        self._has_pop_view = False
    else:
        # HD (9th Nov. 2022): currently disabled, more testing is required ...
        self._has_pop_view = False #isinstance(self.pre, PopulationView) or isinstance(self.post, PopulationView)

connectivity_matrix(fill=0.0) #

Returns a dense connectivity matrix (2D Numpy array) representing the connections between the pre- and post-populations.

The first index of the matrix represents post-synaptic neurons, the second the pre-synaptic ones.

If PopulationViews were used for creating the projection, the matrix is expanded to the whole populations by default.

Parameters:

  • fill

    value to put in the matrix when there is no connection (default: 0.0).

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
def connectivity_matrix(self, fill=0.0):
    """
    Returns a dense connectivity matrix (2D Numpy array) representing the connections between the pre- and post-populations.

    The first index of the matrix represents post-synaptic neurons, the second the pre-synaptic ones.

    If PopulationViews were used for creating the projection, the matrix is expanded to the whole populations by default.

    :param fill: value to put in the matrix when there is no connection (default: 0.0).
    """
    if not self.initialized:
        Global._error('The connectivity matrix can only be accessed after compilation')

    # get correct dimensions for dense matrix
    if isinstance(self.pre, PopulationView):
        size_pre = self.pre.population.size
    else:
        size_pre = self.pre.size
    if isinstance(self.post, PopulationView):
        size_post = self.post.population.size
    else:
        size_post = self.post.size

    # create empty dense matrix with default values
    res = np.ones((size_post, size_pre)) * fill

    # fill row-by-row with real values
    for rank in self.post_ranks:
        # row-rank
        if self._storage_format == "dense":
            idx = rank
        else:
            idx =  self.post_ranks.index(rank)
        # pre-ranks
        preranks = self.cyInstance.pre_rank(idx)
        # get the values
        if "w" in self.synapse_type.description['local'] and (not self._has_single_weight()):
            w = self.cyInstance.get_local_attribute_row("w", idx, Global.config["precision"])
        elif "w" in self.synapse_type.description['semiglobal']:
            w = self.cyInstance.get_semiglobal_attribute("w", idx, Global.config["precision"])*np.ones(self.cyInstance.dendrite_size(idx))
        else:
            w = self.cyInstance.get_global_attribute("w", Global.config["precision"])*np.ones(self.cyInstance.dendrite_size(idx))
        res[rank, preranks] = w
    return res

dendrite(post) #

Returns the dendrite of a postsynaptic neuron according to its rank.

Parameters:

  • post

    can be either the rank or the coordinates of the post-synaptic neuron.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
def dendrite(self, post):
    """
    Returns the dendrite of a postsynaptic neuron according to its rank.

    :param post: can be either the rank or the coordinates of the post-synaptic neuron.
    """
    if not self.initialized:
        Global._error('dendrites can only be accessed after compilation.')

    if isinstance(post, int):
        rank = post
    else:
        rank = self.post.rank_from_coordinates(post)

    if rank in self.post_ranks:
        return Dendrite(self, rank, self.post_ranks.index(rank))
    else:
        Global._error(" The neuron of rank "+ str(rank) + " has no dendrite in this projection.", exit=True)

disable_learning(update=None) #

Disables learning for all synapses of this projection.

The effect depends on the rate-coded or spiking nature of the projection:

  • Rate-coded: the updating of all synaptic variables is disabled (including the weights w). This is equivalent to proj.update = False.

  • Spiking: the updating of the weights w is disabled, but all other variables are updated. This is equivalent to proj.plasticity = False.

This method is useful when performing some tests on a trained network without messing with the learned weights.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
def disable_learning(self, update=None):
    """
    Disables learning for all synapses of this projection.

    The effect depends on the rate-coded or spiking nature of the projection:

    * **Rate-coded**: the updating of all synaptic variables is disabled (including the weights ``w``). This is equivalent to ``proj.update = False``.

    * **Spiking**: the updating of the weights ``w`` is disabled, but all other variables are updated. This is equivalent to ``proj.plasticity = False``.

    This method is useful when performing some tests on a trained network without messing with the learned weights.
    """
    try:
        if self.synapse_type.type == 'rate':
            self.cyInstance._set_update(False)
        else:
            self.cyInstance._set_plasticity(False)
    except:
        Global._warning('disabling learning is only possible after compile().')

enable_learning(period=None, offset=None) #

Enables learning for all the synapses of this projection.

For example, providing the following parameters at time 10 ms:

enable_learning(period=10., offset=5.)

would call the updating methods at times 15, 25, 35, etc...

The default behaviour is that the synaptic variables are updated at each time step. The parameters must be multiple of dt.

Parameters:

  • period

    determines how often the synaptic variables will be updated.

  • offset

    determines the offset at which the synaptic variables will be updated relative to the current time.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
def enable_learning(self, period=None, offset=None):
    """
    Enables learning for all the synapses of this projection.

    For example, providing the following parameters at time 10 ms:

    ```python
    enable_learning(period=10., offset=5.)
    ```

    would call the updating methods at times 15, 25, 35, etc...

    The default behaviour is that the synaptic variables are updated at each time step. The parameters must be multiple of ``dt``.

    :param period: determines how often the synaptic variables will be updated.
    :param offset: determines the offset at which the synaptic variables will be updated relative to the current time.

    """
    # Check arguments
    if not period is None and not offset is None:
        if offset >= period:
            Global._error('enable_learning(): the offset must be smaller than the period.')

    if period is None and not offset is None:
        Global._error('enable_learning(): if you define an offset, you have to define a period.')

    try:
        self.cyInstance._set_update(True)
        self.cyInstance._set_plasticity(True)
        if period != None:
            self.cyInstance._set_update_period(int(period/Global.config['dt']))
        else:
            self.cyInstance._set_update_period(int(1))
            period = Global.config['dt']
        if offset != None:
            relative_offset = Global.get_time() % period + offset
            self.cyInstance._set_update_offset(int(int(relative_offset%period)/Global.config['dt']))
        else:
            self.cyInstance._set_update_offset(int(0))
    except:
        Global._warning('Enable_learning() is only possible after compile()')

get(name) #

Returns a list of parameters/variables values for each dendrite in the projection.

The list will have the same length as the number of actual dendrites (self.size), so it can be smaller than the size of the postsynaptic population. Use self.post_ranks to indice it.

Parameters:

  • name

    the name of the parameter or variable

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
702
703
704
705
706
707
708
709
710
def get(self, name):
    """
    Returns a list of parameters/variables values for each dendrite in the projection.

    The list will have the same length as the number of actual dendrites (self.size), so it can be smaller than the size of the postsynaptic population. Use self.post_ranks to indice it.

    :param name: the name of the parameter or variable
    """
    return self.__getattr__(name)

load(filename, pickle_encoding=None) #

Loads the saved state of the projection by Projection.save().

Warning: Matlab data can not be loaded.

Example:

proj.load('proj1.npz')
proj.load('proj1.txt')
proj.load('proj1.txt.gz')

Parameters:

  • filename

    the file name with relative or absolute path.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
def load(self, filename, pickle_encoding=None):
    """
    Loads the saved state of the projection by `Projection.save()`.

    Warning: Matlab data can not be loaded.

    Example:

    ```python
    proj.load('proj1.npz')
    proj.load('proj1.txt')
    proj.load('proj1.txt.gz')
    ```

    :param filename: the file name with relative or absolute path.
    """
    from ANNarchy.core.IO import _load_connectivity_data
    self._load_proj_data(_load_connectivity_data(filename, pickle_encoding))

nb_efferent_synapses() #

Number of efferent connections. Intended only for spiking models.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
626
627
628
629
630
631
632
633
634
def nb_efferent_synapses(self):
    "Number of efferent connections. Intended only for spiking models."
    if self.cyInstance is None:
         Global._warning("Access 'nb_efferent_synapses()' of a Projection is only valid after compile()")
         return None
    if self.synapse_type.type == "rate":
        Global._error("Projection.nb_efferent_synapses() is not available for rate-coded projections.")

    return self.cyInstance.nb_efferent_synapses()

nb_synapses_per_dendrite() #

Total number of synapses for each dendrite as a list.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
619
620
621
622
623
624
def nb_synapses_per_dendrite(self):
    "Total number of synapses for each dendrite as a list."
    if self.cyInstance is None:
        Global._warning("Access 'nb_synapses_per_dendrite' attribute of a Projection is only valid after compile()")
        return []
    return [self.cyInstance.dendrite_size(n) for n in range(self.size)]

receptive_fields(variable='w', in_post_geometry=True) #

Gathers all receptive fields within this projection.

Parameters:

  • variable

    name of the variable

  • in_post_geometry

    if False, the data will be plotted as square grid. (default = True)

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
def receptive_fields(self, variable = 'w', in_post_geometry = True):
    """
    Gathers all receptive fields within this projection.

    :param variable: name of the variable
    :param in_post_geometry: if False, the data will be plotted as square grid. (default = True)
    """
    if in_post_geometry:
        x_size = self.post.geometry[1]
        y_size = self.post.geometry[0]
    else:
        x_size = int( math.floor(math.sqrt(self.post.size)) )
        y_size = int( math.ceil(math.sqrt(self.post.size)) )


    def get_rf(rank): # TODO: IMPROVE
        res = np.zeros( self.pre.size )
        for n in range(len(self.post_ranks)):
            if self.post_ranks[n] == n:
                pre_ranks = self.cyInstance.pre_rank(n)
                data = self.cyInstance.get_local_attribute_row(variable, rank, Global.config["precision"])
                for j in range(len(pre_ranks)):
                    res[pre_ranks[j]] = data[j]
        return res.reshape(self.pre.geometry)

    res = np.zeros((1, x_size*self.pre.geometry[1]))
    for y in range ( y_size ):
        row = np.concatenate(  [ get_rf(self.post.rank_from_coordinates( (y, x) ) ) for x in range ( x_size ) ], axis = 1)
        res = np.concatenate((res, row))

    return res

reset(attributes=-1, synapses=False) #

Resets all parameters and variables of the projection to their initial value (before the call to compile()).

Parameters:

  • attributes

    list of attributes (parameter or variable) which should be reinitialized. Default: all attributes (-1).

  • synapses

    defines if the weights and delays should also be recreated. Default: False

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
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
def reset(self, attributes=-1, synapses=False):
    """
    Resets all parameters and variables of the projection to their initial value (before the call to compile()).

    :param attributes: list of attributes (parameter or variable) which should be reinitialized. Default: all attributes (-1).
    :param synapses: defines if the weights and delays should also be recreated. Default: False
    """
    if attributes == -1:
        attributes = self.attributes

    if synapses:
        # destroy the previous C++ content
        self._clear()
        # call the init connectivity again
        self.initialized = self._connect(None)

    for var in attributes:
        # Skip w
        if var=='w':
            continue
        # check it exists
        if not var in self.attributes:
            Global._warning("Projection.reset():", var, "is not an attribute of the population, won't reset.")
            continue
        # Set the value
        try:
            self.__setattr__(var, self.init[var])
        except Exception as e:
            Global._print(e)
            Global._warning("Projection.reset(): something went wrong while resetting", var)

save(filename) #

Saves all information about the projection (connectivity, current value of parameters and variables) into a file.

  • If the file name is '.npz', the data will be saved and compressed using np.savez_compressed (recommended).

  • If the file name ends with '.gz', the data will be pickled into a binary file and compressed using gzip.

  • If the file name is '.mat', the data will be saved as a Matlab 7.2 file. Scipy must be installed.

  • Otherwise, the data will be pickled into a simple binary text file using pickle.

Parameters:

  • filename

    file name, may contain relative or absolute path. Warning: the '.mat' data will not be loadable by ANNarchy, it is only for external analysis purpose. Example: python proj.save('proj1.npz') proj.save('proj1.txt') proj.save('proj1.txt.gz') proj.save('proj1.mat')

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
def save(self, filename):
    """
    Saves all information about the projection (connectivity, current value of parameters and variables) into a file.

    * If the file name is '.npz', the data will be saved and compressed using `np.savez_compressed` (recommended).

    * If the file name ends with '.gz', the data will be pickled into a binary file and compressed using gzip.

    * If the file name is '.mat', the data will be saved as a Matlab 7.2 file. Scipy must be installed.

    * Otherwise, the data will be pickled into a simple binary text file using pickle.

    :param filename: file name, may contain relative or absolute path.

    **Warning:** the '.mat' data will not be loadable by ANNarchy, it is only for external analysis purpose.

    Example:

    ```python
    proj.save('proj1.npz')
    proj.save('proj1.txt')
    proj.save('proj1.txt.gz')
    proj.save('proj1.mat')
    ```
    """
    from ANNarchy.core.IO import _save_data
    _save_data(filename, self._data())

save_connectivity(filename) #

Saves the connectivity of the projection into a file.

Only the connectivity matrix, the weights and delays are saved, not the other synaptic variables.

The generated data can be used to create a projection in another network:

proj.connect_from_file(filename)
  • If the file name is '.npz', the data will be saved and compressed using np.savez_compressed (recommended).

  • If the file name ends with '.gz', the data will be pickled into a binary file and compressed using gzip.

  • If the file name is '.mat', the data will be saved as a Matlab 7.2 file. Scipy must be installed.

  • Otherwise, the data will be pickled into a simple binary text file using pickle.

Parameters:

  • filename

    file name, may contain relative or absolute path.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
def save_connectivity(self, filename):
    """
    Saves the connectivity of the projection into a file.

    Only the connectivity matrix, the weights and delays are saved, not the other synaptic variables.

    The generated data can be used to create a projection in another network:

    ```python
    proj.connect_from_file(filename)
    ```

    * If the file name is '.npz', the data will be saved and compressed using `np.savez_compressed` (recommended).

    * If the file name ends with '.gz', the data will be pickled into a binary file and compressed using gzip.

    * If the file name is '.mat', the data will be saved as a Matlab 7.2 file. Scipy must be installed.

    * Otherwise, the data will be pickled into a simple binary text file using pickle.

    :param filename: file name, may contain relative or absolute path.

    """
    # Check that the network is compiled
    if not self.initialized:
        Global._error('save_connectivity(): the network has not been compiled yet.')
        return

    # Check if the repertory exist
    (path, fname) = os.path.split(filename)

    if not path == '':
        if not os.path.isdir(path):
            Global._print('Creating folder', path)
            os.mkdir(path)

    extension = os.path.splitext(fname)[1]

    # Gathering the data
    data = {
        'name': self.name,
        'post_ranks': self.post_ranks,
        'pre_ranks': np.array(self.cyInstance.pre_rank_all(), dtype=object),
        'w': np.array(self.w, dtype=object),
        'delay': np.array(self.cyInstance.get_delay(), dtype=object) if hasattr(self.cyInstance, 'get_delay') else None,
        'max_delay': self.max_delay,
        'uniform_delay': self.uniform_delay,
        'size': self.size,
        'nb_synapses': self.cyInstance.nb_synapses()
    }

    # Save the data
    if extension == '.gz':
        Global._print("Saving connectivity in gunzipped binary format...")
        try:
            import gzip
        except:
            Global._error('gzip is not installed.')
            return
        with gzip.open(filename, mode = 'wb') as w_file:
            try:
                pickle.dump(data, w_file, protocol=pickle.HIGHEST_PROTOCOL)
            except Exception as e:
                Global._print('Error while saving in gzipped binary format.')
                Global._print(e)
                return

    elif extension == '.npz':
        Global._print("Saving connectivity in Numpy format...")
        np.savez_compressed(filename, **data )

    elif extension == '.mat':
        Global._print("Saving connectivity in Matlab format...")
        if data['delay'] is None:
            data['delay'] = 0
        try:
            import scipy.io as sio
            sio.savemat(filename, data)
        except Exception as e:
            Global._error('Error while saving in Matlab format.')
            Global._print(e)
            return

    else:
        Global._print("Saving connectivity in text format...")
        # save in Pythons pickle format
        with open(filename, mode = 'wb') as w_file:
            try:
                pickle.dump(data, w_file, protocol=pickle.HIGHEST_PROTOCOL)
            except Exception as e:
                Global._print('Error while saving in text format.')
                Global._print(e)
                return
        return

set(value) #

Sets the parameters/variables values for each dendrite in the projection.

For parameters, you can provide:

  • a single value, which will be the same for all dendrites.

  • a list or 1D numpy array of the same length as the number of actual dendrites (self.size).

For variables, you can provide:

  • a single value, which will be the same for all synapses of all dendrites.

  • a list or 1D numpy array of the same length as the number of actual dendrites (self.size). The synapses of each postsynaptic neuron will take the same value.

Warning: it is not possible to set different values to each synapse using this method. One should iterate over the dendrites:

for dendrite in proj.dendrites:
    dendrite.w = np.ones(dendrite.size)

Parameters:

  • value

    a dictionary with the name of the parameter/variable as key.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
def set(self, value):
    """
    Sets the parameters/variables values for each dendrite in the projection.

    For parameters, you can provide:

    * a single value, which will be the same for all dendrites.

    * a list or 1D numpy array of the same length as the number of actual dendrites (self.size).

    For variables, you can provide:

    * a single value, which will be the same for all synapses of all dendrites.

    * a list or 1D numpy array of the same length as the number of actual dendrites (self.size). The synapses of each postsynaptic neuron will take the same value.

    **Warning:** it is not possible to set different values to each synapse using this method. One should iterate over the dendrites:

    ```python
    for dendrite in proj.dendrites:
        dendrite.w = np.ones(dendrite.size)
    ```

    :param value: a dictionary with the name of the parameter/variable as key.

    """

    for name, val in value.items():
        self.__setattr__(name, val)

start_creating(period=None) #

Starts creating the synapses in the projection if the synapse defines a 'creating' argument.

'structural_plasticity' must be set to True in setup().

Parameters:

  • period

    how often creating should be evaluated (default: dt, i.e. each step)

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
def start_creating(self, period=None):
    """
    Starts creating the synapses in the projection if the synapse defines a 'creating' argument.

    'structural_plasticity' must be set to True in setup().

    :param period: how often creating should be evaluated (default: dt, i.e. each step)
    """
    if not period:
        period = Global.config['dt']
    if not self.cyInstance:
        Global._error('Can not start creating if the network is not compiled.')

    if Global.config['structural_plasticity']:
        try:
            self.cyInstance.start_creating(int(period/Global.config['dt']), Global.get_current_step())
        except:
            Global._error("The synapse does not define a 'creating' argument.")

    else:
        Global._error("You must set 'structural_plasticity' to True in setup() to start creating connections.")

start_pruning(period=None) #

Starts pruning the synapses in the projection if the synapse defines a 'pruning' argument.

'structural_plasticity' must be set to True in setup().

Parameters:

  • period

    how often pruning should be evaluated (default: dt, i.e. each step)

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
def start_pruning(self, period=None):
    """
    Starts pruning the synapses in the projection if the synapse defines a 'pruning' argument.

    'structural_plasticity' must be set to True in setup().

    :param period: how often pruning should be evaluated (default: dt, i.e. each step)
    """
    if not period:
        period = Global.config['dt']
    if not self.cyInstance:
        Global._error('Can not start pruning if the network is not compiled.')

    if Global.config['structural_plasticity']:
        try:
            self.cyInstance.start_pruning(int(period/Global.config['dt']), Global.get_current_step())
        except :
            Global._error("The synapse does not define a 'pruning' argument.")

    else:
        Global._error("You must set 'structural_plasticity' to True in setup() to start pruning connections.")

stop_creating() #

Stops creating the synapses in the projection if the synapse defines a 'creating' argument.

'structural_plasticity' must be set to True in setup().

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
def stop_creating(self):
    """
    Stops creating the synapses in the projection if the synapse defines a 'creating' argument.

    'structural_plasticity' must be set to True in setup().
    """
    if not self.cyInstance:
        Global._error('Can not stop creating if the network is not compiled.')

    if Global.config['structural_plasticity']:
        try:
            self.cyInstance.stop_creating()
        except:
            Global._error("The synapse does not define a 'creating' argument.")

    else:
        Global._error("You must set 'structural_plasticity' to True in setup() to start creating connections.")

stop_pruning() #

Stops pruning the synapses in the projection if the synapse defines a 'pruning' argument.

'structural_plasticity' must be set to True in setup().

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
def stop_pruning(self):
    """
    Stops pruning the synapses in the projection if the synapse defines a 'pruning' argument.

    'structural_plasticity' must be set to True in setup().
    """
    if not self.cyInstance:
        Global._error('Can not stop pruning if the network is not compiled.')

    if Global.config['structural_plasticity']:
        try:
            self.cyInstance.stop_pruning()
        except:
            Global._error("The synapse does not define a 'pruning' argument.")

    else:
        Global._error("You must set 'structural_plasticity' to True in setup() to start pruning connections.")

synapse(pre, post) #

Returns the synapse between a pre- and a post-synaptic neuron if it exists, None otherwise.

Parameters:

  • pre

    rank of the pre-synaptic neuron.

  • post

    rank of the post-synaptic neuron.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/Projection.py
672
673
674
675
676
677
678
679
680
681
682
def synapse(self, pre, post):
    """
    Returns the synapse between a pre- and a post-synaptic neuron if it exists, None otherwise.

    :param pre: rank of the pre-synaptic neuron.
    :param post: rank of the post-synaptic neuron.
    """
    if not isinstance(pre, int) or not isinstance(post, int):
        Global._error('Projection.synapse() only accepts ranks for the pre and post neurons.')

    return self.dendrite(post).synapse(pre)

Connectors#

ANNarchy.core.ConnectorMethods.connect_one_to_one(self, weights=1.0, delays=0.0, force_multiple_weights=False, storage_format=None, storage_order=None) #

Builds a one-to-one connection pattern between the two populations.

Parameters:

  • weights

    initial synaptic values, either a single value (float) or a random distribution object.

  • delays

    synaptic delays, either a single value or a random distribution object (default=dt).

  • force_multiple_weights

    if a single value is provided for weights and there is no learning, a single weight value will be used for the whole projection instead of one per synapse. Setting force_multiple_weights to True ensures that a value per synapse will be used.

  • storage_format

    for some of the default connection patterns, ANNarchy provide different storage formats. For one-to-one we support list-of-list ("lil") or compressed sparse row ("csr"), by default lil is chosen.

  • storage_order

    for some of the available storage formats, ANNarchy provides different storage orderings. For one-to-one we support pre_to_post and post_to_pre, by default post_to_pre is chosen.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/ConnectorMethods.py
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
def connect_one_to_one(self, weights=1.0, delays=0.0, force_multiple_weights=False, storage_format=None, storage_order=None):
    """
    Builds a one-to-one connection pattern between the two populations.

    :param weights: initial synaptic values, either a single value (float) or a random distribution object.
    :param delays: synaptic delays, either a single value or a random distribution object (default=dt).
    :param force_multiple_weights: if a single value is provided for ``weights`` and there is no learning, a single weight value will be used for the whole projection instead of one per synapse. Setting ``force_multiple_weights`` to True ensures that a value per synapse will be used.
    :param storage_format: for some of the default connection patterns, ANNarchy provide different storage formats. For one-to-one we support list-of-list ("lil") or compressed sparse row ("csr"), by default lil is chosen.
    :param storage_order: for some of the available storage formats, ANNarchy provides different storage orderings. For one-to-one we support *pre_to_post* and *post_to_pre*, by default *post_to_pre* is chosen.
    """
    if self.pre.size != self.post.size:
        Global._warning("connect_one_to_one() between", self.pre.name, 'and', self.post.name, 'with target', self.target)
        Global._print("\t the two populations have different sizes, please check the connection pattern is what you expect.")

    self.connector_name = "One-to-One"
    self.connector_description = "One-to-One, weights %(weight)s, delays %(delay)s" % {'weight': _process_random(weights), 'delay': _process_random(delays)}

    if isinstance(weights, (int, float)) and not force_multiple_weights:
        self._single_constant_weight = True

    if storage_format == "dense":
        Global._error("The usage of 'dense' storage format on one-to-one pattern is not allowed.")

    # if weights or delays are from random distribution I need to know this in code generator
    self.connector_weight_dist = weights if isinstance(weights, RandomDistribution) else None
    self.connector_delay_dist = delays if isinstance(delays, RandomDistribution) else None

    self._store_connectivity(one_to_one, (weights, delays, storage_format, storage_order), delays, storage_format, storage_order)
    return self

ANNarchy.core.ConnectorMethods.connect_all_to_all(self, weights, delays=0.0, allow_self_connections=False, force_multiple_weights=False, storage_format=None, storage_order=None) #

Builds an all-to-all connection pattern between the two populations.

Parameters:

  • weights

    synaptic values, either a single value or a random distribution object.

  • delays

    synaptic delays, either a single value or a random distribution object (default=dt).

  • allow_self_connections

    if True, self-connections between a neuron and itself are allowed (default = False if the pre- and post-populations are identical, True otherwise).

  • force_multiple_weights

    if a single value is provided for weights and there is no learning, a single weight value will be used for the whole projection instead of one per synapse. Setting force_multiple_weights to True ensures that a value per synapse will be used.

  • storage_format

    for some of the default connection patterns, ANNarchy provide different storage formats. For all-to-all we support list-of-list ("lil") or compressed sparse row ("csr"), by default lil is chosen.

  • storage_order

    for some of the available storage formats, ANNarchy provides different storage orderings. For all-to-all we support pre_to_post and post_to_pre, by default post_to_pre is chosen. Please note, the last two arguments should be changed carefully, as they can have large impact on the computational performance of ANNarchy.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/ConnectorMethods.py
 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
def connect_all_to_all(self, weights, delays=0.0, allow_self_connections=False, force_multiple_weights=False, storage_format=None, storage_order=None):
    """
    Builds an all-to-all connection pattern between the two populations.

    :param weights: synaptic values, either a single value or a random distribution object.
    :param delays: synaptic delays, either a single value or a random distribution object (default=dt).
    :param allow_self_connections: if True, self-connections between a neuron and itself are allowed (default = False if the pre- and post-populations are identical, True otherwise).
    :param force_multiple_weights: if a single value is provided for ``weights`` and there is no learning, a single weight value will be used for the whole projection instead of one per synapse. Setting ``force_multiple_weights`` to True ensures that a value per synapse will be used.
    :param storage_format: for some of the default connection patterns, ANNarchy provide different storage formats. For all-to-all we support list-of-list ("lil") or compressed sparse row ("csr"), by default lil is chosen.
    :param storage_order: for some of the available storage formats, ANNarchy provides different storage orderings. For all-to-all we support pre_to_post and post_to_pre, by default post_to_pre is chosen.

    Please note, the last two arguments should be changed carefully, as they can have large impact on the computational performance of ANNarchy.
    """
    pre_pop = self.pre if not isinstance(self.pre, PopulationView) else self.pre.population
    post_pop = self.post if not isinstance(self.post, PopulationView) else self.post.population
    if pre_pop != post_pop:
        allow_self_connections = True

    self.connector_name = "All-to-All"
    self.connector_description = "All-to-All, weights %(weight)s, delays %(delay)s" % {'weight': _process_random(weights), 'delay': _process_random(delays)}

    # Does the projection define a single non-plastic weight?
    if isinstance(weights, (int, float)) and not force_multiple_weights:
        self._single_constant_weight = True

    # if weights or delays are from random distribution I need to know this in code generator
    self.connector_weight_dist = weights if isinstance(weights, RandomDistribution) else None
    self.connector_delay_dist = delays if isinstance(delays, RandomDistribution) else None

    # Store the connectivity
    self._store_connectivity(all_to_all, (weights, delays, allow_self_connections, storage_format, storage_order), delays, storage_format, storage_order)
    return self

ANNarchy.core.ConnectorMethods.connect_fixed_probability(self, probability, weights, delays=0.0, allow_self_connections=False, force_multiple_weights=False, storage_format=None, storage_order=None) #

Builds a probabilistic connection pattern between the two populations.

Each neuron in the postsynaptic population is connected to neurons of the presynaptic population with the given probability. Self-connections are avoided by default.

Parameters:

  • probability

    probability that a synapse is created.

  • weights

    either a single value for all synapses or a RandomDistribution object.

  • delays

    either a single value for all synapses or a RandomDistribution object (default = dt)

  • allow_self_connections

    defines if self-connections are allowed (default=False).

  • force_multiple_weights

    if a single value is provided for weights and there is no learning, a single weight value will be used for the whole projection instead of one per synapse. Setting force_multiple_weights to True ensures that a value per synapse will be used.

  • storage_format

    for some of the default connection patterns ANNarchy provide different storage formats. For all-to-all we support list-of-list ("lil") or compressed sparse row ("csr"), by default lil is chosen.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/ConnectorMethods.py
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
def connect_fixed_probability(self, probability, weights, delays=0.0, allow_self_connections=False, force_multiple_weights=False, storage_format=None, storage_order=None):
    """
    Builds a probabilistic connection pattern between the two populations.

    Each neuron in the postsynaptic population is connected to neurons of the presynaptic population with the given probability. Self-connections are avoided by default.

    :param probability: probability that a synapse is created.
    :param weights: either a single value for all synapses or a RandomDistribution object.
    :param delays: either a single value for all synapses or a RandomDistribution object (default = dt)
    :param allow_self_connections: defines if self-connections are allowed (default=False).
    :param force_multiple_weights: if a single value is provided for ``weights`` and there is no learning, a single weight value will be used for the whole projection instead of one per synapse. Setting ``force_multiple_weights`` to True ensures that a value per synapse will be used.
    :param storage_format: for some of the default connection patterns ANNarchy provide different storage formats. For all-to-all we support list-of-list ("lil") or compressed sparse row ("csr"), by default lil is chosen.
    """
    if self.pre != self.post:
        allow_self_connections = True

    self.connector_name = "Random"
    self.connector_description = "Random, sparseness %(proba)s, weights %(weight)s, delays %(delay)s" % {'weight': _process_random(weights), 'delay': _process_random(delays), 'proba': probability}

    if isinstance(weights, (int, float)) and not force_multiple_weights:
        self._single_constant_weight = True

    # if weights or delays are from random distribution I need to know this in code generator
    self.connector_weight_dist = weights if isinstance(weights, RandomDistribution) else None
    self.connector_delay_dist = delays if isinstance(delays, RandomDistribution) else None

    self._store_connectivity(fixed_probability, (probability, weights, delays, allow_self_connections, storage_format, storage_order), delays, storage_format, storage_order)
    return self

ANNarchy.core.ConnectorMethods.connect_fixed_number_pre(self, number, weights, delays=0.0, allow_self_connections=False, force_multiple_weights=False, storage_format=None, storage_order=None) #

Builds a connection pattern between the two populations with a fixed number of pre-synaptic neurons.

Each neuron in the postsynaptic population receives connections from a fixed number of neurons of the presynaptic population chosen randomly.

Parameters:

  • number

    number of synapses per postsynaptic neuron.

  • weights

    either a single value for all synapses or a RandomDistribution object.

  • delays

    either a single value for all synapses or a RandomDistribution object (default = dt)

  • allow_self_connections

    defines if self-connections are allowed (default=False).

  • force_multiple_weights

    if a single value is provided for weights and there is no learning, a single weight value will be used for the whole projection instead of one per synapse. Setting force_multiple_weights to True ensures that a value per synapse will be used.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/ConnectorMethods.py
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
def connect_fixed_number_pre(self, number, weights, delays=0.0, allow_self_connections=False, force_multiple_weights=False, storage_format=None, storage_order=None):
    """
    Builds a connection pattern between the two populations with a fixed number of pre-synaptic neurons.

    Each neuron in the postsynaptic population receives connections from a fixed number of neurons of the presynaptic population chosen randomly.

    :param number: number of synapses per postsynaptic neuron.
    :param weights: either a single value for all synapses or a RandomDistribution object.
    :param delays: either a single value for all synapses or a RandomDistribution object (default = dt)
    :param allow_self_connections: defines if self-connections are allowed (default=False).
    :param force_multiple_weights: if a single value is provided for ``weights`` and there is no learning, a single weight value will be used for the whole projection instead of one per synapse. Setting ``force_multiple_weights`` to True ensures that a value per synapse will be used.
    """
    if self.pre != self.post:
        allow_self_connections = True

    if number > self.pre.size:
        Global._error('connect_fixed_number_pre: the number of pre-synaptic neurons exceeds the size of the population.')

    self.connector_name = "Random Convergent"
    self.connector_description = "Random Convergent %(number)s $\\rightarrow$ 1, weights %(weight)s, delays %(delay)s"% {'weight': _process_random(weights), 'delay': _process_random(delays), 'number': number}

    if isinstance(weights, (int, float)) and not force_multiple_weights:
        self._single_constant_weight = True

    # if weights or delays are from random distribution I need to know this in code generator
    self.connector_weight_dist = weights if isinstance(weights, RandomDistribution) else None
    self.connector_delay_dist = delays if isinstance(delays, RandomDistribution) else None

    self._store_connectivity(fixed_number_pre, (number, weights, delays, allow_self_connections, storage_format, storage_order), delays, storage_format, storage_order)
    return self

ANNarchy.core.ConnectorMethods.connect_fixed_number_post(self, number, weights=1.0, delays=0.0, allow_self_connections=False, force_multiple_weights=False, storage_format=None, storage_order=None) #

Builds a connection pattern between the two populations with a fixed number of post-synaptic neurons.

Each neuron in the pre-synaptic population sends connections to a fixed number of neurons of the post-synaptic population chosen randomly.

Parameters:

  • number

    number of synapses per pre-synaptic neuron.

  • weights

    either a single value for all synapses or a RandomDistribution object.

  • delays

    either a single value for all synapses or a RandomDistribution object (default = dt)

  • allow_self_connections

    defines if self-connections are allowed (default=False)

  • force_multiple_weights

    if a single value is provided for weights and there is no learning, a single weight value will be used for the whole projection instead of one per synapse. Setting force_multiple_weights to True ensures that a value per synapse will be used.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/ConnectorMethods.py
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
def connect_fixed_number_post(self, number, weights=1.0, delays=0.0, allow_self_connections=False, force_multiple_weights=False, storage_format=None, storage_order=None):
    """
    Builds a connection pattern between the two populations with a fixed number of post-synaptic neurons.

    Each neuron in the pre-synaptic population sends connections to a fixed number of neurons of the post-synaptic population chosen randomly.

    :param number: number of synapses per pre-synaptic neuron.
    :param weights: either a single value for all synapses or a RandomDistribution object.
    :param delays: either a single value for all synapses or a RandomDistribution object (default = dt)
    :param allow_self_connections: defines if self-connections are allowed (default=False)
    :param force_multiple_weights: if a single value is provided for ``weights`` and there is no learning, a single weight value will be used for the whole projection instead of one per synapse. Setting ``force_multiple_weights`` to True ensures that a value per synapse will be used.
    """
    if self.pre != self.post:
        allow_self_connections = True

    if number > self.post.size:
        Global._error('connect_fixed_number_post: the number of post-synaptic neurons exceeds the size of the population.')

    self.connector_name = "Random Divergent"
    self.connector_description = "Random Divergent 1 $\\rightarrow$ %(number)s, weights %(weight)s, delays %(delay)s"% {'weight': _process_random(weights), 'delay': _process_random(delays), 'number': number}

    if isinstance(weights, (int, float)) and not force_multiple_weights:
        self._single_constant_weight = True

    # if weights or delays are from random distribution I need to know this in code generator
    self.connector_weight_dist = weights if isinstance(weights, RandomDistribution) else None
    self.connector_delay_dist = delays if isinstance(delays, RandomDistribution) else None

    self._store_connectivity(fixed_number_post, (number, weights, delays, allow_self_connections, storage_format, storage_order), delays, storage_format, storage_order)
    return self

ANNarchy.core.ConnectorMethods.connect_gaussian(self, amp, sigma, delays=0.0, limit=0.01, allow_self_connections=False, storage_format=None) #

Builds a Gaussian connection pattern between the two populations.

Each neuron in the postsynaptic population is connected to a region of the presynaptic population centered around the neuron with the same normalized coordinates using a Gaussian profile.

Parameters:

  • amp

    amplitude of the Gaussian function

  • sigma

    width of the Gaussian function

  • delays

    synaptic delay, either a single value or a random distribution object (default=dt).

  • limit

    proportion of amp below which synapses are not created (default: 0.01)

  • allow_self_connections

    allows connections between a neuron and itself.

  • storage_format

    for some of the default connection patterns, ANNarchy provide different storage formats. By default lil (list-in-list) is chosen.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/ConnectorMethods.py
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
def connect_gaussian(self, amp, sigma, delays=0.0, limit=0.01, allow_self_connections=False, storage_format=None):
    """
    Builds a Gaussian connection pattern between the two populations.

    Each neuron in the postsynaptic population is connected to a region of the presynaptic population centered around
    the neuron with the same normalized coordinates using a Gaussian profile.

    :param amp: amplitude of the Gaussian function
    :param sigma: width of the Gaussian function
    :param delays: synaptic delay, either a single value or a random distribution object (default=dt).
    :param limit: proportion of *amp* below which synapses are not created (default: 0.01)
    :param allow_self_connections: allows connections between a neuron and itself.
    :param storage_format: for some of the default connection patterns, ANNarchy provide different storage formats. By default *lil* (list-in-list) is chosen.
    """
    if self.pre != self.post:
        allow_self_connections = True

    if isinstance(self.pre, PopulationView) or isinstance(self.post, PopulationView):
        Global._error('Gaussian connector is only possible on whole populations, not PopulationViews.')

    self.connector_name = "Gaussian"
    self.connector_description = "Gaussian, $A$ %(A)s, $\sigma$ %(sigma)s, delays %(delay)s"% {'A': str(amp), 'sigma': str(sigma), 'delay': _process_random(delays)}

    # weights are not drawn, delays possibly
    self.connector_delay_dist = delays if isinstance(delays, RandomDistribution) else None

    self._store_connectivity(gaussian, (amp, sigma, delays, limit, allow_self_connections, storage_format, "post_to_pre"), delays, storage_format, "post_to_pre")
    return self

ANNarchy.core.ConnectorMethods.connect_dog(self, amp_pos, sigma_pos, amp_neg, sigma_neg, delays=0.0, limit=0.01, allow_self_connections=False, storage_format=None) #

Builds a Difference-Of-Gaussians connection pattern between the two populations.

Each neuron in the postsynaptic population is connected to a region of the presynaptic population centered around the neuron with the same normalized coordinates using a Difference-Of-Gaussians profile.

Parameters:

  • amp_pos

    amplitude of the positive Gaussian function

  • sigma_pos

    width of the positive Gaussian function

  • amp_neg

    amplitude of the negative Gaussian function

  • sigma_neg

    width of the negative Gaussian function

  • delays

    synaptic delay, either a single value or a random distribution object (default=dt).

  • limit

    proportion of amp below which synapses are not created (default: 0.01)

  • allow_self_connections

    allows connections between a neuron and itself.

  • storage_format

    for some of the default connection patterns, ANNarchy provide different storage formats. By default lil (list-in-list) is chosen.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/ConnectorMethods.py
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
def connect_dog(self, amp_pos, sigma_pos, amp_neg, sigma_neg, delays=0.0, limit=0.01, allow_self_connections=False, storage_format=None):
    """
    Builds a Difference-Of-Gaussians connection pattern between the two populations.

    Each neuron in the postsynaptic population is connected to a region of the presynaptic population centered around
    the neuron with the same normalized coordinates using a Difference-Of-Gaussians profile.

    :param amp_pos: amplitude of the positive Gaussian function
    :param sigma_pos: width of the positive Gaussian function
    :param amp_neg: amplitude of the negative Gaussian function
    :param sigma_neg: width of the negative Gaussian function
    :param delays: synaptic delay, either a single value or a random distribution object (default=dt).
    :param limit: proportion of *amp* below which synapses are not created (default: 0.01)
    :param allow_self_connections: allows connections between a neuron and itself.
    :param storage_format: for some of the default connection patterns, ANNarchy provide different storage formats. By default *lil* (list-in-list) is chosen.
    """
    if self.pre != self.post:
        allow_self_connections = True

    if isinstance(self.pre, PopulationView) or isinstance(self.post, PopulationView):
        Global._error('DoG connector is only possible on whole populations, not PopulationViews.')

    self.connector_name = "Difference-of-Gaussian"
    self.connector_description = "Difference-of-Gaussian, $A^+ %(Aplus)s, $\sigma^+$ %(sigmaplus)s, $A^- %(Aminus)s, $\sigma^-$ %(sigmaminus)s, delays %(delay)s"% {'Aplus': str(amp_pos), 'sigmaplus': str(sigma_pos), 'Aminus': str(amp_neg), 'sigmaminus': str(sigma_neg), 'delay': _process_random(delays)}

    # delays are possibly drawn from distribution, weights not
    self.connector_delay_dist = delays if isinstance(delays, RandomDistribution) else None

    self._store_connectivity(dog, (amp_pos, sigma_pos, amp_neg, sigma_neg, delays, limit, allow_self_connections, storage_format, "post_to_pre"), delays, storage_format, "post_to_pre")
    return self

ANNarchy.core.ConnectorMethods.connect_with_func(self, method, storage_format=None, storage_order=None, **args) #

Builds a connection pattern based on a user-defined method.

Parameters:

  • method

    method to call. The method must return a CSR object.

  • args

    list of arguments needed by the function

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/ConnectorMethods.py
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
def connect_with_func(self, method, storage_format=None, storage_order=None, **args):
    """
    Builds a connection pattern based on a user-defined method.

    :param method: method to call. The method **must** return a CSR object.
    :param args: list of arguments needed by the function
    """
    # Invoke the method directly, we need the delays already....
    synapses = method(self.pre, self.post, **args)
    synapses.validate()

    # Treat delays
    if synapses.uniform_delay != -1: # uniform delay
        d = synapses.max_delay * Global.config['dt']
        self.connector_delay_dist = None
    else:
        # Just to trick _store_connectivity(), the real delays are in the CSR
        d = DiscreteUniform(0., synapses.max_delay * Global.config['dt'])
        self.connector_delay_dist = DiscreteUniform(0., synapses.max_delay * Global.config['dt'])

    self._store_connectivity(self._load_from_lil, (synapses, ), d, storage_format=storage_format, storage_order=storage_order)

    self.connector_name = "User-defined"
    self.connector_description = "Created by the method " + method.__name__
    return self

ANNarchy.core.ConnectorMethods.connect_from_matrix(self, weights, delays=0.0, pre_post=False, storage_format=None, storage_order=None) #

Builds a connection pattern according to a dense connectivity matrix.

The matrix must be N*M, where N is the number of neurons in the post-synaptic population and M in the pre-synaptic one. Lists of lists must have the same size.

If a synapse should not be created, the weight value should be None.

Parameters:

  • weights

    a matrix or list of lists representing the weights. If a value is None, the synapse will not be created.

  • delays

    a matrix or list of lists representing the delays. Must represent the same synapses as weights. If the argument is omitted, delays are 0.

  • pre_post

    states which index is first. By default, the first dimension is related to the post-synaptic population. If pre_post is True, the first dimension is the pre-synaptic population.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/ConnectorMethods.py
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
def connect_from_matrix(self, weights, delays=0.0, pre_post=False, storage_format=None, storage_order=None):
    """
    Builds a connection pattern according to a dense connectivity matrix.

    The matrix must be N*M, where N is the number of neurons in the post-synaptic population and M in the pre-synaptic one. Lists of lists must have the same size.

    If a synapse should not be created, the weight value should be None.

    :param weights: a matrix or list of lists representing the weights. If a value is None, the synapse will not be created.
    :param delays: a matrix or list of lists representing the delays. Must represent the same synapses as weights. If the argument is omitted, delays are 0.
    :param pre_post: states which index is first. By default, the first dimension is related to the post-synaptic population. If ``pre_post`` is True, the first dimension is the pre-synaptic population.
    """

    # Store the synapses
    self.connector_name = "Connectivity matrix"
    self.connector_description = "Connectivity matrix"

    if isinstance(weights, list):
        try:
            weights = np.array(weights)
        except:
            Global._error('connect_from_matrix(): You must provide a dense 2D matrix.')

    self._store_connectivity(self._load_from_matrix, (weights, delays, pre_post), delays, storage_format, storage_order)

    return self

ANNarchy.core.ConnectorMethods.connect_from_sparse(self, weights, delays=0.0, storage_format=None, storage_order=None) #

Builds a connectivity pattern using a Scipy sparse matrix for the weights and (optionally) delays.

Warning: a sparse matrix has pre-synaptic ranks as first dimension.

Parameters:

  • weights

    a sparse lil_matrix object created from scipy.

  • delays

    the value of the constant delay (default: dt).

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/ConnectorMethods.py
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
def connect_from_sparse(self, weights, delays=0.0, storage_format=None, storage_order=None):
    """
    Builds a connectivity pattern using a Scipy sparse matrix for the weights and (optionally) delays.

    Warning: a sparse matrix has pre-synaptic ranks as first dimension.

    :param weights: a sparse lil_matrix object created from scipy.
    :param delays: the value of the constant delay (default: dt).
    """
    try:
        from scipy.sparse import lil_matrix, csr_matrix, csc_matrix
    except:
        Global._error("connect_from_sparse(): scipy is not installed, sparse matrices can not be loaded.")

    if not isinstance(weights, (lil_matrix, csr_matrix, csc_matrix)):
        Global._error("connect_from_sparse(): only lil, csr and csc matrices are allowed for now.")

    if not isinstance(delays, (int, float)):
        Global._error("connect_from_sparse(): only constant delays are allowed for sparse matrices.")

    weights = csc_matrix(weights)

    # if weights[weights.nonzero()].max() == weights[weights.nonzero()].min() :
    #     self._single_constant_weight = True

    # Store the synapses
    self.connector_name = "Sparse connectivity matrix"
    self.connector_description = "Sparse connectivity matrix"
    self._store_connectivity(self._load_from_sparse, (weights, delays), delays, storage_format, storage_order)

    return self

ANNarchy.core.ConnectorMethods.connect_from_file(self, filename, pickle_encoding=None, storage_format=None, storage_order=None) #

Builds the connectivity matrix using data saved using the Projection.save_connectivity() method (not save()!).

Admissible file formats are compressed Numpy files (.npz), gunzipped binary text files (.gz) or binary text files.

Parameters:

  • filename

    file where the connections were saved. .. note:: Only the ranks, weights and delays are loaded, not the other variables.

Source code in /home/docs/checkouts/readthedocs.org/user_builds/annarchy/conda/latest/lib/python3.9/site-packages/ANNarchy/core/ConnectorMethods.py
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
def connect_from_file(self, filename, pickle_encoding=None, storage_format=None, storage_order=None):
    """
    Builds the connectivity matrix using data saved using the Projection.save_connectivity() method (not save()!).

    Admissible file formats are compressed Numpy files (.npz), gunzipped binary text files (.gz) or binary text files.

    :param filename: file where the connections were saved.

    .. note::

        Only the ranks, weights and delays are loaded, not the other variables.
    """
    # Create an empty LIL object
    lil = LILConnectivity()

    # Load the data
    from ANNarchy.core.IO import _load_connectivity_data
    try:
        data = _load_connectivity_data(filename, pickle_encoding)
    except Exception as e:
        Global._print(e)
        Global._error('connect_from_file(): Unable to load the data', filename, 'into the projection.')

    # Load the LIL object
    try:
        # Size
        lil.size = data['size']
        lil.nb_synapses = data['nb_synapses']

        # Ranks
        lil.post_rank = list(data['post_ranks'])
        lil.pre_rank = list(data['pre_ranks'])

        # Weights
        if isinstance(data['w'], (int, float)):
            self._single_constant_weight = True
            lil.w = [[float(data['w'])]]
        elif isinstance(data['w'], (np.ndarray,)) and data['w'].size == 1:
            self._single_constant_weight = True
            lil.w = [[float(data['w'])]]
        else:
            lil.w = data['w']

        # Delays
        lil.max_delay = data['max_delay']
        lil.uniform_delay = data['uniform_delay']

        if data['delay'] is not None:
            if lil.uniform_delay == -1:
                lil.delay = list(data['delay'])
            else:
                lil.delay = [[lil.max_delay]]

    except Exception as e:
        Global._print(e)
        Global._error('Unable to load the data', filename, 'into the projection.')

    # Store the synapses
    self.connector_name = "From File"
    self.connector_description = "From File"
    self._store_connectivity(self._load_from_lil, (lil,), lil.max_delay if lil.uniform_delay > 0 else lil.delay, storage_format=storage_format, storage_order=storage_order)

    return self