Debian Codegraph @

brian2/tests/test_synapses.py

raw
1 import logging
2 import uuid
3
4 import pytest
5 import sympy
6 from numpy.testing import assert_array_equal, assert_equal
7
8 from brian2 import *
9 from brian2.codegen.generators import NumpyCodeGenerator
10 from brian2.codegen.permutation_analysis import (
11 OrderDependenceError,
12 check_for_order_independence,
13 )
14 from brian2.codegen.translation import make_statements
15 from brian2.core.functions import DEFAULT_FUNCTIONS
16 from brian2.core.network import schedule_propagation_offset
17 from brian2.core.variables import ArrayVariable, Constant, variables_by_owner
18 from brian2.devices.cpp_standalone.device import CPPStandaloneDevice
19 from brian2.devices.device import all_devices, get_device, reinit_and_delete
20 from brian2.equations.equations import EquationError
21 from brian2.stateupdaters.base import UnsupportedEquationsException
22 from brian2.synapses.parse_synaptic_generator_syntax import parse_synapse_generator
23 from brian2.tests.utils import assert_allclose, exc_isinstance
24 from brian2.utils.logger import catch_logs
25 from brian2.utils.stringtools import deindent, get_identifiers, indent, word_substitute
26
27
28 def _compare(synapses, expected):
29 conn_matrix = np.zeros((len(synapses.source), len(synapses.target)), dtype=np.int32)
30 for _i, _j in zip(synapses.i[:], synapses.j[:]):
31 conn_matrix[_i, _j] += 1
32
33 assert_equal(conn_matrix, expected)
34 # also compare the correct numbers of incoming and outgoing synapses
35 incoming = conn_matrix.sum(axis=0)
36 outgoing = conn_matrix.sum(axis=1)
37 assert all(synapses.N_outgoing[:] == outgoing[synapses.i[:]]), (
38 "N_outgoing returned an incorrect value"
39 )
40 (
41 assert_array_equal(synapses.N_outgoing_pre, outgoing),
42 "N_outgoing_pre returned an incorrect value",
43 )
44 assert all(synapses.N_incoming[:] == incoming[synapses.j[:]]), (
45 "N_incoming returned an incorrect value"
46 )
47 (
48 assert_array_equal(synapses.N_incoming_post, incoming),
49 "N_incoming_post returned an incorrect value",
50 )
51
52 # Compare the "synapse number" if it exists
53 if synapses.multisynaptic_index is not None:
54 # Build an array of synapse numbers by counting the number of times
55 # a source/target combination exists
56 synapse_numbers = np.zeros_like(synapses.i[:])
57 numbers = {}
58 for _i, (source, target) in enumerate(zip(synapses.i[:], synapses.j[:])):
59 number = numbers.get((source, target), 0)
60 synapse_numbers[_i] = number
61 numbers[(source, target)] = number + 1
62 assert all(
63 synapses.state(synapses.multisynaptic_index)[:] == synapse_numbers
64 ), "synapse_number returned an incorrect value"
65
66
67 @pytest.mark.codegen_independent
68 def test_creation():
69 """
70 A basic test that creating a Synapses object works.
71 """
72 G = NeuronGroup(42, "v: 1", threshold="False")
73 S = Synapses(G, G, "w:1", on_pre="v+=w")
74 # We store weakref proxys, so we can't directly compare the objects
75 assert S.source.name == S.target.name == G.name
76 assert len(S) == 0
77 S = Synapses(G, model="w:1", on_pre="v+=w")
78 assert S.source.name == S.target.name == G.name
79
80
81 @pytest.mark.codegen_independent
82 def test_creation_errors():
83 G = NeuronGroup(42, "v: 1", threshold="False")
84 # Check that the old Synapses(..., connect=...) syntax raises an error
85 with pytest.raises(TypeError):
86 Synapses(G, G, "w:1", on_pre="v+=w", connect=True)
87 # Check that using pre and on_pre (resp. post/on_post) at the same time
88 # raises an error
89 with pytest.raises(TypeError):
90 Synapses(G, G, "w:1", pre="v+=w", on_pre="v+=w", connect=True)
91 with pytest.raises(TypeError):
92 Synapses(G, G, "w:1", post="v+=w", on_post="v+=w", connect=True)
93
94
95 @pytest.mark.codegen_independent
96 def test_connect_errors():
97 G = NeuronGroup(42, "")
98 S = Synapses(G, G)
99
100 # Not a boolean condition
101 with pytest.raises(TypeError):
102 S.connect("i*2")
103
104 # Unit error
105 with pytest.raises(DimensionMismatchError):
106 S.connect("i > 3*mV")
107
108 # Syntax error
109 with pytest.raises(SyntaxError):
110 S.connect("sin(3, 4) > 1")
111
112 # Unit error in p argument
113 with pytest.raises(TypeError):
114 S.connect("1*mV")
115
116 # Syntax error in p argument
117 with pytest.raises(SyntaxError):
118 S.connect(p="sin(3, 4)")
119
120
121 @pytest.mark.codegen_independent
122 def test_name_clashes():
123 # Using identical names for synaptic and pre- or post-synaptic variables
124 # is confusing and should be forbidden
125 G1 = NeuronGroup(1, "a : 1")
126 G2 = NeuronGroup(1, "b : 1")
127 with pytest.raises(ValueError):
128 Synapses(G1, G2, "a : 1")
129 with pytest.raises(ValueError):
130 Synapses(G1, G2, "b : 1")
131
132 # Using _pre or _post as variable names is confusing (even if it is non-
133 # ambiguous in unconnected NeuronGroups)
134 with pytest.raises(ValueError):
135 Synapses(G1, G2, "x_pre : 1")
136 with pytest.raises(ValueError):
137 Synapses(G1, G2, "x_post : 1")
138 with pytest.raises(ValueError):
139 Synapses(G1, G2, "x_pre = 1 : 1")
140 with pytest.raises(ValueError):
141 Synapses(G1, G2, "x_post = 1 : 1")
142 with pytest.raises(ValueError):
143 NeuronGroup(1, "x_pre : 1")
144 with pytest.raises(ValueError):
145 NeuronGroup(1, "x_post : 1")
146 with pytest.raises(ValueError):
147 NeuronGroup(1, "x_pre = 1 : 1")
148 with pytest.raises(ValueError):
149 NeuronGroup(1, "x_post = 1 : 1")
150
151 # this should all be ok
152 Synapses(G1, G2, "c : 1")
153 Synapses(G1, G2, "a_syn : 1")
154 Synapses(G1, G2, "b_syn : 1")
155
156
157 @pytest.mark.standalone_compatible
158 def test_incoming_outgoing():
159 """
160 Test the count of outgoing/incoming synapses per neuron.
161 (It will be also automatically tested for all connection patterns that
162 use the above _compare function for testing)
163 """
164 G1 = NeuronGroup(5, "")
165 G2 = NeuronGroup(5, "")
166 S = Synapses(G1, G2, "")
167 S.connect(i=[0, 0, 0, 1, 1, 2], j=[0, 1, 2, 1, 2, 3])
168 run(0 * ms) # to make this work for standalone
169 # First source neuron has 3 outgoing synapses, the second 2, the third 1
170 assert all(S.N_outgoing[0, :] == 3)
171 assert all(S.N_outgoing[1, :] == 2)
172 assert all(S.N_outgoing[2, :] == 1)
173 assert all(S.N_outgoing[3:, :] == 0)
174 assert_array_equal(S.N_outgoing_pre, [3, 2, 1, 0, 0])
175 # First target neuron receives 1 input, the second+third each 2, the fourth receives 1
176 assert all(S.N_incoming[:, 0] == 1)
177 assert all(S.N_incoming[:, 1] == 2)
178 assert all(S.N_incoming[:, 2] == 2)
179 assert all(S.N_incoming[:, 3] == 1)
180 assert all(S.N_incoming[:, 4:] == 0)
181 assert_array_equal(S.N_incoming_post, [1, 2, 2, 1, 0])
182
183
184 @pytest.mark.standalone_compatible
185 def test_connection_arrays():
186 """
187 Test connecting synapses with explictly given arrays
188 """
189 G = NeuronGroup(42, "")
190 G2 = NeuronGroup(17, "")
191
192 # one-to-one
193 expected1 = np.eye(len(G2))
194 S1 = Synapses(G2)
195 S1.connect(i=np.arange(len(G2)), j=np.arange(len(G2)))
196
197 # full
198 expected2 = np.ones((len(G), len(G2)))
199 S2 = Synapses(G, G2)
200 X, Y = np.meshgrid(np.arange(len(G)), np.arange(len(G2)))
201 S2.connect(i=X.flatten(), j=Y.flatten())
202
203 # Multiple synapses
204 expected3 = np.zeros((len(G), len(G2)))
205 expected3[3, 3] = 2
206 S3 = Synapses(G, G2)
207 S3.connect(i=[3, 3], j=[3, 3])
208
209 run(0 * ms) # for standalone
210 _compare(S1, expected1)
211 _compare(S2, expected2)
212 _compare(S3, expected3)
213
214 # Incorrect usage
215 S = Synapses(G, G2)
216 with pytest.raises(TypeError):
217 S.connect(i=[1.1, 2.2], j=[1.1, 2.2])
218 with pytest.raises(TypeError):
219 S.connect(i=[1, 2], j="string")
220 with pytest.raises(TypeError):
221 S.connect(i=[1, 2], j=[1, 2], n="i")
222 with pytest.raises(TypeError):
223 S.connect([1, 2])
224 with pytest.raises(ValueError):
225 S.connect(i=[1, 2, 3], j=[1, 2])
226 with pytest.raises(ValueError):
227 S.connect(i=np.ones((3, 3), dtype=np.int32), j=np.ones((3, 1), dtype=np.int32))
228 with pytest.raises(IndexError):
229 S.connect(i=[41, 42], j=[0, 1]) # source index > max
230 with pytest.raises(IndexError):
231 S.connect(i=[0, 1], j=[16, 17]) # target index > max
232 with pytest.raises(IndexError):
233 S.connect(i=[0, -1], j=[0, 1]) # source index < 0
234 with pytest.raises(IndexError):
235 S.connect(i=[0, 1], j=[0, -1]) # target index < 0
236 with pytest.raises(ValueError):
237 S.connect("i==j", j=np.arange(10))
238 with pytest.raises(TypeError):
239 S.connect("i==j", n=object())
240 with pytest.raises(TypeError):
241 S.connect("i==j", p=object())
242 with pytest.raises(TypeError):
243 S.connect(object())
244
245
246 @pytest.mark.standalone_compatible
247 def test_connection_string_deterministic_full():
248 G = NeuronGroup(17, "")
249 G2 = NeuronGroup(4, "")
250
251 # Full connection
252 expected_full = np.ones((len(G), len(G2)))
253
254 S1 = Synapses(G, G2, "")
255 S1.connect(True)
256
257 S2 = Synapses(G, G2, "")
258 S2.connect("True")
259
260 run(0 * ms) # for standalone
261
262 _compare(S1, expected_full)
263 _compare(S2, expected_full)
264
265
266 @pytest.mark.standalone_compatible
267 def test_connection_string_deterministic_full_no_self():
268 G = NeuronGroup(17, "v : 1")
269 G.v = "i"
270 G2 = NeuronGroup(4, "v : 1")
271 G2.v = "17 + i"
272
273 # Full connection without self-connections
274 expected_no_self = np.ones((len(G), len(G))) - np.eye(len(G))
275
276 S1 = Synapses(G, G)
277 S1.connect("i != j")
278
279 S2 = Synapses(G, G)
280 S2.connect("v_pre != v_post")
281
282 S3 = Synapses(G, G)
283 S3.connect(condition="i != j")
284
285 run(0 * ms) # for standalone
286
287 _compare(S1, expected_no_self)
288 _compare(S2, expected_no_self)
289 _compare(S3, expected_no_self)
290
291
292 @pytest.mark.standalone_compatible
293 def test_connection_string_deterministic_full_one_to_one():
294 G = NeuronGroup(17, "v : 1")
295 G.v = "i"
296 G2 = NeuronGroup(4, "v : 1")
297 G2.v = "17 + i"
298
299 # One-to-one connectivity
300 expected_one_to_one = np.eye(len(G))
301
302 S1 = Synapses(G, G)
303 S1.connect("i == j")
304
305 S2 = Synapses(G, G)
306 S2.connect("v_pre == v_post")
307
308 S3 = Synapses(
309 G,
310 G,
311 """
312 sub_1 = v_pre : 1
313 sub_2 = v_post : 1
314 w:1
315 """,
316 )
317 S3.connect("sub_1 == sub_2")
318
319 S4 = Synapses(G, G)
320 S4.connect(j="i")
321
322 run(0 * ms) # for standalone
323
324 _compare(S1, expected_one_to_one)
325 _compare(S2, expected_one_to_one)
326 _compare(S3, expected_one_to_one)
327 _compare(S4, expected_one_to_one)
328
329
330 @pytest.mark.standalone_compatible
331 def test_connection_string_deterministic_full_custom():
332 G = NeuronGroup(17, "")
333 G2 = NeuronGroup(4, "")
334 # Everything except for the upper [2, 2] quadrant
335 number = 2
336 expected_custom = np.ones((len(G), len(G)))
337 expected_custom[:number, :number] = 0
338 S1 = Synapses(G, G)
339 S1.connect("(i >= number) or (j >= number)")
340
341 S2 = Synapses(G, G)
342 S2.connect(
343 "(i >= explicit_number) or (j >= explicit_number)",
344 namespace={"explicit_number": number},
345 )
346
347 # check that this mistaken syntax raises an error
348 with pytest.raises(ValueError):
349 S2.connect("k for k in range(1)")
350
351 # check that trying to connect to a neuron outside the range raises an error
352 if get_device() == all_devices["runtime"]:
353 with pytest.raises(BrianObjectException) as exc:
354 S2.connect(j="20")
355 assert exc_isinstance(exc, IndexError)
356
357 run(0 * ms) # for standalone
358
359 _compare(S1, expected_custom)
360 _compare(S2, expected_custom)
361
362
363 @pytest.mark.standalone_compatible
364 def test_connection_string_deterministic_multiple_and():
365 # In Brian versions 2.1.0-2.1.2, this fails on the numpy target
366 # See github issue 900
367 group = NeuronGroup(10, "")
368 synapses = Synapses(group, group)
369 synapses.connect("i>=5 and i<10 and j>=5")
370 run(0 * ms) # for standalone
371 assert len(synapses) == 25
372
373
374 @pytest.mark.standalone_compatible
375 def test_connection_random_with_condition():
376 G = NeuronGroup(4, "")
377
378 S1 = Synapses(G, G)
379 S1.connect("i!=j", p=0.0)
380
381 S2 = Synapses(G, G)
382 S2.connect("i!=j", p=1.0)
383 expected2 = np.ones((len(G), len(G))) - np.eye(len(G))
384
385 S3 = Synapses(G, G)
386 S3.connect("i>=2", p=0.0)
387
388 S4 = Synapses(G, G)
389 S4.connect("i>=2", p=1.0)
390 expected4 = np.zeros((len(G), len(G)))
391 expected4[2, :] = 1
392 expected4[3, :] = 1
393
394 S5 = Synapses(G, G)
395 S5.connect("j<2", p=0.0)
396 S6 = Synapses(G, G)
397 S6.connect("j<2", p=1.0)
398 expected6 = np.zeros((len(G), len(G)))
399 expected6[:, 0] = 1
400 expected6[:, 1] = 1
401
402 with catch_logs() as _: # Ignore warnings about empty synapses
403 run(0 * ms) # for standalone
404
405 assert len(S1) == 0
406 _compare(S2, expected2)
407 assert len(S3) == 0
408 _compare(S4, expected4)
409 assert len(S5) == 0
410 _compare(S6, expected6)
411
412
413 @pytest.mark.standalone_compatible
414 @pytest.mark.long
415 def test_connection_random_with_condition_2():
416 G = NeuronGroup(4, "")
417
418 # Just checking that everything works in principle (we can't check the
419 # actual connections)
420 S7 = Synapses(G, G)
421 S7.connect("i!=j", p=0.01)
422
423 S8 = Synapses(G, G)
424 S8.connect("i!=j", p=0.03)
425
426 S9 = Synapses(G, G)
427 S9.connect("i!=j", p=0.3)
428
429 S10 = Synapses(G, G)
430 S10.connect("i>=2", p=0.01)
431
432 S11 = Synapses(G, G)
433 S11.connect("i>=2", p=0.03)
434
435 S12 = Synapses(G, G)
436 S12.connect("i>=2", p=0.3)
437
438 S13 = Synapses(G, G)
439 S13.connect("j>=2", p=0.01)
440
441 S14 = Synapses(G, G)
442 S14.connect("j>=2", p=0.03)
443
444 S15 = Synapses(G, G)
445 S15.connect("j>=2", p=0.3)
446
447 S16 = Synapses(G, G)
448 S16.connect("i!=j", p="i*0.1")
449
450 S17 = Synapses(G, G)
451 S17.connect("i!=j", p="j*0.1")
452
453 # Forces the use of the "jump algorithm"
454 big_group = NeuronGroup(10000, "")
455 S18 = Synapses(big_group, big_group)
456 S18.connect("i != j", p=0.001)
457
458 # See github issue #835 -- this failed when using numpy
459 S19 = Synapses(big_group, big_group)
460 S19.connect("i < int(N_post*0.5)", p=0.001)
461
462 with catch_logs() as _: # Ignore warnings about empty synapses
463 run(0 * ms) # for standalone
464
465 assert not any(S7.i == S7.j)
466 assert not any(S8.i == S8.j)
467 assert not any(S9.i == S9.j)
468 assert all(S10.i >= 2)
469 assert all(S11.i >= 2)
470 assert all(S12.i >= 2)
471 assert all(S13.j >= 2)
472 assert all(S14.j >= 2)
473 assert all(S15.j >= 2)
474 assert not any(S16.i == 0)
475 assert not any(S17.j == 0)
476
477
478 @pytest.mark.standalone_compatible
479 def test_connection_random_with_indices():
480 """
481 Test random connections.
482 """
483 G = NeuronGroup(4, "")
484 G2 = NeuronGroup(7, "")
485
486 S1 = Synapses(G, G2)
487 S1.connect(i=0, j=0, p=0.0)
488 expected1 = np.zeros((len(G), len(G2)))
489
490 S2 = Synapses(G, G2)
491 S2.connect(i=0, j=0, p=1.0)
492 expected2 = np.zeros((len(G), len(G2)))
493 expected2[0, 0] = 1
494
495 S3 = Synapses(G, G2)
496 S3.connect(i=[0, 1], j=[0, 2], p=1.0)
497 expected3 = np.zeros((len(G), len(G2)))
498 expected3[0, 0] = 1
499 expected3[1, 2] = 1
500
501 # Just checking that it works in principle
502 S4 = Synapses(G, G)
503 S4.connect(i=0, j=0, p=0.01)
504 S5 = Synapses(G, G)
505 S5.connect(i=[0, 1], j=[0, 2], p=0.01)
506
507 S6 = Synapses(G, G)
508 S6.connect(i=0, j=0, p=0.03)
509
510 S7 = Synapses(G, G)
511 S7.connect(i=[0, 1], j=[0, 2], p=0.03)
512
513 S8 = Synapses(G, G)
514 S8.connect(i=0, j=0, p=0.3)
515
516 S9 = Synapses(G, G)
517 S9.connect(i=[0, 1], j=[0, 2], p=0.3)
518
519 with catch_logs() as _: # Ignore warnings about empty synapses
520 run(0 * ms) # for standalone
521
522 _compare(S1, expected1)
523 _compare(S2, expected2)
524 _compare(S3, expected3)
525 assert 0 <= len(S4) <= 1
526 assert 0 <= len(S5) <= 2
527 assert 0 <= len(S6) <= 1
528 assert 0 <= len(S7) <= 2
529 assert 0 <= len(S8) <= 1
530 assert 0 <= len(S9) <= 2
531
532
533 @pytest.mark.standalone_compatible
534 def test_connection_random_without_condition():
535 G = NeuronGroup(
536 4,
537 """
538 v: 1
539 x : integer
540 """,
541 )
542 G.x = "i"
543 G2 = NeuronGroup(
544 7,
545 """
546 v: 1
547 y : 1
548 """,
549 )
550 G2.y = "1.0*i/N"
551
552 S1 = Synapses(G, G2)
553 S1.connect(True, p=0.0)
554
555 S2 = Synapses(G, G2)
556 S2.connect(True, p=1.0)
557
558 # Just make sure using values between 0 and 1 work in principle
559 S3 = Synapses(G, G2)
560 S3.connect(True, p=0.3)
561
562 # Use pre-/post-synaptic variables for "stochastic" connections that are
563 # actually deterministic
564 S4 = Synapses(G, G2)
565 S4.connect(True, p="int(x_pre==2)*1.0")
566
567 # Use pre-/post-synaptic variables for "stochastic" connections that are
568 # actually deterministic
569 S5 = Synapses(G, G2)
570 S5.connect(True, p="int(x_pre==2 and y_post > 0.5)*1.0")
571
572 with catch_logs() as _: # Ignore warnings about empty synapses
573 run(0 * ms) # for standalone
574
575 _compare(S1, np.zeros((len(G), len(G2))))
576 _compare(S2, np.ones((len(G), len(G2))))
577 assert 0 <= len(S3) <= len(G) * len(G2)
578 assert len(S4) == 7
579 assert_equal(S4.i, np.ones(7) * 2)
580 assert_equal(S4.j, np.arange(7))
581 assert len(S5) == 3
582 assert_equal(S5.i, np.ones(3) * 2)
583 assert_equal(S5.j, np.arange(3) + 4)
584
585
586 @pytest.mark.standalone_compatible
587 def test_connection_multiple_synapses():
588 """
589 Test multiple synapses per connection.
590 """
591 G = NeuronGroup(42, "v: 1")
592 G.v = "i"
593 G2 = NeuronGroup(17, "v: 1")
594 G2.v = "i"
595
596 S1 = Synapses(G, G2)
597 S1.connect(True, n=0)
598
599 S2 = Synapses(G, G2)
600 S2.connect(True, n=2)
601
602 S3 = Synapses(G, G2)
603 S3.connect(True, n="j")
604
605 S4 = Synapses(G, G2)
606 S4.connect(True, n="i")
607
608 S5 = Synapses(G, G2)
609 S5.connect(True, n="int(i>j)*2")
610
611 S6 = Synapses(G, G2)
612 S6.connect(True, n="int(v_pre>v_post)*2")
613
614 with catch_logs() as _: # Ignore warnings about empty synapses
615 run(0 * ms) # for standalone
616
617 assert len(S1) == 0
618 _compare(S2, 2 * np.ones((len(G), len(G2))))
619 _compare(S3, np.arange(len(G2)).reshape(1, len(G2)).repeat(len(G), axis=0))
620
621 _compare(S4, np.arange(len(G)).reshape(len(G), 1).repeat(len(G2), axis=1))
622 expected = np.zeros((len(G), len(G2)), dtype=np.int32)
623 for source in range(len(G)):
624 expected[source, :source] = 2
625 _compare(S5, expected)
626 _compare(S6, expected)
627
628
629 def test_state_variable_assignment():
630 """
631 Assign values to state variables in various ways
632 """
633
634 G = NeuronGroup(10, "v: volt")
635 G.v = "i*mV"
636 S = Synapses(G, G, "w:volt")
637 S.connect(True)
638
639 # with unit checking
640 assignment_expected = [
641 (5 * mV, np.ones(100) * 5 * mV),
642 (7 * mV, np.ones(100) * 7 * mV),
643 (S.i[:] * mV, S.i[:] * np.ones(100) * mV),
644 ("5*mV", np.ones(100) * 5 * mV),
645 ("i*mV", np.ones(100) * S.i[:] * mV),
646 ("i*mV +j*mV", S.i[:] * mV + S.j[:] * mV),
647 # reference to pre- and postsynaptic state variables
648 ("v_pre", S.i[:] * mV),
649 ("v_post", S.j[:] * mV),
650 # ('i*mV + j*mV + k*mV', S.i[:]*mV + S.j[:]*mV + S.k[:]*mV) #not supported yet
651 ]
652
653 for assignment, expected in assignment_expected:
654 S.w = 0 * volt
655 S.w = assignment
656 assert_allclose(
657 S.w[:], expected, err_msg="Assigning %r gave incorrect result" % assignment
658 )
659 S.w = 0 * volt
660 S.w[:] = assignment
661 assert_allclose(
662 S.w[:], expected, err_msg="Assigning %r gave incorrect result" % assignment
663 )
664
665 # without unit checking
666 assignment_expected = [
667 (5, np.ones(100) * 5 * volt),
668 (7, np.ones(100) * 7 * volt),
669 (S.i[:], S.i[:] * np.ones(100) * volt),
670 ("5", np.ones(100) * 5 * volt),
671 ("i", np.ones(100) * S.i[:] * volt),
672 ("i +j", S.i[:] * volt + S.j[:] * volt),
673 # ('i + j + k', S.i[:]*volt + S.j[:]*volt + S.k[:]*volt) #not supported yet
674 ]
675
676 for assignment, expected in assignment_expected:
677 S.w = 0 * volt
678 S.w_ = assignment
679 assert_allclose(
680 S.w[:], expected, err_msg="Assigning %r gave incorrect result" % assignment
681 )
682 S.w = 0 * volt
683 S.w_[:] = assignment
684 assert_allclose(
685 S.w[:], expected, err_msg="Assigning %r gave incorrect result" % assignment
686 )
687
688
689 def test_state_variable_indexing():
690 G1 = NeuronGroup(5, "v:volt")
691 G1.v = "i*mV"
692 G2 = NeuronGroup(7, "v:volt")
693 G2.v = "10*mV + i*mV"
694 S = Synapses(G1, G2, "w:1", multisynaptic_index="k")
695 S.connect(True, n=2)
696 S.w[:, :, 0] = "5*i + j"
697 S.w[:, :, 1] = "35 + 5*i + j"
698
699 # Slicing
700 assert len(S.w[:]) == len(S.w[:, :]) == len(S.w[:, :, :]) == len(G1) * len(G2) * 2
701 assert len(S.w[0:, 0:]) == len(S.w[0:, 0:, 0:]) == len(G1) * len(G2) * 2
702 assert len(S.w[0::2, 0:]) == 3 * len(G2) * 2
703 assert len(S.w[0, :]) == len(S.w[0, :, :]) == len(G2) * 2
704 assert len(S.w[0:2, :]) == len(S.w[0:2, :, :]) == 2 * len(G2) * 2
705 assert len(S.w[:2, :]) == len(S.w[:2, :, :]) == 2 * len(G2) * 2
706 assert len(S.w[0:4:2, :]) == len(S.w[0:4:2, :, :]) == 2 * len(G2) * 2
707 assert len(S.w[:4:2, :]) == len(S.w[:4:2, :, :]) == 2 * len(G2) * 2
708 assert len(S.w[:, 0]) == len(S.w[:, 0, :]) == len(G1) * 2
709 assert len(S.w[:, 0:2]) == len(S.w[:, 0:2, :]) == 2 * len(G1) * 2
710 assert len(S.w[:, :2]) == len(S.w[:, :2, :]) == 2 * len(G1) * 2
711 assert len(S.w[:, 0:4:2]) == len(S.w[:, 0:4:2, :]) == 2 * len(G1) * 2
712 assert len(S.w[:, :4:2]) == len(S.w[:, :4:2, :]) == 2 * len(G1) * 2
713 assert len(S.w[:, :, 0]) == len(G1) * len(G2)
714 assert len(S.w[:, :, 0:2]) == len(G1) * len(G2) * 2
715 assert len(S.w[:, :, :2]) == len(G1) * len(G2) * 2
716 assert len(S.w[:, :, 0:2:2]) == len(G1) * len(G2)
717 assert len(S.w[:, :, :2:2]) == len(G1) * len(G2)
718
719 # 1d indexing is directly indexing synapses!
720 assert len(S.w[:]) == len(S.w[0:])
721 assert len(S.w[[0, 1]]) == len(S.w[3:5]) == 2
722 assert len(S.w[:]) == len(S.w[np.arange(len(G1) * len(G2) * 2)])
723 assert S.w[3] == S.w[np.int32(3)] == S.w[np.int64(3)] # See issue #888
724
725 # Array-indexing (not yet supported for synapse index)
726 assert_equal(S.w[:, 0:3], S.w[:, [0, 1, 2]])
727 assert_equal(S.w[:, 0:3], S.w[np.arange(len(G1)), [0, 1, 2]])
728
729 # string-based indexing
730 assert_equal(S.w[0:3, :], S.w["i<3"])
731 assert_equal(S.w[:, 0:3], S.w["j<3"])
732 assert_equal(S.w[:, :, 0], S.w["k == 0"])
733 assert_equal(S.w[0:3, :], S.w["v_pre < 2.5*mV"])
734 assert_equal(S.w[:, 0:3], S.w["v_post < 12.5*mV"])
735
736 # invalid indices
737 with pytest.raises(IndexError):
738 S.w.__getitem__((1, 2, 3, 4))
739 with pytest.raises(IndexError):
740 S.w.__getitem__(object())
741 with pytest.raises(IndexError):
742 S.w.__getitem__(1.5)
743
744
745 def test_indices():
746 G = NeuronGroup(10, "v : 1")
747 S = Synapses(G, G, "")
748 S.connect()
749 G.v = "i"
750
751 assert_equal(S.indices[:], np.arange(10 * 10))
752 assert len(S.indices[5, :]) == 10
753 assert_equal(S.indices["v_pre >=5"], S.indices[5:, :])
754 assert_equal(S.indices["j >=5"], S.indices[:, 5:])
755
756
757 def test_subexpression_references():
758 """
759 Assure that subexpressions in targeted groups are handled correctly.
760 """
761 G = NeuronGroup(
762 10,
763 """
764 v : 1
765 v2 = 2*v : 1
766 """,
767 )
768 G.v = np.arange(10)
769 S = Synapses(
770 G,
771 G,
772 """
773 w : 1
774 u = v2_post + 1 : 1
775 x = v2_pre + 1 : 1
776 """,
777 )
778 S.connect("i==(10-1-j)")
779 assert_equal(S.u[:], np.arange(10)[::-1] * 2 + 1)
780 assert_equal(S.x[:], np.arange(10) * 2 + 1)
781
782
783 @pytest.mark.standalone_compatible
784 def test_constant_variable_subexpression_in_synapses():
785 G = NeuronGroup(10, "")
786 S = Synapses(
787 G,
788 G,
789 """
790 dv1/dt = -v1**2 / (10*ms) : 1 (clock-driven)
791 dv2/dt = -v_const**2 / (10*ms) : 1 (clock-driven)
792 dv3/dt = -v_var**2 / (10*ms) : 1 (clock-driven)
793 dv4/dt = -v_noflag**2 / (10*ms) : 1 (clock-driven)
794 v_const = v2 : 1 (constant over dt)
795 v_var = v3 : 1
796 v_noflag = v4 : 1
797 """,
798 method="rk2",
799 )
800 S.connect(j="i")
801 S.v1 = "1.0*i/N"
802 S.v2 = "1.0*i/N"
803 S.v3 = "1.0*i/N"
804 S.v4 = "1.0*i/N"
805
806 run(10 * ms)
807 # "variable over dt" subexpressions are directly inserted into the equation
808 assert_allclose(S.v3[:], S.v1[:])
809 assert_allclose(S.v4[:], S.v1[:])
810 # "constant over dt" subexpressions will keep a fixed value over the time
811 # step and therefore give a slightly different result for multi-step
812 # methods
813 assert np.sum((S.v2 - S.v1) ** 2) > 1e-10
814
815
816 @pytest.mark.standalone_compatible
817 def test_nested_subexpression_references():
818 """
819 Assure that subexpressions in targeted groups are handled correctly.
820 """
821 G = NeuronGroup(
822 10,
823 """
824 v : 1
825 v2 = 2*v : 1
826 v3 = 1.5*v2 : 1
827 """,
828 threshold="v>=5",
829 )
830 G2 = NeuronGroup(10, "v : 1")
831 G.v = np.arange(10)
832 S = Synapses(G, G2, on_pre="v_post += v3_pre")
833 S.connect(j="i")
834 run(defaultclock.dt)
835 assert_allclose(G2.v[:5], 0.0)
836 assert_allclose(G2.v[5:], (5 + np.arange(5)) * 3)
837
838
839 @pytest.mark.codegen_independent
840 def test_equations_unit_check():
841 group = NeuronGroup(1, "v : volt", threshold="True")
842 syn = Synapses(
843 group,
844 group,
845 """
846 sub1 = 3 : 1
847 sub2 = sub1 + 1*mV : volt
848 """,
849 on_pre="v += sub2",
850 )
851 syn.connect()
852 net = Network(group, syn)
853 with pytest.raises(BrianObjectException) as exc:
854 net.run(0 * ms)
855 assert exc_isinstance(exc, DimensionMismatchError)
856
857
858 def test_delay_specification():
859 # By default delays are state variables (i.e. arrays), but if they are
860 # specified in the initializer, they are scalars.
861 G = NeuronGroup(10, "x : meter", threshold="False")
862 G.x = "i*mmeter"
863 # Array delay
864 S = Synapses(G, G, "w:1", on_pre="v+=w")
865 S.connect(j="i")
866 assert len(S.delay[:]) == len(G)
867 S.delay = "i*ms"
868 assert_allclose(S.delay[:], np.arange(len(G)) * ms)
869 velocity = 1 * meter / second
870 S.delay = "abs(x_pre - (N_post-j)*mmeter)/velocity"
871 assert_allclose(S.delay[:], abs(G.x - (10 - G.i) * mmeter) / velocity)
872 S.delay = 5 * ms
873 assert_allclose(S.delay[:], np.ones(len(G)) * 5 * ms)
874 # Setting delays without units
875 S.delay_ = float(7 * ms)
876 assert_allclose(S.delay[:], np.ones(len(G)) * 7 * ms)
877
878 # Scalar delay
879 S = Synapses(G, G, "w:1", on_pre="v+=w", delay=5 * ms)
880 assert_allclose(S.delay[:], 5 * ms)
881 S.connect(j="i")
882 S.delay = "3*ms"
883 assert_allclose(S.delay[:], 3 * ms)
884 S.delay = 10 * ms
885 assert_allclose(S.delay[:], 10 * ms)
886 # Without units
887 S.delay_ = float(20 * ms)
888 assert_allclose(S.delay[:], 20 * ms)
889
890 # Invalid arguments
891 with pytest.raises(DimensionMismatchError):
892 Synapses(G, G, "w:1", on_pre="v+=w", delay=5 * mV)
893 with pytest.raises(TypeError):
894 Synapses(G, G, "w:1", on_pre="v+=w", delay=object())
895 with pytest.raises(ValueError):
896 Synapses(G, G, "w:1", delay=5 * ms)
897 with pytest.raises(ValueError):
898 Synapses(G, G, "w:1", on_pre="v+=w", delay={"post": 5 * ms})
899
900
901 def test_delays_pathways():
902 G = NeuronGroup(10, "x: meter", threshold="False")
903 G.x = "i*mmeter"
904 # Array delay
905 S = Synapses(G, G, "w:1", on_pre={"pre1": "v+=w", "pre2": "v+=w"}, on_post="v-=w")
906 S.connect(j="i")
907 assert len(S.pre1.delay[:]) == len(G)
908 assert len(S.pre2.delay[:]) == len(G)
909 assert len(S.post.delay[:]) == len(G)
910 S.pre1.delay = "i*ms"
911 S.pre2.delay = "j*ms"
912 velocity = 1 * meter / second
913 S.post.delay = "abs(x_pre - (N_post-j)*mmeter)/velocity"
914 assert_allclose(S.pre1.delay[:], np.arange(len(G)) * ms)
915 assert_allclose(S.pre2.delay[:], np.arange(len(G)) * ms)
916 assert_allclose(S.post.delay[:], abs(G.x - (10 - G.i) * mmeter) / velocity)
917 S.pre1.delay = 5 * ms
918 S.pre2.delay = 10 * ms
919 S.post.delay = 1 * ms
920 assert_allclose(S.pre1.delay[:], np.ones(len(G)) * 5 * ms)
921 assert_allclose(S.pre2.delay[:], np.ones(len(G)) * 10 * ms)
922 assert_allclose(S.post.delay[:], np.ones(len(G)) * 1 * ms)
923 # Indexing with strings
924 assert len(S.pre1.delay["j<5"]) == 5
925 assert_allclose(S.pre1.delay["j<5"], 5 * ms)
926 # Indexing with 2d indices
927 assert len(S.post.delay[[3, 4], :]) == 2
928 assert_allclose(S.post.delay[[3, 4], :], 1 * ms)
929 assert len(S.pre2.delay[:, 7]) == 1
930 assert_allclose(S.pre2.delay[:, 7], 10 * ms)
931 assert len(S.pre1.delay[[1, 2], [1, 2]]) == 2
932 assert_allclose(S.pre1.delay[[1, 2], [1, 2]], 5 * ms)
933
934 # Scalar delay
935 S = Synapses(
936 G,
937 G,
938 "w:1",
939 on_pre={"pre1": "v+=w", "pre2": "v+=w"},
940 on_post="v-=w",
941 delay={"pre1": 5 * ms, "post": 1 * ms},
942 )
943 assert_allclose(S.pre1.delay[:], 5 * ms)
944 assert_allclose(S.post.delay[:], 1 * ms)
945 S.connect(j="i")
946 assert len(S.pre2.delay[:]) == len(G)
947 S.pre1.delay = 10 * ms
948 assert_allclose(S.pre1.delay[:], 10 * ms)
949 S.post.delay = "3*ms"
950 assert_allclose(S.post.delay[:], 3 * ms)
951
952
953 def test_delays_pathways_subgroups():
954 G = NeuronGroup(10, "x: meter", threshold="False")
955 G.x = "i*mmeter"
956 # Array delay
957 S = Synapses(
958 G[:5], G[5:], "w:1", on_pre={"pre1": "v+=w", "pre2": "v+=w"}, on_post="v-=w"
959 )
960 S.connect(j="i")
961 assert len(S.pre1.delay[:]) == 5
962 assert len(S.pre2.delay[:]) == 5
963 assert len(S.post.delay[:]) == 5
964 S.pre1.delay = "i*ms"
965 S.pre2.delay = "j*ms"
966 velocity = 1 * meter / second
967 S.post.delay = "abs(x_pre - (N_post-j)*mmeter)/velocity"
968 assert_allclose(S.pre1.delay[:], np.arange(5) * ms)
969 assert_allclose(S.pre2.delay[:], np.arange(5) * ms)
970 assert_allclose(S.post.delay[:], abs(G[:5].x - (5 - G[:5].i) * mmeter) / velocity)
971 S.pre1.delay = 5 * ms
972 S.pre2.delay = 10 * ms
973 S.post.delay = 1 * ms
974 assert_allclose(S.pre1.delay[:], np.ones(5) * 5 * ms)
975 assert_allclose(S.pre2.delay[:], np.ones(5) * 10 * ms)
976 assert_allclose(S.post.delay[:], np.ones(5) * 1 * ms)
977
978
979 @pytest.mark.codegen_independent
980 def test_pre_before_post():
981 # The pre pathway should be executed before the post pathway
982 G = NeuronGroup(
983 1,
984 """
985 x : 1
986 y : 1
987 """,
988 threshold="True",
989 )
990 S = Synapses(G, G, "", on_pre="x=1; y=1", on_post="x=2")
991 S.connect()
992 run(defaultclock.dt)
993 # Both pathways should have been executed, but post should have overriden
994 # the x value (because it was executed later)
995 assert G.x == 2
996 assert G.y == 1
997
998
999 @pytest.mark.standalone_compatible
1000 def test_pre_post_simple():
1001 # Test that pre and post still work correctly
1002 G1 = SpikeGeneratorGroup(1, [0], [1] * ms)
1003 G2 = SpikeGeneratorGroup(1, [0], [2] * ms)
1004 with catch_logs() as l:
1005 S = Synapses(
1006 G1,
1007 G2,
1008 """
1009 pre_value : 1
1010 post_value : 1
1011 """,
1012 pre="pre_value +=1",
1013 post="post_value +=2",
1014 )
1015 S.connect()
1016 syn_mon = StateMonitor(S, ["pre_value", "post_value"], record=[0], when="end")
1017 run(3 * ms)
1018 offset = schedule_propagation_offset()
1019 assert_allclose(syn_mon.pre_value[0][syn_mon.t < 1 * ms + offset], 0)
1020 assert_allclose(syn_mon.pre_value[0][syn_mon.t >= 1 * ms + offset], 1)
1021 assert_allclose(syn_mon.post_value[0][syn_mon.t < 2 * ms + offset], 0)
1022 assert_allclose(syn_mon.post_value[0][syn_mon.t >= 2 * ms + offset], 2)
1023
1024
1025 @pytest.mark.standalone_compatible
1026 def test_transmission_simple():
1027 source = SpikeGeneratorGroup(2, [0, 1], [2, 1] * ms)
1028 target = NeuronGroup(2, "v : 1")
1029 syn = Synapses(source, target, on_pre="v += 1")
1030 syn.connect(j="i")
1031 mon = StateMonitor(target, "v", record=True, when="end")
1032 run(2.5 * ms)
1033 offset = schedule_propagation_offset()
1034 assert_allclose(mon[0].v[mon.t < 2 * ms + offset], 0.0)
1035 assert_allclose(mon[0].v[mon.t >= 2 * ms + offset], 1.0)
1036 assert_allclose(mon[1].v[mon.t < 1 * ms + offset], 0.0)
1037 assert_allclose(mon[1].v[mon.t >= 1 * ms + offset], 1.0)
1038
1039
1040 @pytest.mark.standalone_compatible
1041 def test_transmission_custom_event():
1042 source = NeuronGroup(
1043 2,
1044 "",
1045 events={
1046 "custom": (
1047 "timestep(t,dt)>=timestep((2-i)*ms, dt) "
1048 "and timestep(t,dt)<timestep((2-i)*ms + dt, dt)"
1049 )
1050 },
1051 )
1052 target = NeuronGroup(2, "v : 1")
1053 syn = Synapses(source, target, on_pre="v += 1", on_event="custom")
1054 syn.connect(j="i")
1055 mon = StateMonitor(target, "v", record=True, when="end")
1056 run(2.5 * ms)
1057 assert_allclose(mon[0].v[mon.t < 2 * ms], 0.0)
1058 assert_allclose(mon[0].v[mon.t >= 2 * ms], 1.0)
1059 assert_allclose(mon[1].v[mon.t < 1 * ms], 0.0)
1060 assert_allclose(mon[1].v[mon.t >= 1 * ms], 1.0)
1061
1062
1063 @pytest.mark.standalone_compatible
1064 def test_transmission_custom_event_complex():
1065 # This was broken with release 2.6, entries in on_event where checked against pre/post
1066 # instead of the pathway name
1067 group = NeuronGroup(3, "v:1", threshold="v>1 and v<2", events={"over_2": "v>2"})
1068 group.v = [0, 1.5, 2.5]
1069
1070 s = Synapses(
1071 group,
1072 group,
1073 model="""a:integer
1074 b:integer
1075 c:integer
1076 d:integer""",
1077 on_event={
1078 "path_a": "spike",
1079 "path_b": "over_2",
1080 "path_c": "spike",
1081 "path_d": "over_2",
1082 },
1083 on_pre={"path_a": "a+=1", "path_b": "b+=1"},
1084 on_post={"path_c": "c+=1", "path_d": "d+=1"},
1085 )
1086 s.connect()
1087 run(defaultclock.dt)
1088 assert all(s.a[:] == [0, 0, 0, 1, 1, 1, 0, 0, 0])
1089 assert all(s.b[:] == [0, 0, 0, 0, 0, 0, 1, 1, 1])
1090 assert all(s.c[:] == [0, 1, 0, 0, 1, 0, 0, 1, 0])
1091 assert all(s.d[:] == [0, 0, 1, 0, 0, 1, 0, 0, 1])
1092
1093
1094 @pytest.mark.codegen_independent
1095 def test_invalid_custom_event():
1096 group1 = NeuronGroup(
1097 2,
1098 "v : 1",
1099 events={
1100 "custom": (
1101 "timestep(t,dt)>=timesteep((2-i)*ms,dt) "
1102 "and timestep(t, dt)<timestep((2-i)*ms + dt, dt)"
1103 )
1104 },
1105 )
1106 group2 = NeuronGroup(2, "v : 1", threshold="v>1")
1107 with pytest.raises(ValueError) as ex:
1108 Synapses(group1, group1, on_pre="v+=1")
1109 assert "threshold" in str(ex) # Check that it mentions the threshold arg
1110 with pytest.raises(ValueError):
1111 Synapses(group2, group2, on_pre="v+=1", on_event="custom")
1112
1113
1114 def test_transmission():
1115 default_dt = defaultclock.dt
1116 delays = [
1117 [0, 0, 0, 0] * ms,
1118 [1, 1, 1, 0] * ms,
1119 [0, 1, 2, 3] * ms,
1120 [2, 2, 0, 0] * ms,
1121 [2, 1, 0, 1] * ms,
1122 ]
1123 for delay in delays:
1124 # Make sure that the Synapses class actually propagates spikes :)
1125 source = NeuronGroup(
1126 4,
1127 """
1128 dv/dt = rate : 1
1129 rate : Hz
1130 """,
1131 threshold="v>1",
1132 reset="v=0",
1133 )
1134 source.rate = [51, 101, 101, 51] * Hz
1135 target = NeuronGroup(4, "v:1", threshold="v>1", reset="v=0")
1136
1137 source_mon = SpikeMonitor(source)
1138 target_mon = SpikeMonitor(target)
1139
1140 S = Synapses(source, target, on_pre="v+=1.1")
1141 S.connect(j="i")
1142 S.delay = delay
1143 net = Network(S, source, target, source_mon, target_mon)
1144 net.run(50 * ms + default_dt + max(delay))
1145 # All spikes should trigger spikes in the receiving neurons with
1146 # the respective delay ( + one dt)
1147 for d in range(len(delay)):
1148 assert_allclose(
1149 source_mon.t[source_mon.i == d],
1150 target_mon.t[target_mon.i == d] - default_dt - delay[d],
1151 )
1152
1153
1154 @pytest.mark.standalone_compatible
1155 def test_transmission_all_to_one_heterogeneous_delays():
1156 source = SpikeGeneratorGroup(
1157 6,
1158 [0, 1, 4, 5, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5],
1159 [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2] * defaultclock.dt,
1160 )
1161 target = NeuronGroup(1, "v : 1")
1162 synapses = Synapses(source, target, "w : 1", on_pre="v_post += w")
1163 synapses.connect()
1164 synapses.w = [1, 2, 3, 4, 5, 6]
1165 synapses.delay = [0, 0, 0, 1, 2, 1] * defaultclock.dt
1166
1167 mon = StateMonitor(target, "v", record=True, when="end")
1168 if schedule_propagation_offset() == 0 * second:
1169 offset = 0
1170 else:
1171 offset = 1
1172 run((4 + offset) * defaultclock.dt)
1173 assert mon[0].v[0 + offset] == 3
1174 assert mon[0].v[1 + offset] == 12
1175 assert mon[0].v[2 + offset] == 33
1176 assert mon[0].v[3 + offset] == 48
1177
1178
1179 @pytest.mark.standalone_compatible
1180 def test_transmission_one_to_all_heterogeneous_delays():
1181 source = SpikeGeneratorGroup(1, [0, 0], [0, 2] * defaultclock.dt)
1182 target = NeuronGroup(6, "v:integer")
1183 synapses = Synapses(source, target, on_pre="v_post += 1")
1184 synapses.connect()
1185 synapses.delay = [
1186 1,
1187 1,
1188 2,
1189 4,
1190 3,
1191 2,
1192 ] * defaultclock.dt - schedule_propagation_offset()
1193
1194 mon = StateMonitor(target, "v", record=True, when="end")
1195 run(5 * defaultclock.dt)
1196 assert_allclose(mon[0].v, [0, 1, 1, 2, 2])
1197 assert_allclose(mon[1].v, [0, 1, 1, 2, 2])
1198 assert_allclose(mon[2].v, [0, 0, 1, 1, 2])
1199 assert_allclose(mon[3].v, [0, 0, 0, 0, 1])
1200 assert_allclose(mon[4].v, [0, 0, 0, 1, 1])
1201 assert_allclose(mon[5].v, [0, 0, 1, 1, 2])
1202
1203
1204 @pytest.mark.standalone_compatible
1205 def test_transmission_scalar_delay():
1206 inp = SpikeGeneratorGroup(2, [0, 1], [0, 1] * ms)
1207 target = NeuronGroup(2, "v:1")
1208 S = Synapses(inp, target, on_pre="v+=1", delay=0.5 * ms)
1209 S.connect(j="i")
1210 mon = StateMonitor(target, "v", record=True, when="end")
1211 run(2 * ms)
1212 offset = schedule_propagation_offset()
1213 assert_allclose(mon[0].v[mon.t < 0.5 * ms + offset - defaultclock.dt / 2], 0)
1214 assert_allclose(mon[0].v[mon.t >= 0.5 * ms + offset - defaultclock.dt / 2], 1)
1215 assert_allclose(mon[1].v[mon.t < 1.5 * ms + offset - defaultclock.dt / 2], 0)
1216 assert_allclose(mon[1].v[mon.t >= 1.5 * ms + offset - defaultclock.dt / 2], 1)
1217
1218
1219 @pytest.mark.standalone_compatible
1220 def test_transmission_scalar_delay_different_clocks():
1221 inp = SpikeGeneratorGroup(
1222 2,
1223 [0, 1],
1224 [0, 1] * ms,
1225 dt=0.5 * ms,
1226 # give the group a unique name to always
1227 # get a 'fresh' warning
1228 name="sg_%d" % uuid.uuid4(),
1229 )
1230 target = NeuronGroup(2, "v:1", dt=0.1 * ms)
1231 S = Synapses(inp, target, on_pre="v+=1", delay=0.5 * ms)
1232 S.connect(j="i")
1233 mon = StateMonitor(target, "v", record=True, when="end")
1234
1235 if get_device() == all_devices["runtime"]:
1236 # We should get a warning when using inconsistent dts
1237 with catch_logs() as l:
1238 run(2 * ms)
1239 assert len(l) == 1, "expected a warning, got %d" % len(l)
1240 assert l[0][1].endswith("synapses_dt_mismatch")
1241
1242 run(0 * ms)
1243 assert_allclose(mon[0].v[mon.t < 0.5 * ms], 0)
1244 assert_allclose(mon[0].v[mon.t >= 0.5 * ms], 1)
1245 assert_allclose(mon[1].v[mon.t < 1.5 * ms], 0)
1246 assert_allclose(mon[1].v[mon.t >= 1.5 * ms], 1)
1247
1248
1249 @pytest.mark.standalone_compatible
1250 def test_transmission_boolean_variable():
1251 source = SpikeGeneratorGroup(4, [0, 1, 2, 3], [2, 1, 2, 1] * ms)
1252 target = NeuronGroup(4, "v : 1")
1253 syn = Synapses(source, target, "use : boolean (constant)", on_pre="v += int(use)")
1254 syn.connect(j="i")
1255 syn.use = "i<2"
1256 mon = StateMonitor(target, "v", record=True, when="end")
1257 run(2.5 * ms)
1258 offset = schedule_propagation_offset()
1259 assert_allclose(mon[0].v[mon.t < 2 * ms + offset], 0.0)
1260 assert_allclose(mon[0].v[mon.t >= 2 * ms + offset], 1.0)
1261 assert_allclose(mon[1].v[mon.t < 1 * ms + offset], 0.0)
1262 assert_allclose(mon[1].v[mon.t >= 1 * ms + offset], 1.0)
1263 assert_allclose(mon[2].v, 0.0)
1264 assert_allclose(mon[3].v, 0.0)
1265
1266
1267 @pytest.mark.codegen_independent
1268 def test_clocks():
1269 """
1270 Make sure that a `Synapse` object uses the correct clocks.
1271 """
1272 source_dt = 0.05 * ms
1273 target_dt = 0.1 * ms
1274 synapse_dt = 0.2 * ms
1275 source = NeuronGroup(1, "v:1", dt=source_dt, threshold="False")
1276 target = NeuronGroup(1, "v:1", dt=target_dt, threshold="False")
1277 synapse = Synapses(
1278 source, target, "w:1", on_pre="v+=1", on_post="v+=1", dt=synapse_dt
1279 )
1280 synapse.connect()
1281
1282 assert synapse.pre.clock is source.clock
1283 assert synapse.post.clock is target.clock
1284 assert synapse.pre._clock.dt == source_dt
1285 assert synapse.post._clock.dt == target_dt
1286 assert synapse._clock.dt == synapse_dt
1287
1288
1289 def test_equations_with_clocks():
1290 """
1291 Make sure that dt of a `Synapse` object is correctly resolved.
1292 """
1293 source_dt = 0.1 * ms
1294 synapse_dt = 1 * ms
1295 source_target = NeuronGroup(1, "v:1", dt=source_dt, threshold="False")
1296 synapse = Synapses(
1297 source_target,
1298 source_target,
1299 "dw/dt = 1/ms : 1 (clock-driven)",
1300 dt=synapse_dt,
1301 method="euler",
1302 )
1303 synapse.connect()
1304 synapse.w = 0
1305 run(1 * ms)
1306
1307 assert synapse.w[0] == 1
1308
1309
1310 def test_changed_dt_spikes_in_queue():
1311 defaultclock.dt = 0.5 * ms
1312 G1 = NeuronGroup(1, "v:1", threshold="v>1", reset="v=0")
1313 G1.v = 1.1
1314 G2 = NeuronGroup(10, "v:1", threshold="v>1", reset="v=0")
1315 S = Synapses(G1, G2, on_pre="v+=1.1")
1316 S.connect(True)
1317 S.delay = "j*ms"
1318 mon = SpikeMonitor(G2)
1319 net = Network(G1, G2, S, mon)
1320 net.run(5 * ms)
1321 defaultclock.dt = 1 * ms
1322 net.run(3 * ms)
1323 defaultclock.dt = 0.1 * ms
1324 net.run(2 * ms)
1325 # Spikes should have delays of 0, 1, 2, ... ms and always
1326 # trigger a spike one dt later
1327 expected = [
1328 0.5,
1329 1.5,
1330 2.5,
1331 3.5,
1332 4.5, # dt=0.5ms
1333 6,
1334 7,
1335 8, # dt = 1ms
1336 8.1,
1337 9.1, # dt=0.1ms
1338 ] * ms
1339 assert_allclose(mon.t[:], expected)
1340
1341
1342 @pytest.mark.codegen_independent
1343 def test_no_synapses():
1344 # Synaptic pathway but no synapses
1345 G1 = NeuronGroup(1, "", threshold="True")
1346 G2 = NeuronGroup(1, "v:1")
1347 S = Synapses(G1, G2, on_pre="v+=1")
1348 net = Network(G1, G2, S)
1349 with pytest.raises(BrianObjectException) as exc:
1350 net.run(0 * ms)
1351 assert exc_isinstance(exc, TypeError)
1352
1353
1354 @pytest.mark.codegen_independent
1355 def test_no_synapses_variable_write():
1356 # Synaptic pathway but no synapses
1357 G1 = NeuronGroup(1, "", threshold="True")
1358 G2 = NeuronGroup(1, "v:1")
1359 S = Synapses(G1, G2, "w : 1", on_pre="v+=w")
1360 # Setting synaptic variables before calling connect is not allowed
1361 with pytest.raises(TypeError):
1362 setattr(S, "w", 1)
1363 with pytest.raises(TypeError):
1364 setattr(S, "delay", 1 * ms)
1365
1366
1367 @pytest.mark.standalone_compatible
1368 def test_summed_variable():
1369 source = NeuronGroup(2, "v : volt", threshold="v>1*volt", reset="v=0*volt")
1370 source.v = 1.1 * volt # will spike immediately
1371 target = NeuronGroup(2, "v : volt")
1372 S = Synapses(
1373 source,
1374 target,
1375 """
1376 w : volt
1377 x : volt
1378 v_post = 2*x : volt (summed)
1379 """,
1380 on_pre="x+=w",
1381 multisynaptic_index="k",
1382 )
1383 S.connect("i==j", n=2)
1384 S.w["k == 0"] = "i*volt"
1385 S.w["k == 1"] = "(i + 0.5)*volt"
1386 net = Network(source, target, S)
1387 net.run(1 * ms)
1388
1389 # v of the target should be the sum of the two weights
1390 assert_allclose(target.v, np.array([1.0, 5.0]) * volt)
1391
1392
1393 @pytest.mark.standalone_compatible
1394 def test_summed_variable_pre_and_post():
1395 G1 = NeuronGroup(
1396 4,
1397 """
1398 neuron_var : 1
1399 syn_sum : 1
1400 neuron_sum : 1
1401 """,
1402 )
1403 G1.neuron_var = "i"
1404 G2 = NeuronGroup(
1405 4,
1406 """
1407 neuron_var : 1
1408 syn_sum : 1
1409 neuron_sum : 1
1410 """,
1411 )
1412 G2.neuron_var = "i+4"
1413
1414 synapses = Synapses(
1415 G1,
1416 G2,
1417 """
1418 syn_var : 1
1419 neuron_sum_pre = neuron_var_post : 1 (summed)
1420 syn_sum_pre = syn_var : 1 (summed)
1421 neuron_sum_post = neuron_var_pre : 1 (summed)
1422 syn_sum_post = syn_var : 1 (summed)
1423 """,
1424 )
1425 # The first three cells in G1 connect to the first cell in G2
1426 # The remaining three cells of G2 all connect to the last cell of G1
1427 synapses.connect(i=[0, 1, 2, 3, 3, 3], j=[0, 0, 0, 1, 2, 3])
1428 synapses.syn_var = [0, 1, 2, 3, 4, 5]
1429
1430 run(defaultclock.dt)
1431 assert_allclose(G1.syn_sum[:], [0, 1, 2, 12])
1432 assert_allclose(G1.neuron_sum[:], [4, 4, 4, 18])
1433 assert_allclose(G2.syn_sum[:], [3, 3, 4, 5])
1434 assert_allclose(G2.neuron_sum[:], [3, 3, 3, 3])
1435
1436
1437 @pytest.mark.standalone_compatible
1438 def test_summed_variable_differing_group_size():
1439 G1 = NeuronGroup(2, "var : 1", name="G1")
1440 G2 = NeuronGroup(10, "var : 1", name="G2")
1441 G2.var[:5] = 1
1442 G2.var[5:] = 10
1443 syn1 = Synapses(
1444 G1,
1445 G2,
1446 """
1447 syn_var : 1
1448 var_pre = syn_var + var_post : 1 (summed)
1449 """,
1450 )
1451 syn1.connect(i=0, j=[0, 1, 2, 3, 4])
1452 syn1.connect(i=1, j=[5, 6, 7, 8, 9])
1453 syn1.syn_var = np.arange(10)
1454 # The same in the other direction
1455 G3 = NeuronGroup(10, "var : 1", name="G3")
1456 G4 = NeuronGroup(2, "var : 1", name="G4")
1457 G3.var[:5] = 1
1458 G3.var[5:] = 10
1459 syn2 = Synapses(
1460 G3,
1461 G4,
1462 """
1463 syn_var : 1
1464 var_post = syn_var + var_pre : 1 (summed)
1465 """,
1466 )
1467 syn2.connect(i=[0, 1, 2, 3, 4], j=0)
1468 syn2.connect(i=[5, 6, 7, 8, 9], j=1)
1469 syn2.syn_var = np.arange(10)
1470
1471 run(defaultclock.dt)
1472
1473 assert_allclose(G1.var[0], 5 * 1 + 0 + 1 + 2 + 3 + 4)
1474 assert_allclose(G1.var[1], 5 * 10 + 5 + 6 + 7 + 8 + 9)
1475
1476 assert_allclose(G4.var[0], 5 * 1 + 0 + 1 + 2 + 3 + 4)
1477 assert_allclose(G4.var[1], 5 * 10 + 5 + 6 + 7 + 8 + 9)
1478
1479
1480 def test_summed_variable_errors():
1481 G = NeuronGroup(
1482 10,
1483 """
1484 dv/dt = -v / (10*ms) : volt
1485 sub = 2*v : volt
1486 p : volt
1487 """,
1488 threshold="False",
1489 reset="",
1490 )
1491
1492 # Using the (summed) flag for a differential equation or a parameter
1493 with pytest.raises(ValueError):
1494 Synapses(G, G, """dp_post/dt = -p_post / (10*ms) : volt (summed)""")
1495 with pytest.raises(ValueError):
1496 Synapses(G, G, """p_post : volt (summed)""")
1497
1498 # Using the (summed) flag for a variable name without _pre or _post suffix
1499 with pytest.raises(ValueError):
1500 Synapses(G, G, """p = 3*volt : volt (summed)""")
1501 # Using the name of a variable that does not exist
1502 with pytest.raises(ValueError):
1503 Synapses(G, G, """q_post = 3*volt : volt (summed)""")
1504
1505 # Target equation is not a parameter
1506 with pytest.raises(ValueError):
1507 Synapses(G, G, """sub_post = 3*volt : volt (summed)""")
1508 with pytest.raises(ValueError):
1509 Synapses(G, G, """v_post = 3*volt : volt (summed)""")
1510
1511 # Unit mismatch between synapses and target
1512 with pytest.raises(DimensionMismatchError):
1513 Synapses(G, G, """p_post = 3*second : second (summed)""")
1514
1515 # Two summed variable equations targetting the same variable
1516 with pytest.raises(ValueError):
1517 Synapses(
1518 G,
1519 G,
1520 """
1521 p_post = 3*volt : volt (summed)
1522 p_pre = 3*volt : volt (summed)
1523 """,
1524 )
1525
1526 # Summed variable referring to an event-driven variable
1527 with pytest.raises(EquationError) as ex:
1528 Synapses(
1529 G,
1530 G,
1531 """
1532 ds/dt = -s/(3*ms) : volt (event-driven)
1533 p_post = s : volt (summed)
1534 """,
1535 on_pre="s += 1*mV",
1536 )
1537 assert "'p_post'" in str(ex.value) and "'s'" in str(ex.value)
1538
1539 # Indirect dependency
1540 with pytest.raises(EquationError) as ex:
1541 Synapses(
1542 G,
1543 G,
1544 """
1545 ds/dt = -s/(3*ms) : volt (event-driven)
1546 x = s : volt
1547 y = x : volt
1548 p_post = y : 1 (summed)
1549 """,
1550 on_pre="s += 1*mV",
1551 )
1552 assert "'p_post'" in str(ex.value) and "'s'" in str(ex.value)
1553 assert "'x'" in str(ex.value) and "'y'" in str(ex.value)
1554
1555 with pytest.raises(BrianObjectException) as ex:
1556 S = Synapses(
1557 G,
1558 G,
1559 """
1560 y : siemens
1561 p_post = y : volt (summed)
1562 """,
1563 )
1564 run(0 * ms)
1565
1566 assert isinstance(ex.value.__cause__, DimensionMismatchError)
1567
1568
1569 @pytest.mark.codegen_independent
1570 def test_multiple_summed_variables():
1571 # See github issue #766
1572 source = NeuronGroup(1, "")
1573 target = NeuronGroup(10, "v : 1")
1574 syn1 = Synapses(source, target, "v_post = 1 : 1 (summed)")
1575 syn1.connect()
1576 syn2 = Synapses(source, target, "v_post = 1 : 1 (summed)")
1577 syn2.connect()
1578 net = Network(collect())
1579 with pytest.raises(NotImplementedError):
1580 net.run(0 * ms)
1581
1582
1583 @pytest.mark.standalone_compatible
1584 def test_summed_variables_subgroups():
1585 source = NeuronGroup(1, "")
1586 target = NeuronGroup(10, "v : 1")
1587 subgroup1 = target[:6]
1588 subgroup2 = target[6:]
1589 syn1 = Synapses(source, subgroup1, "v_post = 1 : 1 (summed)")
1590 syn1.connect(n=2)
1591 syn2 = Synapses(source, subgroup2, "v_post = 1 : 1 (summed)")
1592 syn2.connect()
1593 run(defaultclock.dt)
1594 assert_allclose(target.v[:6], 2 * np.ones(6))
1595 assert_allclose(target.v[6:], 1 * np.ones(4))
1596
1597
1598 @pytest.mark.codegen_independent
1599 def test_summed_variables_overlapping_subgroups():
1600 # See github issue #766
1601 source = NeuronGroup(1, "")
1602 target = NeuronGroup(10, "v : 1")
1603 # overlapping subgroups
1604 subgroup1 = target[:7]
1605 subgroup2 = target[6:]
1606 syn1 = Synapses(source, subgroup1, "v_post = 1 : 1 (summed)")
1607 syn1.connect(n=2)
1608 syn2 = Synapses(source, subgroup2, "v_post = 1 : 1 (summed)")
1609 syn2.connect()
1610 net = Network(collect())
1611 with pytest.raises(NotImplementedError):
1612 net.run(0 * ms)
1613
1614
1615 @pytest.mark.codegen_independent
1616 def test_summed_variables_linked_variables():
1617 source = NeuronGroup(1, "")
1618 target1 = NeuronGroup(10, "v : 1")
1619 target2 = NeuronGroup(10, "v : 1 (linked)")
1620 target2.v = linked_var(target1.v)
1621 # Seemingly independent targets, but the variable is the same
1622 syn1 = Synapses(source, target1, "v_post = 1 : 1 (summed)")
1623 syn1.connect()
1624 syn2 = Synapses(source, target2, "v_post = 1 : 1 (summed)")
1625 syn2.connect()
1626 net = Network(collect())
1627 with pytest.raises(NotImplementedError):
1628 net.run(0 * ms)
1629
1630
1631 @pytest.mark.codegen_independent
1632 def test_linked_to_shared_variables():
1633 source1 = NeuronGroup(1, "dx/dt = -x / (10*ms) : 1")
1634 source1.x = "rand()"
1635 source2 = NeuronGroup(10, "x : 1 (shared)")
1636 source2.x = "rand()"
1637 mon = StateMonitor(source1, "x", record=True)
1638 group = NeuronGroup(10, "")
1639 syn = Synapses(
1640 group,
1641 group,
1642 """x1 : 1 (linked)
1643 x2 : 1 (linked)
1644 """,
1645 )
1646 syn.x1 = linked_var(source1.x)
1647 syn.x2 = linked_var(source2.x)
1648 syn.connect(i=[0, 5], j=[3, 6])
1649 mon_syn = StateMonitor(syn, ["x1", "x2"], record=True)
1650 run(2 * defaultclock.dt)
1651 assert_allclose(mon.x[0], mon_syn.x1[0])
1652 assert_allclose(mon.x[0], mon_syn.x1[1])
1653 assert_allclose(source2.x, mon_syn.x2[0])
1654 assert_allclose(source2.x, mon_syn.x2[1])
1655
1656
1657 @pytest.mark.codegen_independent
1658 def test_linked_to_non_shared_variables():
1659 source = NeuronGroup(10, "dx/dt = -x / (10*ms) : 1")
1660 source.x = "rand()"
1661 mon = StateMonitor(source, "x", record=True)
1662 group = NeuronGroup(10, "y: 1")
1663 syn = Synapses(
1664 group,
1665 group,
1666 """x : 1 (linked)
1667 x_ind: integer
1668 not_an_index : 1
1669 """,
1670 )
1671 syn.connect(i=[0, 5], j=[3, 6])
1672 with pytest.raises(TypeError):
1673 syn.x = linked_var(source.x, index=[0, 1])
1674 with pytest.raises(ValueError):
1675 syn.x = linked_var(source.x, index="does_not_exist")
1676 with pytest.raises(ValueError):
1677 syn.x = linked_var(source.x, index="y_post")
1678 with pytest.raises(TypeError):
1679 syn.x = linked_var(source.x, index="not_an_index")
1680 syn.x = linked_var(source.x, index="x_ind")
1681 syn.x_ind = [3, 5]
1682 mon_syn = StateMonitor(syn, "x", record=True)
1683 run(2 * defaultclock.dt)
1684 assert_allclose(mon.x[3], mon_syn.x[0])
1685 assert_allclose(mon.x[5], mon_syn.x[1])
1686
1687
1688 def test_scalar_parameter_access():
1689 G = NeuronGroup(
1690 10,
1691 """
1692 v : 1
1693 scalar : Hz (shared)
1694 """,
1695 threshold="False",
1696 )
1697 S = Synapses(
1698 G,
1699 G,
1700 """
1701 w : 1
1702 s : Hz (shared)
1703 number : 1 (shared)
1704 """,
1705 on_pre="v+=w*number",
1706 )
1707 S.connect()
1708
1709 # Try setting a scalar variable
1710 S.s = 100 * Hz
1711 assert_allclose(S.s[:], 100 * Hz)
1712 S.s[:] = 200 * Hz
1713 assert_allclose(S.s[:], 200 * Hz)
1714 S.s = "s - 50*Hz + number*Hz"
1715 assert_allclose(S.s[:], 150 * Hz)
1716 S.s[:] = "50*Hz"
1717 assert_allclose(S.s[:], 50 * Hz)
1718
1719 # Set a postsynaptic scalar variable
1720 S.scalar_post = 100 * Hz
1721 assert_allclose(G.scalar[:], 100 * Hz)
1722 S.scalar_post[:] = 100 * Hz
1723 assert_allclose(G.scalar[:], 100 * Hz)
1724
1725 # Check the second method of accessing that works
1726 assert_allclose(np.asanyarray(S.s), 50 * Hz)
1727
1728 # Check error messages
1729 with pytest.raises(IndexError):
1730 S.s[0]
1731 with pytest.raises(IndexError):
1732 S.s[1]
1733 with pytest.raises(IndexError):
1734 S.s[0:1]
1735 with pytest.raises(IndexError):
1736 S.s["i>5"]
1737
1738 with pytest.raises(ValueError):
1739 S.s.set_item(slice(None), [0, 1] * Hz)
1740 with pytest.raises(IndexError):
1741 S.s.set_item(0, 100 * Hz)
1742 with pytest.raises(IndexError):
1743 S.s.set_item(1, 100 * Hz)
1744 with pytest.raises(IndexError):
1745 S.s.set_item("i>5", 100 * Hz)
1746
1747
1748 def test_scalar_subexpression():
1749 G = NeuronGroup(
1750 10,
1751 """
1752 v : 1
1753 number : 1 (shared)
1754 """,
1755 threshold="False",
1756 )
1757 S = Synapses(
1758 G,
1759 G,
1760 """
1761 s : 1 (shared)
1762 sub = number_post + s : 1 (shared)
1763 """,
1764 on_pre="v+=s",
1765 )
1766 S.connect()
1767 S.s = 100
1768 G.number = 50
1769 assert S.sub[:] == 150
1770
1771 with pytest.raises(SyntaxError):
1772 Synapses(
1773 G,
1774 G,
1775 """
1776 s : 1 (shared)
1777 sub = v_post + s : 1 (shared)
1778 """,
1779 on_pre="v+=s",
1780 )
1781
1782
1783 @pytest.mark.standalone_compatible
1784 def test_sim_with_scalar_variable():
1785 inp = SpikeGeneratorGroup(2, [0, 1], [0, 0] * ms)
1786 out = NeuronGroup(2, "v : 1")
1787 syn = Synapses(
1788 inp,
1789 out,
1790 """
1791 w : 1
1792 s : 1 (shared)
1793 """,
1794 on_pre="v += s + w",
1795 )
1796 syn.connect(j="i")
1797 syn.w = [1, 2]
1798 syn.s = 5
1799 run(2 * defaultclock.dt)
1800 assert_allclose(out.v[:], [6, 7])
1801
1802
1803 @pytest.mark.standalone_compatible
1804 def test_sim_with_scalar_subexpression():
1805 inp = SpikeGeneratorGroup(2, [0, 1], [0, 0] * ms)
1806 out = NeuronGroup(2, "v : 1")
1807 syn = Synapses(
1808 inp,
1809 out,
1810 """
1811 w : 1
1812 s = 5 : 1 (shared)
1813 """,
1814 on_pre="v += s + w",
1815 )
1816 syn.connect(j="i")
1817 syn.w = [1, 2]
1818 run(2 * defaultclock.dt)
1819 assert_allclose(out.v[:], [6, 7])
1820
1821
1822 @pytest.mark.standalone_compatible
1823 def test_sim_with_constant_subexpression():
1824 inp = SpikeGeneratorGroup(2, [0, 1], [0, 0] * ms)
1825 out = NeuronGroup(2, "v : 1")
1826 syn = Synapses(
1827 inp,
1828 out,
1829 """
1830 w : 1
1831 s = 5 : 1 (constant over dt)
1832 """,
1833 on_pre="v += s + w",
1834 )
1835 syn.connect(j="i")
1836 syn.w = [1, 2]
1837 run(2 * defaultclock.dt)
1838 assert_allclose(out.v[:], [6, 7])
1839
1840
1841 @pytest.mark.standalone_compatible
1842 def test_external_variables():
1843 # Make sure that external variables are correctly resolved
1844 source = SpikeGeneratorGroup(1, [0], [0] * ms)
1845 target = NeuronGroup(1, "v:1")
1846 w_var = 1
1847 amplitude = 2
1848 syn = Synapses(source, target, "w=w_var : 1", on_pre="v+=amplitude*w")
1849 syn.connect()
1850 run(defaultclock.dt)
1851 assert target.v[0] == 2
1852
1853
1854 @pytest.mark.standalone_compatible
1855 def test_event_driven():
1856 # Fake example, where the synapse is actually not changing the state of the
1857 # postsynaptic neuron, the pre- and post spiketrains are regular spike
1858 # trains with different rates
1859 pre = NeuronGroup(
1860 2,
1861 """
1862 dv/dt = rate : 1
1863 rate : Hz
1864 """,
1865 threshold="v>1",
1866 reset="v=0",
1867 )
1868 pre.rate = [1000, 1500] * Hz
1869 post = NeuronGroup(
1870 2,
1871 """
1872 dv/dt = rate : 1
1873 rate : Hz
1874 """,
1875 threshold="v>1",
1876 reset="v=0",
1877 )
1878 post.rate = [1100, 1400] * Hz
1879 # event-driven formulation
1880 taupre = 20 * ms
1881 taupost = taupre
1882 gmax = 0.01
1883 dApre = 0.01
1884 dApost = -dApre * taupre / taupost * 1.05
1885 dApost *= gmax
1886 dApre *= gmax
1887 # event-driven
1888 S1 = Synapses(
1889 pre,
1890 post,
1891 """
1892 w : 1
1893 dApre/dt = -Apre/taupre : 1 (event-driven)
1894 dApost/dt = -Apost/taupost : 1 (event-driven)
1895 """,
1896 on_pre="""
1897 Apre += dApre
1898 w = clip(w+Apost, 0, gmax)
1899 """,
1900 on_post="""
1901 Apost += dApost
1902 w = clip(w+Apre, 0, gmax)
1903 """,
1904 )
1905 S1.connect(j="i")
1906 # not event-driven
1907 S2 = Synapses(
1908 pre,
1909 post,
1910 """
1911 w : 1
1912 Apre : 1
1913 Apost : 1
1914 lastupdate : second
1915 """,
1916 on_pre="""
1917 Apre=Apre*exp((lastupdate-t)/taupre)+dApre
1918 Apost=Apost*exp((lastupdate-t)/taupost)
1919 w = clip(w+Apost, 0, gmax)
1920 lastupdate = t
1921 """,
1922 on_post="""
1923 Apre=Apre*exp((lastupdate-t)/taupre)
1924 Apost=Apost*exp((lastupdate-t)/taupost) +dApost
1925 w = clip(w+Apre, 0, gmax)
1926 lastupdate = t
1927 """,
1928 )
1929 S2.connect(j="i")
1930 S1.w = 0.5 * gmax
1931 S2.w = 0.5 * gmax
1932 run(25 * ms)
1933 # The two formulations should yield identical results
1934 assert_allclose(S1.w[:], S2.w[:])
1935
1936
1937 @pytest.mark.codegen_independent
1938 def test_event_driven_dependency_checks():
1939 dummy = NeuronGroup(1, "", threshold="False", reset="")
1940
1941 # Dependency on parameter
1942 syn = Synapses(
1943 dummy,
1944 dummy,
1945 """
1946 da/dt = (a-b) / (5*ms): 1 (event-driven)
1947 b : 1""",
1948 on_pre="b+=1",
1949 )
1950 syn.connect()
1951
1952 # Dependency on parameter via subexpression
1953 syn2 = Synapses(
1954 dummy,
1955 dummy,
1956 """
1957 da/dt = (a-b) / (5*ms): 1 (event-driven)
1958 b = c : 1
1959 c : 1""",
1960 on_pre="c+=1",
1961 )
1962 syn2.connect()
1963 run(0 * ms)
1964
1965
1966 @pytest.mark.codegen_independent
1967 def test_event_driven_dependency_error():
1968 stim = SpikeGeneratorGroup(1, [0], [0] * ms, period=5 * ms)
1969 syn = Synapses(
1970 stim,
1971 stim,
1972 """
1973 da/dt = -a / (5*ms) : 1 (event-driven)
1974 db/dt = -b / (5*ms) : 1 (event-driven)
1975 dc/dt = a*b / (5*ms) : 1 (event-driven)""",
1976 on_pre="a+=1",
1977 )
1978 syn.connect()
1979 net = Network(collect())
1980 with pytest.raises(BrianObjectException) as exc:
1981 net.run(0 * ms)
1982 assert exc_isinstance(exc, UnsupportedEquationsException)
1983
1984
1985 @pytest.mark.codegen_independent
1986 def test_event_driven_dependency_error2():
1987 stim = SpikeGeneratorGroup(1, [0], [0] * ms, period=5 * ms)
1988 tau = 5 * ms
1989 with pytest.raises(EquationError) as exc:
1990 syn = Synapses(
1991 stim,
1992 stim,
1993 """
1994 da/dt = -a / (5*ms) : 1 (clock-driven)
1995 db/dt = -b / (5*ms) : 1 (clock-driven)
1996 dc/dt = a*b / (5*ms) : 1 (event-driven)
1997 """,
1998 on_pre="a+=1",
1999 )
2000 assert "'c'" in str(exc.value) and (
2001 "'a'" in str(exc.value) or "'b'" in str(exc.value)
2002 )
2003
2004 # Indirect dependency
2005 with pytest.raises(EquationError) as exc:
2006 syn = Synapses(
2007 stim,
2008 stim,
2009 """
2010 da/dt = -a / (5*ms) : 1 (clock-driven)
2011 b = a : 1
2012 dc/dt = b / (5*ms) : 1 (event-driven)
2013 """,
2014 on_pre="a+=1",
2015 )
2016 assert (
2017 "'c'" in str(exc.value) and "'a'" in str(exc.value) and "'b'" in str(exc.value)
2018 )
2019
2020
2021 @pytest.mark.codegen_independent
2022 def test_event_driven_dependency_error3():
2023 P = NeuronGroup(10, "dv/dt = -v/(10*ms) : volt")
2024 with pytest.raises(EquationError) as ex:
2025 Synapses(
2026 P,
2027 P,
2028 """
2029 ds/dt = -s/(3*ms) : 1 (event-driven)
2030 df/dt = f*s/(5*ms) : 1 (clock-driven)
2031 """,
2032 on_pre="s += 1",
2033 )
2034 assert "'s'" in str(ex.value) and "'f'" in str(ex.value)
2035
2036 # Indirect dependency
2037 with pytest.raises(EquationError) as ex:
2038 Synapses(
2039 P,
2040 P,
2041 """
2042 ds/dt = -s/(3*ms) : 1 (event-driven)
2043 x = s : 1
2044 y = x : 1
2045 df/dt = f*y/(5*ms) : 1 (clock-driven)
2046 """,
2047 on_pre="s += 1",
2048 )
2049 assert "'s'" in str(ex.value) and "'f'" in str(ex.value)
2050 assert "'x'" in str(ex.value) and "'y'" in str(ex.value)
2051
2052
2053 @pytest.mark.codegen_independent
2054 def test_repr():
2055 G = NeuronGroup(1, "v: volt", threshold="False")
2056 S = Synapses(
2057 G,
2058 G,
2059 """
2060 w : 1
2061 dApre/dt = -Apre/taupre : 1 (event-driven)
2062 dApost/dt = -Apost/taupost : 1 (event-driven)
2063 """,
2064 on_pre="""
2065 Apre += dApre
2066 w = clip(w+Apost, 0, gmax)
2067 """,
2068 on_post="""
2069 Apost += dApost
2070 w = clip(w+Apre, 0, gmax)
2071 """,
2072 )
2073 # Test that string/LaTeX representations do not raise errors
2074 for func in [str, repr, sympy.latex]:
2075 assert len(func(S.equations))
2076
2077
2078 @pytest.mark.codegen_independent
2079 def test_pre_post_variables():
2080 G = NeuronGroup(10, "v : 1", threshold="False")
2081 G2 = NeuronGroup(
2082 10,
2083 """
2084 v : 1
2085 w : 1
2086 """,
2087 threshold="False",
2088 )
2089 S = Synapses(G, G2, "x : 1")
2090 # Check for the most important variables
2091 for var in [
2092 "v_pre",
2093 "v",
2094 "v_post",
2095 "w",
2096 "w_post",
2097 "x",
2098 "N_pre",
2099 "N_post",
2100 "N_incoming",
2101 "N_outgoing",
2102 "i",
2103 "j",
2104 "t",
2105 "dt",
2106 ]:
2107 assert var in S.variables
2108 # Check that postsynaptic variables without suffix refer to the correct
2109 # variable
2110 assert S.variables["v"] is S.variables["v_post"]
2111 assert S.variables["w"] is S.variables["w_post"]
2112
2113 # Check that internal pre-/post-synaptic variables are not accessible
2114 assert "_spikespace_pre" not in S.variables
2115 assert "_spikespace" not in S.variables
2116 assert "_spikespace_post" not in S.variables
2117
2118
2119 @pytest.mark.codegen_independent
2120 def test_variables_by_owner():
2121 # Test the `variables_by_owner` convenience function
2122 G = NeuronGroup(10, "v : 1")
2123 G2 = NeuronGroup(
2124 10,
2125 """
2126 v : 1
2127 w : 1
2128 """,
2129 )
2130 S = Synapses(G, G2, "x : 1")
2131
2132 # Check that the variables returned as owned by the pre/post groups are the
2133 # variables stored in the respective groups. We only compare the `Variable`
2134 # objects, as the names may be different (e.g. ``v_post`` vs. ``v``)
2135 G_variables = {
2136 key: value for key, value in G.variables.items() if value.owner.name == G.name
2137 } # exclude dt
2138 G2_variables = {
2139 key: value for key, value in G2.variables.items() if value.owner.name == G2.name
2140 }
2141 assert set(G_variables.values()) == set(variables_by_owner(S.variables, G).values())
2142 assert set(G2_variables.values()) == set(
2143 variables_by_owner(S.variables, G2).values()
2144 )
2145 assert len(set(variables_by_owner(S.variables, S)) & set(G_variables.values())) == 0
2146 assert (
2147 len(set(variables_by_owner(S.variables, S)) & set(G2_variables.values())) == 0
2148 )
2149 # Just test a few examples for synaptic variables
2150 assert all(
2151 varname in variables_by_owner(S.variables, S)
2152 for varname in ["x", "N", "N_incoming", "N_outgoing"]
2153 )
2154
2155
2156 @pytest.mark.codegen_independent
2157 def check_permutation_code(code):
2158 from collections import defaultdict
2159
2160 vars = get_identifiers(code)
2161 indices = defaultdict(lambda: "_idx")
2162 for var in vars:
2163 if var.endswith("_syn"):
2164 indices[var] = "_idx"
2165 elif var.endswith("_pre"):
2166 indices[var] = "_presynaptic_idx"
2167 elif var.endswith("_post"):
2168 indices[var] = "_postsynaptic_idx"
2169 elif var.endswith("_const"):
2170 indices[var] = "0"
2171 variables = dict()
2172 variables.update(DEFAULT_FUNCTIONS)
2173 for var in indices:
2174 if var.endswith("_const"):
2175 variables[var] = Constant(var, 42, owner=device)
2176 else:
2177 variables[var] = ArrayVariable(var, None, 10, device)
2178 variables["_presynaptic_idx"] = ArrayVariable(var, None, 10, device)
2179 variables["_postsynaptic_idx"] = ArrayVariable(var, None, 10, device)
2180 scalar_statements, vector_statements = make_statements(code, variables, float64)
2181 check_for_order_independence(vector_statements, variables, indices)
2182
2183
2184 def numerically_check_permutation_code(code):
2185 # numerically checks that a code block used in the test below is permutation-independent by creating a
2186 # presynaptic and postsynaptic group of 3 neurons each, and a full connectivity matrix between them, then
2187 # repeatedly filling in random values for each of the variables, and checking for several random shuffles of
2188 # the synapse order that the result doesn't depend on it. This is a sort of test of the test itself, to make
2189 # sure we didn't accidentally assign a good/bad example to the wrong class.
2190 code = deindent(code)
2191 from collections import defaultdict
2192
2193 vars = get_identifiers(code)
2194 indices = defaultdict(lambda: "_idx")
2195 vals = {}
2196 for var in vars:
2197 if var.endswith("_syn"):
2198 indices[var] = "_idx"
2199 vals[var] = zeros(9)
2200 elif var.endswith("_pre"):
2201 indices[var] = "_presynaptic_idx"
2202 vals[var] = zeros(3)
2203 elif var.endswith("_post"):
2204 indices[var] = "_postsynaptic_idx"
2205 vals[var] = zeros(3)
2206 elif var.endswith("_shared"):
2207 indices[var] = "0"
2208 vals[var] = zeros(1)
2209 elif var.endswith("_const"):
2210 indices[var] = "0"
2211 vals[var] = 42
2212 subs = {
2213 var: var + "[" + idx + "]"
2214 for var, idx in indices.items()
2215 if not var.endswith("_const")
2216 }
2217 code = word_substitute(code, subs)
2218 code = f"""
2219 from numpy import *
2220 from numpy.random import rand, randn
2221 for _idx in shuffled_indices:
2222 _presynaptic_idx = presyn[_idx]
2223 _postsynaptic_idx = postsyn[_idx]
2224 {indent(code)}
2225 """
2226 ns = vals.copy()
2227 ns["shuffled_indices"] = arange(9)
2228 ns["presyn"] = arange(9) % 3
2229 ns["postsyn"] = arange(9) // 3
2230 for _ in range(10):
2231 origvals = {}
2232 for k, v in vals.items():
2233 if not k.endswith("_const"):
2234 v[:] = randn(len(v))
2235 origvals[k] = v.copy()
2236 exec(code, ns)
2237 endvals = {}
2238 for k, v in vals.items():
2239 endvals[k] = copy(v)
2240 for _ in range(10):
2241 for k, v in vals.items():
2242 if not k.endswith("_const"):
2243 v[:] = origvals[k]
2244 shuffle(ns["shuffled_indices"])
2245 exec(code, ns)
2246 for k, v in vals.items():
2247 try:
2248 assert_allclose(v, endvals[k])
2249 except AssertionError:
2250 raise OrderDependenceError()
2251
2252
2253 SANITY_CHECK_PERMUTATION_ANALYSIS_EXAMPLE = False
2254
2255 permutation_analysis_good_examples = [
2256 "v_post += w_syn",
2257 "v_post *= w_syn",
2258 "v_post = v_post + w_syn",
2259 "v_post = v_post * w_syn",
2260 "v_post = w_syn * v_post",
2261 "v_post += 1",
2262 "v_post = 1",
2263 "v_post = c_const",
2264 "v_post = x_shared",
2265 "v_post += v_post # NOT_UFUNC_AT_VECTORISABLE",
2266 "v_post += c_const",
2267 "v_post += x_shared",
2268 #'v_post += w_syn*v_post', # this is a hard one (it is good for w*v but bad for w+v)
2269 "v_post += sin(-v_post) # NOT_UFUNC_AT_VECTORISABLE",
2270 "v_post += u_post",
2271 "v_post += w_syn*v_pre",
2272 "v_post += sin(-v_post) # NOT_UFUNC_AT_VECTORISABLE",
2273 "v_post -= sin(v_post) # NOT_UFUNC_AT_VECTORISABLE",
2274 "v_post += v_pre",
2275 "v_pre += v_post",
2276 "v_pre += c_const",
2277 "v_pre += x_shared",
2278 "w_syn = v_pre",
2279 "w_syn = a_syn",
2280 "w_syn += a_syn",
2281 "w_syn *= a_syn",
2282 "w_syn -= a_syn",
2283 "w_syn /= a_syn",
2284 "w_syn += 1",
2285 "w_syn += c_const",
2286 "w_syn += x_shared",
2287 "w_syn *= 2",
2288 "w_syn *= c_const",
2289 "w_syn *= x_shared",
2290 """
2291 w_syn = a_syn
2292 a_syn += 1
2293 """,
2294 """
2295 w_syn = a_syn
2296 a_syn += c_const
2297 """,
2298 """
2299 w_syn = a_syn
2300 a_syn += x_shared
2301 """,
2302 "v_post *= 2",
2303 "v_post *= w_syn",
2304 """
2305 v_pre = 0
2306 w_syn = v_pre
2307 """,
2308 """
2309 v_pre = c_const
2310 w_syn = v_pre
2311 """,
2312 """
2313 v_pre = x_shared
2314 w_syn = v_pre
2315 """,
2316 """
2317 ge_syn += w_syn
2318 Apre_syn += 3
2319 w_syn = clip(w_syn + Apost_syn, 0, 10)
2320 """,
2321 """
2322 ge_syn += w_syn
2323 Apre_syn += c_const
2324 w_syn = clip(w_syn + Apost_syn, 0, 10)
2325 """,
2326 """
2327 ge_syn += w_syn
2328 Apre_syn += x_shared
2329 w_syn = clip(w_syn + Apost_syn, 0, 10)
2330 """,
2331 """
2332 a_syn = v_pre
2333 v_post += a_syn
2334 """,
2335 """
2336 v_post += v_post # NOT_UFUNC_AT_VECTORISABLE
2337 v_post += v_post
2338 """,
2339 """
2340 v_post += 1
2341 x = v_post
2342 """,
2343 ]
2344
2345 permutation_analysis_bad_examples = [
2346 "v_pre = w_syn",
2347 "v_post = v_pre",
2348 "v_post = w_syn",
2349 "v_post += w_syn+v_post",
2350 "v_post += rand()", # rand() has state, and therefore this is order dependent
2351 """
2352 a_syn = v_post
2353 v_post += w_syn
2354 """,
2355 """
2356 x = w_syn
2357 v_pre = x
2358 """,
2359 """
2360 x = v_pre
2361 v_post = x
2362 """,
2363 """
2364 v_post += v_pre
2365 v_pre += v_post
2366 """,
2367 """
2368 b_syn = v_post
2369 v_post += a_syn
2370 """,
2371 """
2372 v_post += w_syn
2373 u_post += v_post
2374 """,
2375 """
2376 v_post += 1
2377 w_syn = v_post
2378 """,
2379 ]
2380
2381
2382 @pytest.mark.codegen_independent
2383 def test_permutation_analysis():
2384 # Examples that should work
2385 for example in permutation_analysis_good_examples:
2386 if SANITY_CHECK_PERMUTATION_ANALYSIS_EXAMPLE:
2387 try:
2388 numerically_check_permutation_code(example)
2389 except OrderDependenceError:
2390 raise AssertionError(
2391 "Test unexpectedly raised a numerical "
2392 "OrderDependenceError on these "
2393 "statements:\n" + example
2394 )
2395 try:
2396 check_permutation_code(example)
2397 except OrderDependenceError:
2398 raise AssertionError(
2399 "Test unexpectedly raised an "
2400 "OrderDependenceError on these "
2401 "statements:\n" + example
2402 )
2403
2404 for example in permutation_analysis_bad_examples:
2405 if SANITY_CHECK_PERMUTATION_ANALYSIS_EXAMPLE:
2406 try:
2407 with pytest.raises(OrderDependenceError):
2408 numerically_check_permutation_code(example)
2409 except AssertionError:
2410 raise AssertionError(
2411 "Order dependence not raised numerically for example: " + example
2412 )
2413 try:
2414 with pytest.raises(OrderDependenceError):
2415 check_permutation_code(example)
2416 except AssertionError:
2417 raise AssertionError("Order dependence not raised for example: " + example)
2418
2419
2420 @pytest.mark.standalone_compatible
2421 def test_vectorisation():
2422 source = NeuronGroup(10, "v : 1", threshold="v>1")
2423 target = NeuronGroup(
2424 10,
2425 """
2426 x : 1
2427 y : 1
2428 """,
2429 )
2430 syn = Synapses(
2431 source,
2432 target,
2433 "w_syn : 1",
2434 on_pre="""
2435 v_pre += w_syn
2436 x_post = y_post
2437 """,
2438 )
2439 syn.connect()
2440 syn.w_syn = 1
2441 source.v["i<5"] = 2
2442 target.y = "i"
2443 run(defaultclock.dt)
2444 assert_allclose(source.v[:5], 12)
2445 assert_allclose(source.v[5:], 0)
2446 assert_allclose(target.x[:], target.y[:])
2447
2448
2449 @pytest.mark.standalone_compatible
2450 def test_vectorisation_STDP_like():
2451 # Test the use of pre- and post-synaptic traces that are stored in the
2452 # pre/post group instead of in the synapses
2453 w_max = 10
2454 neurons = NeuronGroup(
2455 6,
2456 """
2457 dv/dt = rate : 1
2458 ge : 1
2459 rate : Hz
2460 dA/dt = -A/(1*ms) : 1
2461 """,
2462 threshold="v>1",
2463 reset="v=0",
2464 )
2465 # Note that the synapse does not actually increase the target v, we want
2466 # to have simple control about when neurons spike. Also, we separate the
2467 # "depression" and "facilitation" completely. The example also uses
2468 # subgroups, which should complicate things further.
2469 # This test should try to capture the spirit of indexing in such a use case,
2470 # it simply compares the results to fixed pre-calculated values
2471 syn = Synapses(
2472 neurons[:3],
2473 neurons[3:],
2474 """
2475 w_dep : 1
2476 w_fac : 1
2477 """,
2478 on_pre="""
2479 ge_post += w_dep - w_fac
2480 A_pre += 1
2481 w_dep = clip(w_dep + A_post, 0, w_max)
2482 """,
2483 on_post="""
2484 A_post += 1
2485 w_fac = clip(w_fac + A_pre, 0, w_max)
2486 """,
2487 )
2488 syn.connect()
2489 neurons.rate = 1000 * Hz
2490 neurons.v = "abs(3-i)*0.1 + 0.7"
2491 run(2 * ms)
2492 # Make sure that this test is invariant to synapse order
2493 indices = np.argsort(
2494 np.array(list(zip(syn.i[:], syn.j[:])), dtype=[("i", "<i4"), ("j", "<i4")]),
2495 order=["i", "j"],
2496 )
2497 assert_allclose(
2498 syn.w_dep[:][indices],
2499 [
2500 1.29140162,
2501 1.16226149,
2502 1.04603529,
2503 1.16226149,
2504 1.04603529,
2505 0.94143176,
2506 1.04603529,
2507 0.94143176,
2508 6.2472887,
2509 ],
2510 atol=0.0001,
2511 )
2512 assert_allclose(
2513 syn.w_fac[:][indices],
2514 [
2515 5.06030369,
2516 5.62256002,
2517 6.2472887,
2518 5.62256002,
2519 6.2472887,
2520 6.941432,
2521 6.2472887,
2522 6.941432,
2523 1.04603529,
2524 ],
2525 atol=0.0001,
2526 )
2527 assert_allclose(
2528 neurons.A[:],
2529 [1.69665715, 1.88517461, 2.09463845, 2.32737606, 2.09463845, 1.88517461],
2530 atol=0.0001,
2531 )
2532 assert_allclose(
2533 neurons.ge[:],
2534 [0.0, 0.0, 0.0, -7.31700015, -8.13000011, -4.04603529],
2535 atol=0.0001,
2536 )
2537
2538
2539 @pytest.mark.standalone_compatible
2540 def test_synaptic_equations():
2541 # Check that integration works for synaptic equations
2542 G = NeuronGroup(10, "")
2543 tau = 10 * ms
2544 S = Synapses(G, G, "dw/dt = -w / tau : 1 (clock-driven)")
2545 S.connect(j="i")
2546 S.w = "i"
2547 run(10 * ms)
2548 assert_allclose(S.w[:], np.arange(10) * np.exp(-1))
2549
2550
2551 @pytest.mark.standalone_compatible
2552 def test_synapse_with_run_regularly():
2553 # Check that integration works for synaptic equations
2554 G = NeuronGroup(10, "v : 1", threshold="False")
2555 tau = 10 * ms
2556 S = Synapses(G, G, "w : 1", on_pre="v += w")
2557 S.connect(j="i")
2558 S.run_regularly("w = i")
2559 run(defaultclock.dt)
2560 assert_allclose(S.w[:], np.arange(10))
2561
2562
2563 @pytest.mark.standalone_compatible
2564 def test_synapses_to_synapses():
2565 source = SpikeGeneratorGroup(3, [0, 1, 2], [0, 0, 0] * ms, period=2 * ms)
2566 modulator = SpikeGeneratorGroup(3, [0, 2], [1, 3] * ms)
2567 target = NeuronGroup(3, "v : integer")
2568 conn = Synapses(source, target, "w : integer", on_pre="v += w")
2569 conn.connect(j="i")
2570 conn.w = 1
2571 modulatory_conn = Synapses(modulator, conn, on_pre="w += 1")
2572 modulatory_conn.connect(j="i")
2573 run(5 * ms)
2574 # First group has its weight increased to 2 after the first spike
2575 # Third group has its weight increased to 2 after the second spike
2576 assert_array_equal(target.v, [5, 3, 4])
2577
2578
2579 @pytest.mark.standalone_compatible
2580 def test_synapses_to_synapses_connection_array():
2581 source = SpikeGeneratorGroup(3, [0, 1, 2], [0, 0, 0] * ms, period=2 * ms)
2582 modulator = SpikeGeneratorGroup(3, [0, 2], [1, 3] * ms)
2583 target = NeuronGroup(3, "v : integer")
2584 conn = Synapses(source, target, "w : integer", on_pre="v += w")
2585 conn.connect(i=[0, 1, 2], j=[0, 1, 2])
2586 conn.w = 1
2587 modulatory_conn = Synapses(modulator, conn, on_pre="w += 1")
2588 modulatory_conn.connect(i=[0, 1, 2], j=[0, 1, 2])
2589 run(5 * ms)
2590 # First group has its weight increased to 2 after the first spike
2591 # Third group has its weight increased to 2 after the second spike
2592 assert_array_equal(target.v, [5, 3, 4])
2593
2594
2595 @pytest.mark.standalone_compatible
2596 def test_synapses_to_synapses_rule_and_array():
2597 source = SpikeGeneratorGroup(3, [0, 1, 2], [0, 0, 0] * ms, period=2 * ms)
2598 modulator = SpikeGeneratorGroup(3, [0, 2], [1, 3] * ms)
2599 target = NeuronGroup(3, "v : integer")
2600 conn = Synapses(source, target, "w : integer", on_pre="v += w")
2601 conn.connect(j="i")
2602 conn.w = 1
2603 modulatory_conn = Synapses(modulator, conn, on_pre="w += 1")
2604 # This will raise a warning in standalone mode, since we cannot check
2605 # whether the 'j' indices actually correspond to existing synapses
2606 # (the j='i' connection from above has not been executed yet)
2607 with catch_logs() as l:
2608 modulatory_conn.connect(i=[0, 1, 2], j=[0, 1, 2])
2609 if isinstance(get_device(), CPPStandaloneDevice):
2610 assert len(l) == 1
2611 assert l[0][0] == "WARNING"
2612 assert l[0][1] == "brian2.synapses.synapses.cannot_check_synapse_indices"
2613 else:
2614 assert len(l) == 0
2615 run(5 * ms)
2616 # First group has its weight increased to 2 after the first spike
2617 # Third group has its weight increased to 2 after the second spike
2618 assert_array_equal(target.v, [5, 3, 4])
2619
2620
2621 @pytest.mark.standalone_compatible
2622 def test_synapses_to_synapses_statevar_access():
2623 source = NeuronGroup(10, "v:1")
2624 modulator = NeuronGroup(40, "")
2625 target = NeuronGroup(10, "v:1")
2626 conn = Synapses(source, target)
2627 conn.connect(j="i", n=2)
2628 modulator_to_conn = Synapses(modulator, conn)
2629 modulator_to_conn.connect(j="int(i/2)")
2630 conn_to_modulator = Synapses(conn, modulator)
2631 conn_to_modulator.connect(j="i")
2632 conn_to_modulator.connect(j="i + 20")
2633 run(0 * ms)
2634 assert_equal(modulator_to_conn.i, np.arange(40))
2635 assert_equal(modulator_to_conn.j, np.repeat(np.arange(20), 2))
2636 assert_equal(modulator_to_conn.i_post, np.repeat(np.arange(10), 4))
2637 assert_equal(modulator_to_conn.j_post, np.repeat(np.arange(10), 4))
2638 assert_equal(conn_to_modulator.i, np.hstack([np.arange(20), np.arange(20)]))
2639 assert_equal(
2640 conn_to_modulator.i_pre,
2641 np.hstack([np.repeat(np.arange(10), 2), np.repeat(np.arange(10), 2)]),
2642 )
2643 assert_equal(
2644 conn_to_modulator.j_pre,
2645 np.hstack([np.repeat(np.arange(10), 2), np.repeat(np.arange(10), 2)]),
2646 )
2647 assert_equal(conn_to_modulator.j, np.arange(40))
2648
2649
2650 @pytest.mark.standalone_compatible
2651 def test_synapses_to_synapses_different_sizes():
2652 source = NeuronGroup(100, "v : 1", threshold="False")
2653 source.v = "i"
2654 modulator = NeuronGroup(1, "v : 1", threshold="False")
2655 target = NeuronGroup(100, "v : 1")
2656 target.v = "i + 100"
2657 conn = Synapses(source, target, "w:1", multisynaptic_index="k")
2658 conn.connect(j="i", n=2)
2659 conn.w = "i + j"
2660 modulatory_conn = Synapses(modulator, conn)
2661 modulatory_conn.connect("k_post == 1") # only second synapse is targeted
2662 run(0 * ms)
2663 assert_allclose(modulatory_conn.w_post, 2 * np.arange(100))
2664
2665
2666 def test_ufunc_at_vectorisation():
2667 if prefs.codegen.target != "numpy":
2668 pytest.skip("numpy-only test")
2669 for code in permutation_analysis_good_examples:
2670 should_be_able_to_use_ufunc_at = not "NOT_UFUNC_AT_VECTORISABLE" in code
2671 if should_be_able_to_use_ufunc_at:
2672 use_ufunc_at_list = [False, True]
2673 else:
2674 use_ufunc_at_list = [True]
2675 code = deindent(code)
2676 vars = get_identifiers(code)
2677 vars_src = []
2678 vars_tgt = []
2679 vars_syn = []
2680 vars_shared = []
2681 vars_const = {}
2682 for var in vars:
2683 if var.endswith("_pre"):
2684 vars_src.append(var[:-4])
2685 elif var.endswith("_post"):
2686 vars_tgt.append(var[:-5])
2687 elif var.endswith("_syn"):
2688 vars_syn.append(var[:-4])
2689 elif var.endswith("_shared"):
2690 vars_shared.append(var[:-7])
2691 elif var.endswith("_const"):
2692 vars_const[var[:-6]] = 42
2693 eqs_src = "\n".join(var + ":1" for var in vars_src)
2694 eqs_tgt = "\n".join(var + ":1" for var in vars_tgt)
2695 eqs_syn = "\n".join(var + ":1" for var in vars_syn)
2696 eqs_syn += "\n" + "\n".join(var + ":1 (shared)" for var in vars_shared)
2697 origvals = {}
2698 endvals = {}
2699 try:
2700 BrianLogger._log_messages.clear()
2701 with catch_logs(log_level=logging.INFO) as caught_logs:
2702 for use_ufunc_at in use_ufunc_at_list:
2703 NumpyCodeGenerator._use_ufunc_at_vectorisation = use_ufunc_at
2704 src = NeuronGroup(3, eqs_src, threshold="True", name="src")
2705 tgt = NeuronGroup(3, eqs_tgt, name="tgt")
2706 syn = Synapses(
2707 src,
2708 tgt,
2709 eqs_syn,
2710 on_pre=code.replace("_syn", "")
2711 .replace("_const", "")
2712 .replace("_shared", ""),
2713 name="syn",
2714 namespace=vars_const,
2715 )
2716 syn.connect()
2717 for G, vars in [(src, vars_src), (tgt, vars_tgt), (syn, vars_syn)]:
2718 for var in vars:
2719 fullvar = var + G.name
2720 if fullvar in origvals:
2721 G.state(var)[:] = origvals[fullvar]
2722 else:
2723 val = rand(len(G))
2724 G.state(var)[:] = val
2725 origvals[fullvar] = val.copy()
2726 Network(src, tgt, syn).run(defaultclock.dt)
2727 for G, vars in [(src, vars_src), (tgt, vars_tgt), (syn, vars_syn)]:
2728 for var in vars:
2729 fullvar = var + G.name
2730 val = G.state(var)[:].copy()
2731 if fullvar in endvals:
2732 assert_allclose(val, endvals[fullvar])
2733 else:
2734 endvals[fullvar] = val
2735 numpy_generator_messages = [
2736 l
2737 for l in caught_logs
2738 if l[1] == "brian2.codegen.generators.numpy_generator"
2739 ]
2740 if should_be_able_to_use_ufunc_at:
2741 assert len(numpy_generator_messages) == 0
2742 else:
2743 assert len(numpy_generator_messages) == 1
2744 log_lev, log_mod, log_msg = numpy_generator_messages[0]
2745 assert log_msg.startswith("Failed to vectorise code")
2746 finally:
2747 NumpyCodeGenerator._use_ufunc_at_vectorisation = True # restore it
2748
2749
2750 def test_fallback_loop_and_stateless_func():
2751 # See github issue #1024
2752 if prefs.codegen.target != "numpy":
2753 pytest.skip("numpy-only test")
2754 source = NeuronGroup(2, "", threshold="True")
2755 target = NeuronGroup(1, "v : 1")
2756 synapses = Synapses(
2757 source,
2758 target,
2759 "x : 1",
2760 on_pre="""x = rand()
2761 v_post += 0.5*(1-v_post)""",
2762 )
2763 synapses.connect()
2764 with catch_logs(): # Suppress the warning
2765 run(defaultclock.dt)
2766
2767
2768 @pytest.mark.standalone_compatible
2769 def test_synapses_to_synapses_summed_variable():
2770 source = NeuronGroup(5, "")
2771 target = NeuronGroup(5, "")
2772 conn = Synapses(source, target, "w : integer")
2773 conn.connect(j="i")
2774 conn.w = 1
2775 summed_conn = Synapses(
2776 source,
2777 conn,
2778 """
2779 w_post = x : integer (summed)
2780 x : integer
2781 """,
2782 )
2783 summed_conn.connect("i>=j")
2784 summed_conn.x = "i"
2785 run(defaultclock.dt)
2786 assert_array_equal(conn.w[:], [10, 10, 9, 7, 4])
2787
2788
2789 @pytest.mark.codegen_independent
2790 def test_synapse_generator_syntax():
2791 parsed = parse_synapse_generator("k for k in sample(1, N, p=p) if abs(i-k)<10")
2792 assert parsed["element"] == "k"
2793 assert parsed["inner_variable"] == "k"
2794 assert parsed["iterator_func"] == "sample"
2795 assert parsed["iterator_kwds"]["low"] == "1"
2796 assert parsed["iterator_kwds"]["high"] == "N"
2797 assert parsed["iterator_kwds"]["step"] == "1"
2798 assert parsed["iterator_kwds"]["p"] == "p"
2799 assert parsed["iterator_kwds"]["size"] is None
2800 assert parsed["iterator_kwds"]["sample_size"] == "random"
2801 assert parsed["if_expression"] == "abs(i - k) < 10"
2802 parsed = parse_synapse_generator("k for k in sample(N, size=5) if abs(i-k)<10")
2803 assert parsed["element"] == "k"
2804 assert parsed["inner_variable"] == "k"
2805 assert parsed["iterator_func"] == "sample"
2806 assert parsed["iterator_kwds"]["low"] == "0"
2807 assert parsed["iterator_kwds"]["high"] == "N"
2808 assert parsed["iterator_kwds"]["step"] == "1"
2809 assert parsed["iterator_kwds"]["p"] is None
2810 assert parsed["iterator_kwds"]["size"] == "5"
2811 assert parsed["iterator_kwds"]["sample_size"] == "fixed"
2812 assert parsed["if_expression"] == "abs(i - k) < 10"
2813 parsed = parse_synapse_generator("k+1 for k in range(i-100, i+100, 2)")
2814 assert parsed["element"] == "k + 1"
2815 assert parsed["inner_variable"] == "k"
2816 assert parsed["iterator_func"] == "range"
2817 assert parsed["iterator_kwds"]["low"] == "i - 100"
2818 assert parsed["iterator_kwds"]["high"] == "i + 100"
2819 assert parsed["iterator_kwds"]["step"] == "2"
2820 assert parsed["if_expression"] == "True"
2821 with pytest.raises(SyntaxError):
2822 parse_synapse_generator("mad rubbish")
2823 with pytest.raises(SyntaxError):
2824 parse_synapse_generator("k+1")
2825 with pytest.raises(SyntaxError):
2826 parse_synapse_generator("k for k in range()")
2827 with pytest.raises(SyntaxError):
2828 parse_synapse_generator("k for k in range(1,2,3,4)")
2829 with pytest.raises(SyntaxError):
2830 parse_synapse_generator("k for k in range(1,2,3) if ")
2831 with pytest.raises(SyntaxError):
2832 parse_synapse_generator("k[1:3] for k in range(1,2,3)")
2833 with pytest.raises(SyntaxError):
2834 parse_synapse_generator("k for k in x")
2835 with pytest.raises(SyntaxError):
2836 parse_synapse_generator("k for k in x[1:5]")
2837 with pytest.raises(SyntaxError):
2838 parse_synapse_generator("k for k in sample()")
2839 with pytest.raises(SyntaxError):
2840 parse_synapse_generator("k for k in sample(N, p=0.1, size=5)")
2841 with pytest.raises(SyntaxError):
2842 parse_synapse_generator("k for k in sample(N, q=0.1)")
2843
2844
2845 def test_synapse_generator_out_of_range():
2846 G = NeuronGroup(16, "v : 1")
2847 G2 = NeuronGroup(4, "v : 1")
2848 G2.v = "16 + i"
2849
2850 S1 = Synapses(G, G2, "")
2851 with pytest.raises(BrianObjectException) as exc:
2852 S1.connect(j="k for k in range(0, N_post*2)")
2853 exc.errisinstance(IndexError)
2854
2855 # This should be fine
2856 S2 = Synapses(G, G, "")
2857 S2.connect(j="i+k for k in range(0, 5) if i <= N_post-5")
2858 expected = np.zeros((len(G), len(G)))
2859 expected[np.triu_indices(len(G))] = 1
2860 expected[np.triu_indices(len(G), 5)] = 0
2861 expected[len(G) - 4 :, :] = 0
2862 _compare(S2, expected)
2863
2864 # This should be fine (see #1037)
2865 S2 = Synapses(G, G, "")
2866 S2.connect(j="i+k for k in range(0, 5) if i <= N_post-5 and rand() <= 1")
2867 _compare(S2, expected)
2868
2869 # This could in principle be fine, but we cannot test the condition without
2870 # accessing the post-synaptic variable outside of its range. By analyzing
2871 # the post-synaptic condition, we could find out that the value of this
2872 # variable is actually irrelevant, but that makes things too complicated.
2873 S3 = Synapses(G, G, "")
2874 with pytest.raises(BrianObjectException) as exc:
2875 S3.connect(j="i+k for k in range(0, 5) if i <= N_post-5 and v_post >= 0")
2876 assert exc_isinstance(exc, IndexError)
2877 assert "outside allowed range" in str(exc.value.__cause__)
2878
2879
2880 @pytest.mark.standalone_compatible
2881 def test_synapse_generator_deterministic():
2882 # Same as "test_connection_string_deterministic" but using the generator
2883 # syntax
2884 G = NeuronGroup(16, "v : 1")
2885 G.v = "i"
2886 G2 = NeuronGroup(4, "v : 1")
2887 G2.v = "16 + i"
2888
2889 # Full connection
2890 expected_full = np.ones((len(G), len(G2)))
2891
2892 S1 = Synapses(G, G2)
2893 S1.connect(j="k for k in range(N_post)")
2894
2895 # Full connection without self-connections
2896 expected_no_self = np.ones((len(G), len(G))) - np.eye(len(G))
2897
2898 S2 = Synapses(G, G)
2899 S2.connect(j="k for k in range(N_post) if k != i")
2900
2901 S3 = Synapses(G, G)
2902 # slightly confusing with j on the RHS, but it should work...
2903 S3.connect(j="k for k in range(N_post) if j != i")
2904
2905 S4 = Synapses(G, G)
2906 S4.connect(j="k for k in range(N_post) if v_post != v_pre")
2907
2908 # One-to-one connectivity
2909 expected_one_to_one = np.eye(len(G))
2910
2911 S5 = Synapses(G, G)
2912 S5.connect(j="k for k in range(N_post) if k == i") # inefficient
2913
2914 S6 = Synapses(G, G)
2915 # slightly confusing with j on the RHS, but it should work...
2916 S6.connect(j="k for k in range(N_post) if j == i") # inefficient
2917
2918 S7 = Synapses(G, G)
2919 S7.connect(j="k for k in range(N_post) if v_pre == v_post") # inefficient
2920
2921 S8 = Synapses(G, G)
2922 S8.connect(j="i for _ in range(1)") # efficient
2923
2924 S9 = Synapses(G, G)
2925 S9.connect(j="i") # short form of the above
2926
2927 with catch_logs() as _: # Ignore warnings about empty synapses
2928 run(0 * ms) # for standalone
2929
2930 _compare(S1, expected_full)
2931 _compare(S2, expected_no_self)
2932 _compare(S3, expected_no_self)
2933 _compare(S4, expected_no_self)
2934 _compare(S5, expected_one_to_one)
2935 _compare(S6, expected_one_to_one)
2936 _compare(S7, expected_one_to_one)
2937 _compare(S8, expected_one_to_one)
2938 _compare(S9, expected_one_to_one)
2939
2940
2941 @pytest.mark.standalone_compatible
2942 def test_synapse_generator_deterministic_over_postsynaptic():
2943 # Same as "test_connection_string_deterministic" but using the generator
2944 # syntax and iterating over post-synaptic variables
2945 G = NeuronGroup(16, "v : 1")
2946 G.v = "i"
2947 G2 = NeuronGroup(4, "v : 1")
2948 G2.v = "16 + i"
2949
2950 # Full connection
2951 expected_full = np.ones((len(G), len(G2)))
2952
2953 S1 = Synapses(G, G2)
2954 S1.connect(i="k for k in range(N_pre)")
2955
2956 # Full connection without self-connections
2957 expected_no_self = np.ones((len(G), len(G))) - np.eye(len(G))
2958
2959 S2 = Synapses(G, G)
2960 S2.connect(i="k for k in range(N_pre) if k != j")
2961
2962 S3 = Synapses(G, G)
2963 # slightly confusing with i on the RHS, but it should work...
2964 S3.connect(i="k for k in range(N_pre) if i != j")
2965
2966 S4 = Synapses(G, G)
2967 S4.connect(j="k for k in range(N_pre) if v_pre != v_post")
2968
2969 # One-to-one connectivity
2970 expected_one_to_one = np.eye(len(G))
2971
2972 S5 = Synapses(G, G)
2973 S5.connect(i="k for k in range(N_pre) if k == j") # inefficient
2974
2975 S6 = Synapses(G, G)
2976 # slightly confusing with j on the RHS, but it should work...
2977 S6.connect(i="k for k in range(N_pre) if i == j") # inefficient
2978
2979 S7 = Synapses(G, G)
2980 S7.connect(i="k for k in range(N_pre) if v_pre == v_post") # inefficient
2981
2982 S8 = Synapses(G, G)
2983 S8.connect(i="j for _ in range(1)") # efficient
2984
2985 S9 = Synapses(G, G)
2986 S9.connect(i="j") # short form of the above
2987
2988 with catch_logs() as _: # Ignore warnings about empty synapses
2989 run(0 * ms) # for standalone
2990
2991 _compare(S1, expected_full)
2992 _compare(S2, expected_no_self)
2993 _compare(S3, expected_no_self)
2994 _compare(S4, expected_no_self)
2995 _compare(S5, expected_one_to_one)
2996 _compare(S6, expected_one_to_one)
2997 _compare(S7, expected_one_to_one)
2998 _compare(S8, expected_one_to_one)
2999 _compare(S9, expected_one_to_one)
3000
3001
3002 @pytest.mark.standalone_compatible
3003 @pytest.mark.long
3004 def test_synapse_generator_deterministic_2():
3005 # Same as "test_connection_string_deterministic" but using the generator
3006 # syntax
3007 G = NeuronGroup(16, "")
3008 G2 = NeuronGroup(4, "")
3009 # A few more tests of deterministic connections where the generator syntax
3010 # is particularly useful
3011
3012 # Ring structure
3013 S10 = Synapses(G, G)
3014 S10.connect(j="(i + (-1)**k) % N_post for k in range(2)")
3015 expected_ring = np.zeros((len(G), len(G)), dtype=np.int32)
3016 expected_ring[np.arange(15), np.arange(15) + 1] = 1 # Next cell
3017 expected_ring[np.arange(1, 16), np.arange(15)] = 1 # Previous cell
3018 expected_ring[[0, 15], [15, 0]] = 1 # wrap around the ring
3019
3020 # Diverging connection pattern
3021 S11 = Synapses(G2, G)
3022 S11.connect(j="i*4 + k for k in range(4)")
3023 expected_diverging = np.zeros((len(G2), len(G)), dtype=np.int32)
3024 for source in range(4):
3025 expected_diverging[source, np.arange(4) + source * 4] = 1
3026
3027 # Diverging connection pattern within population (no self-connections)
3028 S11b = Synapses(G2, G2)
3029 S11b.connect(j="k for k in range(i-3, i+4) if i!=k", skip_if_invalid=True)
3030 expected_diverging_b = np.zeros((len(G2), len(G2)), dtype=np.int32)
3031 for source in range(len(G2)):
3032 expected_diverging_b[
3033 source, np.clip(np.arange(-3, 4) + source, 0, len(G2) - 1)
3034 ] = 1
3035 expected_diverging_b[source, source] = 0
3036
3037 # Converging connection pattern
3038 S12 = Synapses(G, G2)
3039 S12.connect(j="int(i/4)")
3040 expected_converging = np.zeros((len(G), len(G2)), dtype=np.int32)
3041 for target in range(4):
3042 expected_converging[np.arange(4) + target * 4, target] = 1
3043
3044 # skip if invalid
3045 S13 = Synapses(G2, G2)
3046 S13.connect(j="i+(-1)**k for k in range(2)", skip_if_invalid=True)
3047 expected_offdiagonal = np.zeros((len(G2), len(G2)), dtype=np.int32)
3048 expected_offdiagonal[np.arange(len(G2) - 1), np.arange(len(G2) - 1) + 1] = 1
3049 expected_offdiagonal[np.arange(len(G2) - 1) + 1, np.arange(len(G2) - 1)] = 1
3050
3051 # Converging connection pattern with restriction
3052 S14 = Synapses(G, G2)
3053 S14.connect(j="int(i/4) if i % 2 == 0")
3054 expected_converging_restricted = np.zeros((len(G), len(G2)), dtype=np.int32)
3055 for target in range(4):
3056 expected_converging_restricted[np.arange(4, step=2) + target * 4, target] = 1
3057
3058 # Connecting to post indices >= source index
3059 expected_diagonal = np.zeros((len(G), len(G)), dtype=np.int32)
3060 expected_diagonal[np.triu_indices(len(G))] = 1
3061 S15 = Synapses(G, G)
3062 S15.connect(j="i + k for k in range(0, N_post-i)")
3063
3064 S15b = Synapses(G, G)
3065 S15b.connect(j="i + k for k in range(0, N_post)", skip_if_invalid=True)
3066
3067 S15c = Synapses(G, G)
3068 S15c.connect(j="i + k for k in range(0, N_post) if j < N_post")
3069
3070 S15d = Synapses(G, G)
3071 S15d.connect(j="i + k for k in range(0, N_post) if i + k < N_post")
3072
3073 with catch_logs() as _: # Ignore warnings about empty synapses
3074 run(0 * ms) # for standalone
3075
3076 _compare(S10, expected_ring)
3077 _compare(S11, expected_diverging)
3078 _compare(S11b, expected_diverging_b)
3079 _compare(S12, expected_converging)
3080 _compare(S13, expected_offdiagonal)
3081 _compare(S14, expected_converging_restricted)
3082 _compare(S15, expected_diagonal)
3083 _compare(S15b, expected_diagonal)
3084 _compare(S15c, expected_diagonal)
3085 _compare(S15d, expected_diagonal)
3086
3087
3088 @pytest.mark.standalone_compatible
3089 def test_synapse_generator_random():
3090 # The same tests as test_connection_random_without_condition, but using
3091 # the generator syntax
3092 G = NeuronGroup(4, "x : integer")
3093 G.x = "i"
3094 G2 = NeuronGroup(7, "")
3095
3096 S1 = Synapses(G, G2)
3097 S1.connect(j="k for k in sample(N_post, p=0)")
3098
3099 S2 = Synapses(G, G2)
3100 S2.connect(j="k for k in sample(N_post, p=1)")
3101
3102 # Just make sure using values between 0 and 1 work in principle
3103 S3 = Synapses(G, G2)
3104 S3.connect(j="k for k in sample(N_post, p=0.3)")
3105
3106 # Use pre-/post-synaptic variables for "stochastic" connections that are
3107 # actually deterministic
3108 S4 = Synapses(G, G2)
3109 S4.connect(j="k for k in sample(N_post, p=int(x_pre==2)*1.0)")
3110
3111 with catch_logs() as _: # Ignore warnings about empty synapses
3112 run(0 * ms) # for standalone
3113
3114 assert len(S1) == 0
3115 _compare(S2, np.ones((len(G), len(G2))))
3116 assert 0 <= len(S3) <= len(G) * len(G2)
3117 assert len(S4) == 7
3118 assert_equal(S4.i, np.ones(7) * 2)
3119 assert_equal(S4.j, np.arange(7))
3120
3121
3122 @pytest.mark.standalone_compatible
3123 def test_synapse_generator_random_over_postsynaptic():
3124 # The same tests as test_connection_random_without_condition, but using
3125 # the generator syntax and iterating over post-synaptic neurons
3126 G = NeuronGroup(4, "")
3127 G2 = NeuronGroup(7, "y : 1")
3128 G2.y = "i"
3129
3130 S1 = Synapses(G, G2)
3131 S1.connect(i="k for k in sample(N_pre, p=0)")
3132
3133 S2 = Synapses(G, G2)
3134 S2.connect(i="k for k in sample(N_pre, p=1)")
3135
3136 # Just make sure using values between 0 and 1 work in principle
3137 S3 = Synapses(G, G2)
3138 S3.connect(i="k for k in sample(N_pre, p=0.3)")
3139
3140 # Use pre-/post-synaptic variables for "stochastic" connections that are
3141 # actually deterministic
3142 S4 = Synapses(G, G2)
3143 S4.connect(i="k for k in sample(N_pre, p=int(y_post==2)*1.0)")
3144
3145 with catch_logs() as _: # Ignore warnings about empty synapses
3146 run(0 * ms) # for standalone
3147
3148 assert len(S1) == 0
3149 _compare(S2, np.ones((len(G), len(G2))))
3150 assert 0 <= len(S3) <= len(G) * len(G2)
3151 assert len(S4) == 4
3152 assert_equal(S4.i, np.arange(4))
3153 assert_equal(S4.j, np.ones(4) * 2)
3154
3155
3156 @pytest.mark.standalone_compatible
3157 def test_synapse_generator_random_positive_steps():
3158 # Test generator with sampling from stepped ranges (e.g. all even numbers)
3159 G = NeuronGroup(4, "x : integer")
3160 G.x = "i"
3161 G2 = NeuronGroup(7, "")
3162
3163 S1 = Synapses(G, G2)
3164 S1.connect(j="k for k in sample(2, N_post, 2, p=0)")
3165
3166 S2 = Synapses(G, G2)
3167 S2.connect(j="k for k in sample(2, N_post, 2, p=1)")
3168
3169 # Just make sure using values between 0 and 1 work in principle (note that
3170 # 0.25 is the cutoff between the general method and the "jump method", so
3171 # we test a value above and below
3172 S3 = Synapses(G, G2)
3173 S3.connect(j="k for k in sample(2, N_post, 2, p=0.2)")
3174
3175 S3b = Synapses(G, G2)
3176 S3b.connect(j="k for k in sample(2, N_post, 2, p=0.3)")
3177
3178 # Use pre-/post-synaptic variables for "stochastic" connections that are
3179 # actually deterministic
3180 S4 = Synapses(G, G2)
3181 S4.connect(j="k for k in sample(2, N_post, 2, p=int(x_pre==2)*1.0)")
3182
3183 with catch_logs() as _: # Ignore warnings about empty synapses
3184 run(0 * ms) # for standalone
3185
3186 assert len(S1) == 0
3187 S2_comp = np.zeros((len(G), len(G2)))
3188 S2_comp[:, 2::2] = 1
3189 _compare(S2, S2_comp)
3190 assert 0 <= len(S3) <= len(G) * 3
3191 assert all(S3.j[:] % 2 == 0)
3192 assert all(S3.j >= 2)
3193 assert 0 <= len(S3b) <= len(G) * 3
3194 assert all(S3b.j[:] % 2 == 0)
3195 assert all(S3b.j >= 2)
3196 assert len(S4) == 3
3197 assert_equal(S4.i, np.ones(3) * 2)
3198 assert_equal(S4.j, np.arange(2, 7, 2))
3199
3200
3201 @pytest.mark.standalone_compatible
3202 def test_synapse_generator_random_negative_steps():
3203 # Test generator with sampling from stepped ranges (e.g. all even numbers)
3204 # going backwards
3205 G = NeuronGroup(4, "x : integer")
3206 G.x = "i"
3207 G2 = NeuronGroup(7, "")
3208
3209 S1 = Synapses(G, G2)
3210 S1.connect(j="k for k in sample(N_post-1, 0, -2, p=0)")
3211
3212 S2 = Synapses(G, G2)
3213 S2.connect(j="k for k in sample(N_post-1, 0, -2, p=1)")
3214
3215 # Just make sure using values between 0 and 1 work in principle (note that
3216 # 0.25 is the cutoff between the general method and the "jump method", so
3217 # we test a value above and below
3218 S3 = Synapses(G, G2)
3219 S3.connect(j="k for k in sample(N_post-1, 0, -2, p=0.2)")
3220
3221 S3b = Synapses(G, G2)
3222 S3b.connect(j="k for k in sample(N_post-1, 0, -2, p=0.3)")
3223
3224 # Use pre-/post-synaptic variables for "stochastic" connections that are
3225 # actually deterministic
3226 S4 = Synapses(G, G2)
3227 S4.connect(j="k for k in sample(N_post-1, 0, -2, p=int(x_pre==2)*1.0)")
3228
3229 with catch_logs() as _: # Ignore warnings about empty synapses
3230 run(0 * ms) # for standalone
3231
3232 assert len(S1) == 0
3233 S2_comp = np.zeros((len(G), len(G2)))
3234 S2_comp[:, 2::2] = 1
3235 _compare(S2, S2_comp)
3236 assert 0 <= len(S3) <= len(G) * 3
3237 assert all(S3.j[:] % 2 == 0)
3238 assert all(S3.j >= 2)
3239 assert 0 <= len(S3b) <= len(G) * 3
3240 assert all(S3b.j[:] % 2 == 0)
3241 assert all(S3b.j >= 2)
3242 assert len(S4) == 3
3243 assert_array_equal(S4.i, np.ones(3) * 2)
3244 assert_array_equal(S4.j, [6, 4, 2])
3245
3246
3247 @pytest.mark.standalone_compatible
3248 def test_synapse_generator_fixed_random():
3249 # Random samples with fixed size
3250 G = NeuronGroup(4, "x : integer")
3251 G.x = "i"
3252 G2 = NeuronGroup(7, "")
3253
3254 S1 = Synapses(G, G2)
3255 S1.connect(j="k for k in sample(N_post, size=0)")
3256
3257 S2 = Synapses(G, G2)
3258 S2.connect(j="k for k in sample(N_post, size=N_post)")
3259
3260 S3 = Synapses(G, G2)
3261 S3.connect(j="k for k in sample(N_post, size=3)")
3262
3263 # Use pre-/post-synaptic variables for "stochastic" connections that are
3264 # actually deterministic
3265 S4 = Synapses(G, G2)
3266 S4.connect(j="k for k in sample(N_post, size=int(x_pre==2)*N_post)")
3267
3268 with catch_logs() as _: # Ignore warnings about empty synapses
3269 run(0 * ms) # for standalone
3270
3271 assert len(S1) == 0
3272 _compare(S2, np.ones((len(G), len(G2))))
3273 # Each neuron should have 3 outgoing connections
3274 assert_array_equal(S3.N_outgoing_pre, np.ones(4) * 3)
3275 # Synapses should be sorted and unique
3276 for source_idx in range(4):
3277 assert len(set(S3.j[source_idx, :])) == 3
3278 assert all(S3.j[source_idx, :] == sorted(S3.j[source_idx, :]))
3279 assert len(S4) == 7
3280 assert_equal(S4.i, np.ones(7) * 2)
3281 assert_equal(S4.j, np.arange(7))
3282
3283
3284 @pytest.mark.standalone_compatible
3285 def test_synapse_generator_fixed_random_over_postsynaptic():
3286 # Random samples with fixed size, iterating over post-synaptic neurons
3287 G = NeuronGroup(4, "")
3288 G2 = NeuronGroup(7, "y : integer")
3289 G2.y = "i"
3290
3291 S1 = Synapses(G, G2)
3292 S1.connect(i="k for k in sample(N_pre, size=0)")
3293
3294 S2 = Synapses(G, G2)
3295 S2.connect(i="k for k in sample(N_pre, size=N_pre)")
3296
3297 S3 = Synapses(G, G2)
3298 S3.connect(i="k for k in sample(N_pre, size=3)")
3299
3300 # Use pre-/post-synaptic variables for "stochastic" connections that are
3301 # actually deterministic
3302 S4 = Synapses(G, G2)
3303 S4.connect(i="k for k in sample(N_pre, size=int(y_post==2)*N_pre)")
3304
3305 with catch_logs() as _: # Ignore warnings about empty synapses
3306 run(0 * ms) # for standalone
3307
3308 assert len(S1) == 0
3309 _compare(S2, np.ones((len(G), len(G2))))
3310 # Each neuron should have 3 incoming connections
3311 assert_array_equal(S3.N_incoming_post, np.ones(7) * 3)
3312 # Synapses should be sorted and unique
3313 for target_idx in range(7):
3314 assert len(set(S3.i[:, target_idx])) == 3
3315 assert all(S3.i[:, target_idx] == sorted(S3.i[:, target_idx]))
3316 assert len(S4) == 4
3317 assert_equal(S4.j, np.ones(4) * 2)
3318 assert_equal(S4.i, np.arange(4))
3319
3320
3321 @pytest.mark.standalone_compatible
3322 def test_synapse_generator_fixed_random_positive_steps():
3323 # Test generator with fixed-size sampling from stepped ranges (e.g. all
3324 # even numbers)
3325 G = NeuronGroup(4, "x : integer")
3326 G.x = "i"
3327 G2 = NeuronGroup(7, "")
3328
3329 S1 = Synapses(G, G2)
3330 S1.connect(j="k for k in sample(2, N_post, 2, size=0)")
3331
3332 S2 = Synapses(G, G2)
3333 S2.connect(j="k for k in sample(2, N_post, 2, size=3)")
3334
3335 # Just make sure using values between 0 and 1 work in principle
3336 S3 = Synapses(G, G2)
3337 S3.connect(j="k for k in sample(2, N_post, 2, size=2)")
3338
3339 # Use pre-/post-synaptic variables for "stochastic" connections that are
3340 # actually deterministic
3341 S4 = Synapses(G, G2)
3342 S4.connect(j="k for k in sample(2, N_post, 2, size=int(x_pre==2)*3)")
3343
3344 with catch_logs() as _: # Ignore warnings about empty synapses
3345 run(0 * ms) # for standalone
3346
3347 assert len(S1) == 0
3348 S2_comp = np.zeros((len(G), len(G2)))
3349 S2_comp[:, 2::2] = 1
3350 _compare(S2, S2_comp)
3351 assert len(S3) == len(G) * 2
3352 assert all(S3.N_outgoing_pre == 2)
3353 assert all(S3.j[:] % 2 == 0)
3354 assert all(S3.j >= 2)
3355 assert all([len(S3.j[x, :]) == len(set(S3.j[x, :])) for x in range(len(G))])
3356 assert len(S4) == 3
3357 assert_equal(S4.i, np.ones(3) * 2)
3358 assert_equal(S4.j, np.arange(2, 7, 2))
3359
3360
3361 @pytest.mark.standalone_compatible
3362 def test_synapse_generator_fixed_random_negative_steps():
3363 # Test generator with fixed-size sampling from stepped ranges (e.g. all
3364 # even numbers) going backwards
3365 G = NeuronGroup(4, "x : integer")
3366 G.x = "i"
3367 G2 = NeuronGroup(7, "")
3368
3369 S1 = Synapses(G, G2)
3370 S1.connect(j="k for k in sample(N_post-1, 0, -2, size=0)")
3371
3372 S2 = Synapses(G, G2)
3373 S2.connect(j="k for k in sample(N_post-1, 0, -2, size=3)")
3374
3375 # Just make sure using intermediate values between 0 and 1 work in principle
3376 S3 = Synapses(G, G2)
3377 S3.connect(j="k for k in sample(N_post-1, 0, -2, size=2)")
3378
3379 # Use pre-/post-synaptic variables for "stochastic" connections that are
3380 # actually deterministic
3381 S4 = Synapses(G, G2, "w:1")
3382 S4.connect(j="k for k in sample(N_post-1, 0, -2, size=int(x_pre==2)*3)")
3383
3384 with catch_logs() as _: # Ignore warnings about empty synapses
3385 run(0 * ms) # for standalone
3386
3387 assert len(S1) == 0
3388 S2_comp = np.zeros((len(G), len(G2)))
3389 S2_comp[:, 2::2] = 1
3390 _compare(S2, S2_comp)
3391 assert len(S3) == len(G) * 2
3392 assert all(S3.N_outgoing_pre == 2)
3393 assert all(S3.j[:] % 2 == 0)
3394 assert all(S3.j >= 2)
3395 assert all([len(S3.j[x, :]) == len(set(S3.j[x, :])) for x in range(len(G))])
3396 assert len(S4) == 3
3397 assert_equal(S4.i, np.ones(3) * 2)
3398 assert_equal(S4.j, np.arange(6, 0, -2))
3399
3400
3401 @pytest.mark.standalone_compatible
3402 def test_synapse_generator_fixed_random_error1():
3403 G = NeuronGroup(5, "")
3404 G2 = NeuronGroup(7, "")
3405 S = Synapses(G, G2)
3406 with pytest.raises((BrianObjectException, IndexError, RuntimeError)):
3407 # Won't work for i=4
3408 S.connect(j="k for k in sample(N_post, size=i+4)")
3409 run(0 * ms) # for standalone
3410
3411
3412 @pytest.mark.standalone_compatible
3413 def test_synapse_generator_fixed_random_error2():
3414 G = NeuronGroup(5, "")
3415 G2 = NeuronGroup(7, "")
3416 S = Synapses(G, G2)
3417 with pytest.raises((BrianObjectException, IndexError, RuntimeError)):
3418 # Won't work for i=4
3419 S.connect(j="k for k in sample(N_post, size=3-i)")
3420 run(0 * ms) # for standalone
3421
3422
3423 @pytest.mark.standalone_compatible
3424 def test_synapse_generator_fixed_random_skip_if_invalid():
3425 G = NeuronGroup(5, "")
3426 G2 = NeuronGroup(7, "")
3427 S1 = Synapses(G, G2)
3428 S2 = Synapses(G, G2)
3429 # > N_post for i=4
3430 S1.connect(j="k for k in sample(N_post, size=i+4)", skip_if_invalid=True)
3431 # < 0 for i=4
3432 S2.connect(j="k for k in sample(N_post, size=3-i)", skip_if_invalid=True)
3433 run(0 * ms) # for standalone
3434 assert_array_equal(S1.N_outgoing_pre, [4, 5, 6, 7, 7])
3435 assert_array_equal(S2.N_outgoing_pre, [3, 2, 1, 0, 0])
3436
3437
3438 @pytest.mark.standalone_compatible
3439 def test_synapse_generator_random_with_condition():
3440 G = NeuronGroup(4, "")
3441
3442 S1 = Synapses(G, G)
3443 S1.connect(j="k for k in sample(N_post, p=0) if i != k")
3444
3445 S2 = Synapses(G, G)
3446 S2.connect(j="k for k in sample(N_post, p=1) if i != k")
3447 expected2 = np.ones((len(G), len(G))) - np.eye(len(G))
3448
3449 S3 = Synapses(G, G)
3450 S3.connect(j="k for k in sample(N_post, p=0) if i >= 2")
3451
3452 S4 = Synapses(G, G)
3453 S4.connect(j="k for k in sample(N_post, p=1.0) if i >= 2")
3454 expected4 = np.zeros((len(G), len(G)))
3455 expected4[2, :] = 1
3456 expected4[3, :] = 1
3457
3458 S5 = Synapses(G, G)
3459 S5.connect(j="k for k in sample(N_post, p=0) if j < 2") # inefficient
3460
3461 S6 = Synapses(G, G)
3462 S6.connect(j="k for k in sample(2, p=0)") # better
3463
3464 S7 = Synapses(G, G)
3465 expected7 = np.zeros((len(G), len(G)))
3466 expected7[:, 0] = 1
3467 expected7[:, 1] = 1
3468 S7.connect(j="k for k in sample(N_post, p=1.0) if j < 2") # inefficient
3469
3470 S8 = Synapses(G, G)
3471 S8.connect(j="k for k in sample(2, p=1.0)") # better
3472
3473 with catch_logs() as _: # Ignore warnings about empty synapses
3474 run(0 * ms) # for standalone
3475
3476 assert len(S1) == 0
3477 _compare(S2, expected2)
3478 assert len(S3) == 0
3479 _compare(S4, expected4)
3480 assert len(S5) == 0
3481 assert len(S6) == 0
3482 _compare(S7, expected7)
3483 _compare(S8, expected7)
3484
3485
3486 @pytest.mark.standalone_compatible
3487 @pytest.mark.long
3488 def test_synapse_generator_random_with_condition_2():
3489 G = NeuronGroup(4, "")
3490
3491 # Just checking that everything works in principle (we can't check the
3492 # actual connections)
3493 S9 = Synapses(G, G)
3494 S9.connect(j="k for k in sample(N_post, p=0.001) if i != k")
3495
3496 S10 = Synapses(G, G)
3497 S10.connect(j="k for k in sample(N_post, p=0.03) if i != k")
3498
3499 S11 = Synapses(G, G)
3500 S11.connect(j="k for k in sample(N_post, p=0.1) if i != k")
3501
3502 S12 = Synapses(G, G)
3503 S12.connect(j="k for k in sample(N_post, p=0.9) if i != k")
3504
3505 S13 = Synapses(G, G)
3506 S13.connect(j="k for k in sample(N_post, p=0.001) if i >= 2")
3507
3508 S14 = Synapses(G, G)
3509 S14.connect(j="k for k in sample(N_post, p=0.03) if i >= 2")
3510
3511 S15 = Synapses(G, G)
3512 S15.connect(j="k for k in sample(N_post, p=0.1) if i >= 2")
3513
3514 S16 = Synapses(G, G)
3515 S16.connect(j="k for k in sample(N_post, p=0.9) if i >= 2")
3516
3517 S17 = Synapses(G, G)
3518 S17.connect(j="k for k in sample(N_post, p=0.001) if j < 2")
3519
3520 S18 = Synapses(G, G)
3521 S18.connect(j="k for k in sample(N_post, p=0.03) if j < 2")
3522
3523 S19 = Synapses(G, G)
3524 S19.connect(j="k for k in sample(N_post, p=0.1) if j < 2")
3525
3526 S20 = Synapses(G, G)
3527 S20.connect(j="k for k in sample(N_post, p=0.9) if j < 2")
3528
3529 S21 = Synapses(G, G)
3530 S21.connect(j="k for k in sample(2, p=0.001)")
3531
3532 S22 = Synapses(G, G)
3533 S22.connect(j="k for k in sample(2, p=0.03)")
3534
3535 S23 = Synapses(G, G)
3536 S23.connect(j="k for k in sample(2, p=0.1)")
3537
3538 S24 = Synapses(G, G)
3539 S24.connect(j="k for k in sample(2, p=0.9)")
3540
3541 # Some more tests specific to the generator syntax
3542 S25 = Synapses(G, G)
3543 S25.connect(j="i+1 for _ in sample(1, p=0.5) if i < N_post-1")
3544
3545 S26 = Synapses(G, G)
3546 S26.connect(j="i+k for k in sample(N_post-i, p=0.5)")
3547
3548 with catch_logs() as _: # Ignore warnings about empty synapses
3549 run(0 * ms) # for standalone
3550
3551 assert not any(S9.i == S9.j)
3552 assert 0 <= len(S9) <= len(G) * (len(G) - 1)
3553 assert not any(S10.i == S10.j)
3554 assert 0 <= len(S10) <= len(G) * (len(G) - 1)
3555 assert not any(S11.i == S11.j)
3556 assert 0 <= len(S11) <= len(G) * (len(G) - 1)
3557 assert not any(S12.i == S12.j)
3558 assert 0 <= len(S12) <= len(G) * (len(G) - 1)
3559 assert all(S13.i[:] >= 2)
3560 assert 0 <= len(S13) <= len(G) * (len(G) - 1)
3561 assert all(S14.i[:] >= 2)
3562 assert 0 <= len(S14) <= len(G) * (len(G) - 1)
3563 assert all(S15.i[:] >= 2)
3564 assert 0 <= len(S15) <= len(G) * (len(G) - 1)
3565 assert all(S16.i[:] >= 2)
3566 assert 0 <= len(S16) <= len(G) * (len(G) - 1)
3567 assert all(S17.j[:] < 2)
3568 assert 0 <= len(S17) <= len(G) * (len(G) - 1)
3569 assert all(S18.j[:] < 2)
3570 assert 0 <= len(S18) <= len(G) * (len(G) - 1)
3571 assert all(S19.j[:] < 2)
3572 assert 0 <= len(S19) <= len(G) * (len(G) - 1)
3573 assert all(S20.j[:] < 2)
3574 assert 0 <= len(S20) <= len(G) * (len(G) - 1)
3575 assert all(S21.j[:] < 2)
3576 assert 0 <= len(S21) <= len(G) * (len(G) - 1)
3577 assert all(S22.j[:] < 2)
3578 assert 0 <= len(S22) <= len(G) * (len(G) - 1)
3579 assert all(S23.j[:] < 2)
3580 assert 0 <= len(S23) <= len(G) * (len(G) - 1)
3581 assert all(S24.j[:] < 2)
3582 assert 0 <= len(S24) <= len(G) * (len(G) - 1)
3583 assert 0 <= len(S25) <= len(G)
3584 assert_equal(S25.j[:], S25.i[:] + 1)
3585 assert 0 <= len(S26) <= (1 + len(G)) * (len(G) / 2)
3586 assert all(S26.j[:] >= S26.i[:])
3587
3588
3589 @pytest.mark.standalone_compatible
3590 def test_synapses_refractory():
3591 source = NeuronGroup(10, "", threshold="True")
3592 target = NeuronGroup(
3593 10,
3594 "dv/dt = 0/second : 1 (unless refractory)",
3595 threshold="i>=5",
3596 refractory=defaultclock.dt,
3597 )
3598 S = Synapses(source, target, on_pre="v += 1")
3599 S.connect(j="i")
3600 run(defaultclock.dt + schedule_propagation_offset())
3601 assert_allclose(target.v[:5], 1)
3602 assert_allclose(target.v[5:], 0)
3603
3604
3605 @pytest.mark.standalone_compatible
3606 def test_synapses_refractory_rand():
3607 source = NeuronGroup(10, "", threshold="True")
3608 target = NeuronGroup(
3609 10,
3610 "dv/dt = 0/second : 1 (unless refractory)",
3611 threshold="i>=5",
3612 refractory=defaultclock.dt,
3613 )
3614 S = Synapses(source, target, on_pre="v += rand()")
3615 S.connect(j="i")
3616 with catch_logs() as _:
3617 # Currently, rand() is a stateful function (we do not make use of
3618 # _vectorisation_idx yet to make random numbers completely
3619 # reproducible), which will lead to a warning, since the result depends
3620 # on the order of execution.
3621 run(defaultclock.dt + schedule_propagation_offset())
3622 assert all(target.v[:5] > 0)
3623 assert_allclose(target.v[5:], 0)
3624
3625
3626 @pytest.mark.codegen_independent
3627 def test_synapse_generator_range_noint():
3628 # arguments to `range` should only be integers (issue #781)
3629 G = NeuronGroup(42, "")
3630 S = Synapses(G, G)
3631 msg = (
3632 r"The '{}' argument of the range function was .+, but it needs to be an"
3633 r" integer\."
3634 )
3635 with pytest.raises(TypeError, match=msg.format("high")):
3636 S.connect(j="k for k in range(42.0)")
3637 with pytest.raises(TypeError, match=msg.format("low")):
3638 S.connect(j="k for k in range(0.0, 42)")
3639 with pytest.raises(TypeError, match=msg.format("high")):
3640 S.connect(j="k for k in range(0, 42.0)")
3641 with pytest.raises(TypeError, match=msg.format("step")):
3642 S.connect(j="k for k in range(0, 42, 1.0)")
3643 with pytest.raises(TypeError, match=msg.format("low")):
3644 S.connect(j="k for k in range(True, 42)")
3645 with pytest.raises(TypeError, match=msg.format("high")):
3646 S.connect(j="k for k in range(0, True)")
3647 with pytest.raises(TypeError, match=msg.format("step")):
3648 S.connect(j="k for k in range(0, 42, True)")
3649
3650
3651 @pytest.mark.codegen_independent
3652 def test_missing_lastupdate_error_syn_pathway():
3653 G = NeuronGroup(1, "v : 1", threshold="False")
3654 S = Synapses(G, G, on_pre="v += exp(-lastupdate/dt)")
3655 S.connect()
3656 with pytest.raises(BrianObjectException) as exc:
3657 run(0 * ms)
3658 assert exc_isinstance(exc, KeyError)
3659 assert "lastupdate = t" in str(exc.value.__cause__)
3660 assert "lastupdate : second" in str(exc.value.__cause__)
3661
3662
3663 @pytest.mark.codegen_independent
3664 def test_missing_lastupdate_error_run_regularly():
3665 G = NeuronGroup(1, "v : 1")
3666 S = Synapses(G, G)
3667 S.connect()
3668 S.run_regularly("v += exp(-lastupdate/dt")
3669 with pytest.raises(BrianObjectException) as exc:
3670 run(0 * ms)
3671 assert exc_isinstance(exc, KeyError)
3672 assert "lastupdate = t" in str(exc.value.__cause__)
3673 assert "lastupdate : second" in str(exc.value.__cause__)
3674
3675
3676 @pytest.mark.codegen_independent
3677 def test_synaptic_subgroups():
3678 source = NeuronGroup(5, "")
3679 target = NeuronGroup(3, "")
3680 syn = Synapses(source, target)
3681 syn.connect()
3682 assert len(syn) == 15
3683
3684 from_3 = syn[3, :]
3685 assert len(from_3) == 3
3686 assert all(syn.i[from_3] == 3)
3687 assert_array_equal(syn.j[from_3], np.arange(3))
3688
3689 to_2 = syn[:, 2]
3690 assert len(to_2) == 5
3691 assert all(syn.j[to_2] == 2)
3692 assert_array_equal(syn.i[to_2], np.arange(5))
3693
3694 mixed = syn[1:3, :2]
3695 assert len(mixed) == 4
3696 connections = {(i, j) for i, j in zip(syn.i[mixed], syn.j[mixed])}
3697 assert connections == {(1, 0), (1, 1), (2, 0), (2, 1)}
3698
3699
3700 @pytest.mark.codegen_independent
3701 def test_incorrect_connect_N_incoming_outgoing():
3702 # See github issue #1227
3703 source = NeuronGroup(5, "")
3704 target = NeuronGroup(3, "")
3705 syn = Synapses(source, target)
3706
3707 with pytest.raises(ValueError) as ex:
3708 syn.connect("N_incoming < 5")
3709 assert "N_incoming" in str(ex)
3710
3711 with pytest.raises(ValueError) as ex:
3712 syn.connect("N_outgoing < 5")
3713 assert "N_outgoing" in str(ex)
3714
3715
3716 @pytest.mark.codegen_independent
3717 def test_setting_from_weight_matrix():
3718 # fully connected weight matrix
3719 # weights[source_index, target_index]
3720 weights = np.array([[1, 2, 3], [4, 5, 6]])
3721
3722 source = NeuronGroup(2, "")
3723 target = NeuronGroup(3, "")
3724
3725 syn = Synapses(source, target, "w : 1")
3726 syn.connect()
3727 syn.w[:] = weights.flatten()
3728
3729 for (i, j), w in np.ndenumerate(weights):
3730 assert all(syn.w[i, j] == weights[i, j])
3731
3732
3733 if __name__ == "__main__":
3734 SANITY_CHECK_PERMUTATION_ANALYSIS_EXAMPLE = True
3735 # prefs.codegen.target = 'numpy'
3736 # prefs._backup()
3737 import time
3738
3739 from _pytest.outcomes import Skipped
3740
3741 from brian2 import prefs
3742
3743 start = time.time()
3744
3745 test_creation()
3746 test_name_clashes()
3747 test_incoming_outgoing()
3748 test_connection_string_deterministic_full()
3749 test_connection_string_deterministic_full_no_self()
3750 test_connection_string_deterministic_full_one_to_one()
3751 test_connection_string_deterministic_full_custom()
3752 test_connection_string_deterministic_multiple_and()
3753 test_connection_random_with_condition()
3754 test_connection_random_with_condition_2()
3755 test_connection_random_without_condition()
3756 test_connection_random_with_indices()
3757 test_connection_multiple_synapses()
3758 test_connection_arrays()
3759 reinit_and_delete()
3760 test_state_variable_assignment()
3761 test_state_variable_indexing()
3762 test_indices()
3763 test_subexpression_references()
3764 test_nested_subexpression_references()
3765 test_constant_variable_subexpression_in_synapses()
3766 test_equations_unit_check()
3767 test_delay_specification()
3768 test_delays_pathways()
3769 test_delays_pathways_subgroups()
3770 test_pre_before_post()
3771 test_pre_post_simple()
3772 test_transmission_simple()
3773 test_transmission_custom_event()
3774 test_invalid_custom_event()
3775 test_transmission()
3776 test_transmission_all_to_one_heterogeneous_delays()
3777 test_transmission_one_to_all_heterogeneous_delays()
3778 test_transmission_scalar_delay()
3779 test_transmission_scalar_delay_different_clocks()
3780 test_transmission_boolean_variable()
3781 test_clocks()
3782 test_changed_dt_spikes_in_queue()
3783 test_no_synapses()
3784 test_no_synapses_variable_write()
3785 test_summed_variable()
3786 test_summed_variable_pre_and_post()
3787 test_summed_variable_differing_group_size()
3788 test_summed_variable_errors()
3789 test_multiple_summed_variables()
3790 test_summed_variables_subgroups()
3791 test_summed_variables_overlapping_subgroups()
3792 test_summed_variables_linked_variables()
3793 test_scalar_parameter_access()
3794 test_scalar_subexpression()
3795 test_sim_with_scalar_variable()
3796 test_sim_with_scalar_subexpression()
3797 test_sim_with_constant_subexpression()
3798 test_external_variables()
3799 test_event_driven()
3800 test_event_driven_dependency_error()
3801 test_event_driven_dependency_error2()
3802 test_event_driven_dependency_error3()
3803 test_repr()
3804 test_pre_post_variables()
3805 test_variables_by_owner()
3806 test_permutation_analysis()
3807 test_vectorisation()
3808 test_vectorisation_STDP_like()
3809 test_synaptic_equations()
3810 test_synapse_with_run_regularly()
3811 test_synapses_to_synapses()
3812 test_synapses_to_synapses_statevar_access()
3813 test_synapses_to_synapses_different_sizes()
3814 test_synapses_to_synapses_summed_variable()
3815 try:
3816 test_ufunc_at_vectorisation()
3817 test_fallback_loop_and_stateless_func()
3818 except Skipped:
3819 print("Skipping numpy-only test")
3820 test_synapse_generator_syntax()
3821 test_synapse_generator_out_of_range()
3822 test_synapse_generator_deterministic()
3823 test_synapse_generator_deterministic_2()
3824 test_synapse_generator_random()
3825 test_synapse_generator_random_with_condition()
3826 test_synapse_generator_random_with_condition_2()
3827 test_synapses_refractory()
3828 test_synapses_refractory_rand()
3829 test_synapse_generator_range_noint()
3830 test_missing_lastupdate_error_syn_pathway()
3831 test_missing_lastupdate_error_run_regularly()
3832 test_synaptic_subgroups()
3833 test_incorrect_connect_N_incoming_outgoing()
3834 test_setting_from_weight_matrix()
3835
3836 print("Tests took", time.time() - start)