-
Notifications
You must be signed in to change notification settings - Fork 216
/
test_synapses.py
3207 lines (2734 loc) · 110 KB
/
test_synapses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
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
import uuid
import logging
import pytest
from numpy.testing import assert_equal, assert_array_equal
import sympy
from brian2 import *
from brian2.codegen.translation import make_statements
from brian2.codegen.generators import NumpyCodeGenerator
from brian2.core.network import schedule_propagation_offset
from brian2.core.variables import variables_by_owner, ArrayVariable, Constant
from brian2.core.functions import DEFAULT_FUNCTIONS
from brian2.stateupdaters.base import UnsupportedEquationsException
from brian2.utils.logger import catch_logs
from brian2.utils.stringtools import get_identifiers, word_substitute, indent, deindent
from brian2.devices.device import reinit_and_delete, all_devices, get_device
from brian2.codegen.permutation_analysis import check_for_order_independence, OrderDependenceError
from brian2.synapses.parse_synaptic_generator_syntax import parse_synapse_generator
from brian2.tests.utils import assert_allclose, exc_isinstance
from brian2.equations.equations import EquationError
def _compare(synapses, expected):
conn_matrix = np.zeros((len(synapses.source), len(synapses.target)),
dtype=np.int32)
for _i, _j in zip(synapses.i[:], synapses.j[:]):
conn_matrix[_i, _j] += 1
assert_equal(conn_matrix, expected)
# also compare the correct numbers of incoming and outgoing synapses
incoming = conn_matrix.sum(axis=0)
outgoing = conn_matrix.sum(axis=1)
assert all(synapses.N_outgoing[:] == outgoing[synapses.i[:]]), 'N_outgoing returned an incorrect value'
assert_array_equal(synapses.N_outgoing_pre, outgoing), 'N_outgoing_pre returned an incorrect value'
assert all(synapses.N_incoming[:] == incoming[synapses.j[:]]), 'N_incoming returned an incorrect value'
assert_array_equal(synapses.N_incoming_post, incoming), 'N_incoming_post returned an incorrect value'
# Compare the "synapse number" if it exists
if synapses.multisynaptic_index is not None:
# Build an array of synapse numbers by counting the number of times
# a source/target combination exists
synapse_numbers = np.zeros_like(synapses.i[:])
numbers = {}
for _i, (source, target) in enumerate(zip(synapses.i[:],
synapses.j[:])):
number = numbers.get((source, target), 0)
synapse_numbers[_i] = number
numbers[(source, target)] = number + 1
assert all(synapses.state(synapses.multisynaptic_index)[:] == synapse_numbers), 'synapse_number returned an incorrect value'
@pytest.mark.codegen_independent
def test_creation():
'''
A basic test that creating a Synapses object works.
'''
G = NeuronGroup(42, 'v: 1', threshold='False')
S = Synapses(G, G, 'w:1', on_pre='v+=w')
# We store weakref proxys, so we can't directly compare the objects
assert S.source.name == S.target.name == G.name
assert len(S) == 0
S = Synapses(G, model='w:1', on_pre='v+=w')
assert S.source.name == S.target.name == G.name
@pytest.mark.codegen_independent
def test_creation_errors():
G = NeuronGroup(42, 'v: 1', threshold='False')
# Check that the old Synapses(..., connect=...) syntax raises an error
with pytest.raises(TypeError):
Synapses(G, G, 'w:1', on_pre='v+=w', connect=True)
# Check that using pre and on_pre (resp. post/on_post) at the same time
# raises an error
with pytest.raises(TypeError):
Synapses(G, G, 'w:1', pre='v+=w', on_pre='v+=w', connect=True)
with pytest.raises(TypeError):
Synapses(G, G, 'w:1', post='v+=w', on_post='v+=w', connect=True)
@pytest.mark.codegen_independent
def test_connect_errors():
G = NeuronGroup(42, '')
S = Synapses(G, G)
# Not a boolean condition
with pytest.raises(TypeError):
S.connect('i*2')
# Unit error
with pytest.raises(DimensionMismatchError):
S.connect('i > 3*mV')
# Syntax error
with pytest.raises(SyntaxError):
S.connect('sin(3, 4) > 1')
# Unit error in p argument
with pytest.raises(TypeError):
S.connect('1*mV')
# Syntax error in p argument
with pytest.raises(SyntaxError):
S.connect(p='sin(3, 4)')
@pytest.mark.codegen_independent
def test_name_clashes():
# Using identical names for synaptic and pre- or post-synaptic variables
# is confusing and should be forbidden
G1 = NeuronGroup(1, 'a : 1')
G2 = NeuronGroup(1, 'b : 1')
with pytest.raises(ValueError):
Synapses(G1, G2, 'a : 1')
with pytest.raises(ValueError):
Synapses(G1, G2, 'b : 1')
# Using _pre or _post as variable names is confusing (even if it is non-
# ambiguous in unconnected NeuronGroups)
with pytest.raises(ValueError):
Synapses(G1, G2, 'x_pre : 1')
with pytest.raises(ValueError):
Synapses(G1, G2, 'x_post : 1')
with pytest.raises(ValueError):
Synapses(G1, G2, 'x_pre = 1 : 1')
with pytest.raises(ValueError):
Synapses(G1, G2, 'x_post = 1 : 1')
with pytest.raises(ValueError):
NeuronGroup(1, 'x_pre : 1')
with pytest.raises(ValueError):
NeuronGroup(1, 'x_post : 1')
with pytest.raises(ValueError):
NeuronGroup(1, 'x_pre = 1 : 1')
with pytest.raises(ValueError):
NeuronGroup(1, 'x_post = 1 : 1')
# this should all be ok
Synapses(G1, G2, 'c : 1')
Synapses(G1, G2, 'a_syn : 1')
Synapses(G1, G2, 'b_syn : 1')
@pytest.mark.standalone_compatible
def test_incoming_outgoing():
'''
Test the count of outgoing/incoming synapses per neuron.
(It will be also automatically tested for all connection patterns that
use the above _compare function for testing)
'''
G1 = NeuronGroup(5, '')
G2 = NeuronGroup(5, '')
S = Synapses(G1, G2, '')
S.connect(i=[0, 0, 0, 1, 1, 2],
j=[0, 1, 2, 1, 2, 3])
run(0*ms) # to make this work for standalone
# First source neuron has 3 outgoing synapses, the second 2, the third 1
assert all(S.N_outgoing[0, :] == 3)
assert all(S.N_outgoing[1, :] == 2)
assert all(S.N_outgoing[2, :] == 1)
assert all(S.N_outgoing[3:, :] == 0)
assert_array_equal(S.N_outgoing_pre, [3, 2, 1, 0, 0])
# First target neuron receives 1 input, the second+third each 2, the fourth receives 1
assert all(S.N_incoming[:, 0] == 1)
assert all(S.N_incoming[:, 1] == 2)
assert all(S.N_incoming[:, 2] == 2)
assert all(S.N_incoming[:, 3] == 1)
assert all(S.N_incoming[:, 4:] == 0)
assert_array_equal(S.N_incoming_post, [1, 2, 2, 1, 0])
@pytest.mark.standalone_compatible
def test_connection_arrays():
'''
Test connecting synapses with explictly given arrays
'''
G = NeuronGroup(42, '')
G2 = NeuronGroup(17, '')
# one-to-one
expected1 = np.eye(len(G2))
S1 = Synapses(G2)
S1.connect(i=np.arange(len(G2)), j=np.arange(len(G2)))
# full
expected2 = np.ones((len(G), len(G2)))
S2 = Synapses(G, G2)
X, Y = np.meshgrid(np.arange(len(G)), np.arange(len(G2)))
S2.connect(i=X.flatten(), j=Y.flatten())
# Multiple synapses
expected3 = np.zeros((len(G), len(G2)))
expected3[3, 3] = 2
S3 = Synapses(G, G2)
S3.connect(i=[3, 3], j=[3, 3])
run(0*ms) # for standalone
_compare(S1, expected1)
_compare(S2, expected2)
_compare(S3, expected3)
# Incorrect usage
S = Synapses(G, G2)
with pytest.raises(TypeError):
S.connect(i=[1.1, 2.2], j=[1.1, 2.2])
with pytest.raises(TypeError):
S.connect(i=[1, 2], j='string')
with pytest.raises(TypeError):
S.connect(i=[1, 2], j=[1, 2], n='i')
with pytest.raises(TypeError):
S.connect([1, 2])
with pytest.raises(ValueError):
S.connect(i=[1, 2, 3], j=[1, 2])
with pytest.raises(ValueError):
S.connect(i=np.ones((3, 3), dtype=np.int32),
j=np.ones((3, 1), dtype=np.int32))
with pytest.raises(IndexError):
S.connect(i=[41, 42], j=[0, 1]) # source index > max
with pytest.raises(IndexError):
S.connect(i=[0, 1], j=[16, 17]) # target index > max
with pytest.raises(IndexError):
S.connect(i=[0, -1], j=[0, 1]) # source index < 0
with pytest.raises(IndexError):
S.connect(i=[0, 1], j=[0, -1]) # target index < 0
with pytest.raises(ValueError):
S.connect('i==j', j=np.arange(10))
with pytest.raises(TypeError):
S.connect('i==j', n=object())
with pytest.raises(TypeError):
S.connect('i==j', p=object())
with pytest.raises(TypeError):
S.connect(object())
@pytest.mark.standalone_compatible
def test_connection_string_deterministic_full():
G = NeuronGroup(17, '')
G2 = NeuronGroup(4, '')
# Full connection
expected_full = np.ones((len(G), len(G2)))
S1 = Synapses(G, G2, '')
S1.connect(True)
S2 = Synapses(G, G2, '')
S2.connect('True')
run(0 * ms) # for standalone
_compare(S1, expected_full)
_compare(S2, expected_full)
@pytest.mark.standalone_compatible
def test_connection_string_deterministic_full_no_self():
G = NeuronGroup(17, 'v : 1')
G.v = 'i'
G2 = NeuronGroup(4, 'v : 1')
G2.v = '17 + i'
# Full connection without self-connections
expected_no_self = np.ones((len(G), len(G))) - np.eye(len(G))
S1 = Synapses(G, G)
S1.connect('i != j')
S2 = Synapses(G, G)
S2.connect('v_pre != v_post')
S3 = Synapses(G, G)
S3.connect(condition='i != j')
run(0*ms) # for standalone
_compare(S1, expected_no_self)
_compare(S2, expected_no_self)
_compare(S3, expected_no_self)
@pytest.mark.standalone_compatible
def test_connection_string_deterministic_full_one_to_one():
G = NeuronGroup(17, 'v : 1')
G.v = 'i'
G2 = NeuronGroup(4, 'v : 1')
G2.v = '17 + i'
# One-to-one connectivity
expected_one_to_one = np.eye(len(G))
S1 = Synapses(G, G)
S1.connect('i == j')
S2 = Synapses(G, G)
S2.connect('v_pre == v_post')
S3 = Synapses(G, G, '''
sub_1 = v_pre : 1
sub_2 = v_post : 1
w:1''')
S3.connect('sub_1 == sub_2')
S4 = Synapses(G, G)
S4.connect(j='i')
run(0*ms) # for standalone
_compare(S1, expected_one_to_one)
_compare(S2, expected_one_to_one)
_compare(S3, expected_one_to_one)
_compare(S4, expected_one_to_one)
@pytest.mark.standalone_compatible
def test_connection_string_deterministic_full_custom():
G = NeuronGroup(17, '')
G2 = NeuronGroup(4, '')
# Everything except for the upper [2, 2] quadrant
number = 2
expected_custom = np.ones((len(G), len(G)))
expected_custom[:number, :number] = 0
S1 = Synapses(G, G)
S1.connect('(i >= number) or (j >= number)')
S2 = Synapses(G, G)
S2.connect('(i >= explicit_number) or (j >= explicit_number)',
namespace={'explicit_number': number})
# check that this mistaken syntax raises an error
with pytest.raises(ValueError):
S2.connect('k for k in range(1)')
# check that trying to connect to a neuron outside the range raises an error
if get_device() == all_devices['runtime']:
with pytest.raises(BrianObjectException) as exc:
S2.connect(j='20')
assert exc.errisinstance(IndexError)
run(0*ms) # for standalone
_compare(S1, expected_custom)
_compare(S2, expected_custom)
@pytest.mark.standalone_compatible
def test_connection_string_deterministic_multiple_and():
# In Brian versions 2.1.0-2.1.2, this fails on the numpy target
# See github issue 900
group = NeuronGroup(10, '')
synapses = Synapses(group, group)
synapses.connect('i>=5 and i<10 and j>=5')
run(0*ms) # for standalone
assert len(synapses) == 25
@pytest.mark.standalone_compatible
def test_connection_random_with_condition():
G = NeuronGroup(4, '')
S1 = Synapses(G, G)
S1.connect('i!=j', p=0.0)
S2 = Synapses(G, G)
S2.connect('i!=j', p=1.0)
expected2 = np.ones((len(G), len(G))) - np.eye(len(G))
S3 = Synapses(G, G)
S3.connect('i>=2', p=0.0)
S4 = Synapses(G, G)
S4.connect('i>=2', p=1.0)
expected4 = np.zeros((len(G), len(G)))
expected4[2, :] = 1
expected4[3, :] = 1
S5 = Synapses(G, G)
S5.connect('j<2', p=0.0)
S6 = Synapses(G, G)
S6.connect('j<2', p=1.0)
expected6 = np.zeros((len(G), len(G)))
expected6[:, 0] = 1
expected6[:, 1] = 1
with catch_logs() as _: # Ignore warnings about empty synapses
run(0 * ms) # for standalone
assert len(S1) == 0
_compare(S2, expected2)
assert len(S3) == 0
_compare(S4, expected4)
assert len(S5) == 0
_compare(S6, expected6)
@pytest.mark.standalone_compatible
@pytest.mark.long
def test_connection_random_with_condition_2():
G = NeuronGroup(4, '')
# Just checking that everything works in principle (we can't check the
# actual connections)
S7 = Synapses(G, G)
S7.connect('i!=j', p=0.01)
S8 = Synapses(G, G)
S8.connect('i!=j', p=0.03)
S9 = Synapses(G, G)
S9.connect('i!=j', p=0.3)
S10 = Synapses(G, G)
S10.connect('i>=2', p=0.01)
S11 = Synapses(G, G)
S11.connect('i>=2', p=0.03)
S12 = Synapses(G, G)
S12.connect('i>=2', p=0.3)
S13 = Synapses(G, G)
S13.connect('j>=2', p=0.01)
S14 = Synapses(G, G)
S14.connect('j>=2', p=0.03)
S15 = Synapses(G, G)
S15.connect('j>=2', p=0.3)
S16 = Synapses(G, G)
S16.connect('i!=j', p='i*0.1')
S17 = Synapses(G, G)
S17.connect('i!=j', p='j*0.1')
# Forces the use of the "jump algorithm"
big_group = NeuronGroup(10000, '')
S18 = Synapses(big_group, big_group)
S18.connect('i != j', p=0.001)
# See github issue #835 -- this failed when using numpy
S19 = Synapses(big_group, big_group)
S19.connect('i < int(N_post*0.5)', p=0.001)
with catch_logs() as _: # Ignore warnings about empty synapses
run(0*ms) # for standalone
assert not any(S7.i == S7.j)
assert not any(S8.i == S8.j)
assert not any(S9.i == S9.j)
assert all(S10.i >= 2)
assert all(S11.i >= 2)
assert all(S12.i >= 2)
assert all(S13.j >= 2)
assert all(S14.j >= 2)
assert all(S15.j >= 2)
assert not any(S16.i == 0)
assert not any(S17.j == 0)
@pytest.mark.standalone_compatible
def test_connection_random_with_indices():
'''
Test random connections.
'''
G = NeuronGroup(4, '')
G2 = NeuronGroup(7, '')
S1 = Synapses(G, G2)
S1.connect(i=0, j=0, p=0.)
expected1 = np.zeros((len(G), len(G2)))
S2 = Synapses(G, G2)
S2.connect(i=0, j=0, p=1.)
expected2 = np.zeros((len(G), len(G2)))
expected2[0, 0] = 1
S3 = Synapses(G, G2)
S3.connect(i=[0, 1], j=[0, 2], p=1.)
expected3 = np.zeros((len(G), len(G2)))
expected3[0, 0] = 1
expected3[1, 2] = 1
# Just checking that it works in principle
S4 = Synapses(G, G)
S4.connect(i=0, j=0, p=0.01)
S5 = Synapses(G, G)
S5.connect(i=[0, 1], j=[0, 2], p=0.01)
S6 = Synapses(G, G)
S6.connect(i=0, j=0, p=0.03)
S7 = Synapses(G, G)
S7.connect(i=[0, 1], j=[0, 2], p=0.03)
S8 = Synapses(G, G)
S8.connect(i=0, j=0, p=0.3)
S9 = Synapses(G, G)
S9.connect(i=[0, 1], j=[0, 2], p=0.3)
with catch_logs() as _: # Ignore warnings about empty synapses
run(0*ms) # for standalone
_compare(S1, expected1)
_compare(S2, expected2)
_compare(S3, expected3)
assert 0 <= len(S4) <= 1
assert 0 <= len(S5) <= 2
assert 0 <= len(S6) <= 1
assert 0 <= len(S7) <= 2
assert 0 <= len(S8) <= 1
assert 0 <= len(S9) <= 2
@pytest.mark.standalone_compatible
def test_connection_random_without_condition():
G = NeuronGroup(4, '''v: 1
x : integer''')
G.x = 'i'
G2 = NeuronGroup(7, '''v: 1
y : 1''')
G2.y = '1.0*i/N'
S1 = Synapses(G, G2)
S1.connect(True, p=0.0)
S2 = Synapses(G, G2)
S2.connect(True, p=1.0)
# Just make sure using values between 0 and 1 work in principle
S3 = Synapses(G, G2)
S3.connect(True, p=0.3)
# Use pre-/post-synaptic variables for "stochastic" connections that are
# actually deterministic
S4 = Synapses(G, G2)
S4.connect(True, p='int(x_pre==2)*1.0')
# Use pre-/post-synaptic variables for "stochastic" connections that are
# actually deterministic
S5 = Synapses(G, G2)
S5.connect(True, p='int(x_pre==2 and y_post > 0.5)*1.0')
with catch_logs() as _: # Ignore warnings about empty synapses
run(0*ms) # for standalone
_compare(S1, np.zeros((len(G), len(G2))))
_compare(S2, np.ones((len(G), len(G2))))
assert 0 <= len(S3) <= len(G) * len(G2)
assert len(S4) == 7
assert_equal(S4.i, np.ones(7)*2)
assert_equal(S4.j, np.arange(7))
assert len(S5) == 3
assert_equal(S5.i, np.ones(3) * 2)
assert_equal(S5.j, np.arange(3) + 4)
@pytest.mark.standalone_compatible
def test_connection_multiple_synapses():
'''
Test multiple synapses per connection.
'''
G = NeuronGroup(42, 'v: 1')
G.v = 'i'
G2 = NeuronGroup(17, 'v: 1')
G2.v = 'i'
S1 = Synapses(G, G2)
S1.connect(True, n=0)
S2 = Synapses(G, G2)
S2.connect(True, n=2)
S3 = Synapses(G, G2)
S3.connect(True, n='j')
S4 = Synapses(G, G2)
S4.connect(True, n='i')
S5 = Synapses(G, G2)
S5.connect(True, n='int(i>j)*2')
S6 = Synapses(G, G2)
S6.connect(True, n='int(v_pre>v_post)*2')
with catch_logs() as _: # Ignore warnings about empty synapses
run(0*ms) # for standalone
assert len(S1) == 0
_compare(S2, 2 * np.ones((len(G), len(G2))))
_compare(S3, np.arange(len(G2)).reshape(1, len(G2)).repeat(len(G),
axis=0))
_compare(S4, np.arange(len(G)).reshape(len(G), 1).repeat(len(G2),
axis=1))
expected = np.zeros((len(G), len(G2)), dtype=np.int32)
for source in range(len(G)):
expected[source, :source] = 2
_compare(S5, expected)
_compare(S6, expected)
def test_state_variable_assignment():
'''
Assign values to state variables in various ways
'''
G = NeuronGroup(10, 'v: volt')
G.v = 'i*mV'
S = Synapses(G, G, 'w:volt')
S.connect(True)
# with unit checking
assignment_expected = [
(5*mV, np.ones(100)*5*mV),
(7*mV, np.ones(100)*7*mV),
(S.i[:] * mV, S.i[:]*np.ones(100)*mV),
('5*mV', np.ones(100)*5*mV),
('i*mV', np.ones(100)*S.i[:]*mV),
('i*mV +j*mV', S.i[:]*mV + S.j[:]*mV),
# reference to pre- and postsynaptic state variables
('v_pre', S.i[:]*mV),
('v_post', S.j[:]*mV),
#('i*mV + j*mV + k*mV', S.i[:]*mV + S.j[:]*mV + S.k[:]*mV) #not supported yet
]
for assignment, expected in assignment_expected:
S.w = 0*volt
S.w = assignment
assert_allclose(S.w[:], expected,
err_msg='Assigning %r gave incorrect result' % assignment)
S.w = 0*volt
S.w[:] = assignment
assert_allclose(S.w[:], expected,
err_msg='Assigning %r gave incorrect result' % assignment)
# without unit checking
assignment_expected = [
(5, np.ones(100)*5*volt),
(7, np.ones(100)*7*volt),
(S.i[:], S.i[:]*np.ones(100)*volt),
('5', np.ones(100)*5*volt),
('i', np.ones(100)*S.i[:]*volt),
('i +j', S.i[:]*volt + S.j[:]*volt),
#('i + j + k', S.i[:]*volt + S.j[:]*volt + S.k[:]*volt) #not supported yet
]
for assignment, expected in assignment_expected:
S.w = 0*volt
S.w_ = assignment
assert_allclose(S.w[:], expected,
err_msg='Assigning %r gave incorrect result' % assignment)
S.w = 0*volt
S.w_[:] = assignment
assert_allclose(S.w[:], expected,
err_msg='Assigning %r gave incorrect result' % assignment)
def test_state_variable_indexing():
G1 = NeuronGroup(5, 'v:volt')
G1.v = 'i*mV'
G2 = NeuronGroup(7, 'v:volt')
G2.v= '10*mV + i*mV'
S = Synapses(G1, G2, 'w:1', multisynaptic_index='k')
S.connect(True, n=2)
S.w[:, :, 0] = '5*i + j'
S.w[:, :, 1] = '35 + 5*i + j'
#Slicing
assert len(S.w[:]) == len(S.w[:, :]) == len(S.w[:, :, :]) == len(G1)*len(G2)*2
assert len(S.w[0:, 0:]) == len(S.w[0:, 0:, 0:]) == len(G1)*len(G2)*2
assert len(S.w[0::2, 0:]) == 3*len(G2)*2
assert len(S.w[0, :]) == len(S.w[0, :, :]) == len(G2)*2
assert len(S.w[0:2, :]) == len(S.w[0:2, :, :]) == 2*len(G2)*2
assert len(S.w[:2, :]) == len(S.w[:2, :, :]) == 2*len(G2)*2
assert len(S.w[0:4:2, :]) == len(S.w[0:4:2, :, :]) == 2*len(G2)*2
assert len(S.w[:4:2, :]) == len(S.w[:4:2, :, :]) == 2*len(G2)*2
assert len(S.w[:, 0]) == len(S.w[:, 0, :]) == len(G1)*2
assert len(S.w[:, 0:2]) == len(S.w[:, 0:2, :]) == 2*len(G1)*2
assert len(S.w[:, :2]) == len(S.w[:, :2, :]) == 2*len(G1)*2
assert len(S.w[:, 0:4:2]) == len(S.w[:, 0:4:2, :]) == 2*len(G1)*2
assert len(S.w[:, :4:2]) == len(S.w[:, :4:2, :]) == 2*len(G1)*2
assert len(S.w[:, :, 0]) == len(G1)*len(G2)
assert len(S.w[:, :, 0:2]) == len(G1)*len(G2)*2
assert len(S.w[:, :, :2]) == len(G1)*len(G2)*2
assert len(S.w[:, :, 0:2:2]) == len(G1)*len(G2)
assert len(S.w[:, :, :2:2]) == len(G1)*len(G2)
# 1d indexing is directly indexing synapses!
assert len(S.w[:]) == len(S.w[0:])
assert len(S.w[[0, 1]]) == len(S.w[3:5]) == 2
assert len(S.w[:]) == len(S.w[np.arange(len(G1)*len(G2)*2)])
assert S.w[3] == S.w[np.int32(3)] == S.w[np.int64(3)] # See issue #888
#Array-indexing (not yet supported for synapse index)
assert_equal(S.w[:, 0:3], S.w[:, [0, 1, 2]])
assert_equal(S.w[:, 0:3], S.w[np.arange(len(G1)), [0, 1, 2]])
#string-based indexing
assert_equal(S.w[0:3, :], S.w['i<3'])
assert_equal(S.w[:, 0:3], S.w['j<3'])
assert_equal(S.w[:, :, 0], S.w['k == 0'])
assert_equal(S.w[0:3, :], S.w['v_pre < 2.5*mV'])
assert_equal(S.w[:, 0:3], S.w['v_post < 12.5*mV'])
#invalid indices
with pytest.raises(IndexError):
S.w.__getitem__((1, 2, 3, 4))
with pytest.raises(IndexError):
S.w.__getitem__(object())
with pytest.raises(IndexError):
S.w.__getitem__(1.5)
def test_indices():
G = NeuronGroup(10, 'v : 1')
S = Synapses(G, G, '')
S.connect()
G.v = 'i'
assert_equal(S.indices[:], np.arange(10*10))
assert len(S.indices[5, :]) == 10
assert_equal(S.indices['v_pre >=5'], S.indices[5:, :])
assert_equal(S.indices['j >=5'], S.indices[:, 5:])
def test_subexpression_references():
'''
Assure that subexpressions in targeted groups are handled correctly.
'''
G = NeuronGroup(10, '''v : 1
v2 = 2*v : 1''')
G.v = np.arange(10)
S = Synapses(G, G, '''w : 1
u = v2_post + 1 : 1
x = v2_pre + 1 : 1''')
S.connect('i==(10-1-j)')
assert_equal(S.u[:], np.arange(10)[::-1]*2+1)
assert_equal(S.x[:], np.arange(10)*2+1)
@pytest.mark.standalone_compatible
def test_constant_variable_subexpression_in_synapses():
G = NeuronGroup(10, '')
S = Synapses(G, G, ''' dv1/dt = -v1**2 / (10*ms) : 1 (clock-driven)
dv2/dt = -v_const**2 / (10*ms) : 1 (clock-driven)
dv3/dt = -v_var**2 / (10*ms) : 1 (clock-driven)
dv4/dt = -v_noflag**2 / (10*ms) : 1 (clock-driven)
v_const = v2 : 1 (constant over dt)
v_var = v3 : 1
v_noflag = v4 : 1''',
method='rk2')
S.connect(j='i')
S.v1 = '1.0*i/N'
S.v2 = '1.0*i/N'
S.v3 = '1.0*i/N'
S.v4 = '1.0*i/N'
run(10*ms)
# "variable over dt" subexpressions are directly inserted into the equation
assert_allclose(S.v3[:], S.v1[:])
assert_allclose(S.v4[:], S.v1[:])
# "constant over dt" subexpressions will keep a fixed value over the time
# step and therefore give a slightly different result for multi-step
# methods
assert np.sum((S.v2 - S.v1)**2) > 1e-10
@pytest.mark.standalone_compatible
def test_nested_subexpression_references():
'''
Assure that subexpressions in targeted groups are handled correctly.
'''
G = NeuronGroup(10, '''v : 1
v2 = 2*v : 1
v3 = 1.5*v2 : 1''',
threshold='v>=5')
G2 = NeuronGroup(10, 'v : 1')
G.v = np.arange(10)
S = Synapses(G, G2, on_pre='v_post += v3_pre')
S.connect(j='i')
run(defaultclock.dt)
assert_allclose(G2.v[:5], 0.)
assert_allclose(G2.v[5:], (5+np.arange(5))*3)
@pytest.mark.codegen_independent
def test_equations_unit_check():
group = NeuronGroup(1, 'v : volt', threshold='True')
syn = Synapses(group, group, '''sub1 = 3 : 1
sub2 = sub1 + 1*mV : volt''',
on_pre='v += sub2')
syn.connect()
net = Network(group, syn)
with pytest.raises(BrianObjectException) as exc:
net.run(0*ms)
assert exc_isinstance(exc, DimensionMismatchError)
def test_delay_specification():
# By default delays are state variables (i.e. arrays), but if they are
# specified in the initializer, they are scalars.
G = NeuronGroup(10, 'x : meter', threshold='False')
G.x = 'i*mmeter'
# Array delay
S = Synapses(G, G, 'w:1', on_pre='v+=w')
S.connect(j='i')
assert len(S.delay[:]) == len(G)
S.delay = 'i*ms'
assert_allclose(S.delay[:], np.arange(len(G))*ms)
velocity = 1 * meter / second
S.delay = 'abs(x_pre - (N_post-j)*mmeter)/velocity'
assert_allclose(S.delay[:], abs(G.x - (10 - G.i)*mmeter)/velocity)
S.delay = 5*ms
assert_allclose(S.delay[:], np.ones(len(G))*5*ms)
# Setting delays without units
S.delay_ = float(7*ms)
assert_allclose(S.delay[:], np.ones(len(G))*7*ms)
# Scalar delay
S = Synapses(G, G, 'w:1', on_pre='v+=w', delay=5*ms)
assert_allclose(S.delay[:], 5*ms)
S.connect(j='i')
S.delay = '3*ms'
assert_allclose(S.delay[:], 3*ms)
S.delay = 10 * ms
assert_allclose(S.delay[:], 10 * ms)
# Without units
S.delay_ = float(20*ms)
assert_allclose(S.delay[:], 20 * ms)
# Invalid arguments
with pytest.raises(DimensionMismatchError):
Synapses(G, G, 'w:1', on_pre='v+=w', delay=5*mV)
with pytest.raises(TypeError):
Synapses(G, G, 'w:1', on_pre='v+=w', delay=object())
with pytest.raises(ValueError):
Synapses(G, G, 'w:1', delay=5*ms)
with pytest.raises(ValueError):
Synapses(G, G, 'w:1', on_pre='v+=w', delay={'post': 5*ms})
def test_delays_pathways():
G = NeuronGroup(10, 'x: meter', threshold='False')
G.x = 'i*mmeter'
# Array delay
S = Synapses(G, G, 'w:1', on_pre={'pre1': 'v+=w',
'pre2': 'v+=w'},
on_post='v-=w')
S.connect(j='i')
assert len(S.pre1.delay[:]) == len(G)
assert len(S.pre2.delay[:]) == len(G)
assert len(S.post.delay[:]) == len(G)
S.pre1.delay = 'i*ms'
S.pre2.delay = 'j*ms'
velocity = 1*meter/second
S.post.delay = 'abs(x_pre - (N_post-j)*mmeter)/velocity'
assert_allclose(S.pre1.delay[:], np.arange(len(G)) * ms)
assert_allclose(S.pre2.delay[:], np.arange(len(G)) * ms)
assert_allclose(S.post.delay[:], abs(G.x - (10 - G.i) * mmeter) / velocity)
S.pre1.delay = 5*ms
S.pre2.delay = 10*ms
S.post.delay = 1*ms
assert_allclose(S.pre1.delay[:], np.ones(len(G)) * 5*ms)
assert_allclose(S.pre2.delay[:], np.ones(len(G)) * 10*ms)
assert_allclose(S.post.delay[:], np.ones(len(G)) * 1*ms)
# Indexing with strings
assert len(S.pre1.delay['j<5']) == 5
assert_allclose(S.pre1.delay['j<5'], 5*ms)
# Indexing with 2d indices
assert len(S.post.delay[[3, 4], :]) == 2
assert_allclose(S.post.delay[[3, 4], :], 1*ms)
assert len(S.pre2.delay[:, 7]) == 1
assert_allclose(S.pre2.delay[:, 7], 10*ms)
assert len(S.pre1.delay[[1, 2], [1, 2]]) == 2
assert_allclose(S.pre1.delay[[1, 2], [1, 2]], 5*ms)
# Scalar delay
S = Synapses(G, G, 'w:1', on_pre={'pre1':'v+=w',
'pre2': 'v+=w'}, on_post='v-=w',
delay={'pre1': 5 * ms, 'post': 1*ms})
assert_allclose(S.pre1.delay[:], 5 * ms)
assert_allclose(S.post.delay[:], 1 * ms)
S.connect(j='i')
assert len(S.pre2.delay[:]) == len(G)
S.pre1.delay = 10 * ms
assert_allclose(S.pre1.delay[:], 10 * ms)
S.post.delay = '3*ms'
assert_allclose(S.post.delay[:], 3 * ms)
def test_delays_pathways_subgroups():
G = NeuronGroup(10, 'x: meter', threshold='False')
G.x = 'i*mmeter'
# Array delay
S = Synapses(G[:5], G[5:], 'w:1',
on_pre={'pre1': 'v+=w',
'pre2': 'v+=w'},
on_post='v-=w')
S.connect(j='i')
assert len(S.pre1.delay[:]) == 5
assert len(S.pre2.delay[:]) == 5
assert len(S.post.delay[:]) == 5
S.pre1.delay = 'i*ms'
S.pre2.delay = 'j*ms'
velocity = 1*meter/second
S.post.delay = 'abs(x_pre - (N_post-j)*mmeter)/velocity'
assert_allclose(S.pre1.delay[:], np.arange(5) * ms)
assert_allclose(S.pre2.delay[:], np.arange(5) * ms)
assert_allclose(S.post.delay[:], abs(G[:5].x - (5 - G[:5].i) * mmeter) / velocity)
S.pre1.delay = 5*ms
S.pre2.delay = 10*ms
S.post.delay = 1*ms
assert_allclose(S.pre1.delay[:], np.ones(5) * 5*ms)
assert_allclose(S.pre2.delay[:], np.ones(5) * 10*ms)
assert_allclose(S.post.delay[:], np.ones(5) * 1*ms)
@pytest.mark.codegen_independent
def test_pre_before_post():
# The pre pathway should be executed before the post pathway
G = NeuronGroup(1, '''x : 1
y : 1''', threshold='True')
S = Synapses(G, G, '', on_pre='x=1; y=1', on_post='x=2')
S.connect()
run(defaultclock.dt)
# Both pathways should have been executed, but post should have overriden
# the x value (because it was executed later)
assert G.x == 2
assert G.y == 1
@pytest.mark.standalone_compatible
def test_pre_post_simple():
# Test that pre and post still work correctly
G1 = SpikeGeneratorGroup(1, [0], [1]*ms)
G2 = SpikeGeneratorGroup(1, [0], [2]*ms)
with catch_logs() as l:
S = Synapses(G1, G2, '''pre_value : 1
post_value : 1''',
pre='pre_value +=1',
post='post_value +=2')
S.connect()
syn_mon = StateMonitor(S, ['pre_value', 'post_value'], record=[0],
when='end')
run(3*ms)
offset = schedule_propagation_offset()
assert_allclose(syn_mon.pre_value[0][syn_mon.t < 1*ms + offset], 0)
assert_allclose(syn_mon.pre_value[0][syn_mon.t >= 1*ms + offset], 1)
assert_allclose(syn_mon.post_value[0][syn_mon.t < 2*ms + offset], 0)
assert_allclose(syn_mon.post_value[0][syn_mon.t >= 2*ms + offset], 2)
@pytest.mark.standalone_compatible
def test_transmission_simple():
source = SpikeGeneratorGroup(2, [0, 1], [2, 1] * ms)
target = NeuronGroup(2, 'v : 1')
syn = Synapses(source, target, on_pre='v += 1')
syn.connect(j='i')
mon = StateMonitor(target, 'v', record=True, when='end')
run(2.5*ms)
offset = schedule_propagation_offset()
assert_allclose(mon[0].v[mon.t<2*ms+offset], 0.)
assert_allclose(mon[0].v[mon.t>=2*ms+offset], 1.)
assert_allclose(mon[1].v[mon.t<1*ms+offset], 0.)
assert_allclose(mon[1].v[mon.t>=1*ms+offset], 1.)
@pytest.mark.standalone_compatible
def test_transmission_custom_event():
source = NeuronGroup(2, '',
events={'custom': 'timestep(t,dt)>=timestep((2-i)*ms, dt) '
'and timestep(t,dt)<timestep((2-i)*ms + dt, dt)'})
target = NeuronGroup(2, 'v : 1')
syn = Synapses(source, target, on_pre='v += 1',
on_event='custom')
syn.connect(j='i')
mon = StateMonitor(target, 'v', record=True, when='end')
run(2.5*ms)
assert_allclose(mon[0].v[mon.t<2*ms], 0.)
assert_allclose(mon[0].v[mon.t>=2*ms], 1.)
assert_allclose(mon[1].v[mon.t<1*ms], 0.)
assert_allclose(mon[1].v[mon.t>=1*ms], 1.)
@pytest.mark.codegen_independent
def test_invalid_custom_event():
group1 = NeuronGroup(2, 'v : 1',
events={'custom': 'timestep(t,dt)>=timesteep((2-i)*ms,dt) '
'and timestep(t, dt)<timestep((2-i)*ms + dt, dt)'})
group2 = NeuronGroup(2, 'v : 1', threshold='v>1')
with pytest.raises(ValueError):
Synapses(group1, group1, on_pre='v+=1', on_event='spike')
with pytest.raises(ValueError):
Synapses(group2, group2, on_pre='v+=1', on_event='custom')
def test_transmission():
default_dt = defaultclock.dt
delays = [[0, 0, 0, 0] * ms,
[1, 1, 1, 0] * ms,