Debian Codegraph @

brian2/tests/test_subgroup.py

raw
1 import pytest
2 from numpy.testing import assert_array_equal, assert_equal
3
4 from brian2 import *
5 from brian2.core.network import schedule_propagation_offset
6 from brian2.devices.device import reinit_and_delete
7 from brian2.tests.utils import assert_allclose
8 from brian2.units.fundamentalunits import DIMENSIONLESS
9 from brian2.utils.logger import catch_logs
10
11
12 @pytest.mark.codegen_independent
13 def test_str_repr():
14 """
15 Test the string representation of a subgroup.
16 """
17 G = NeuronGroup(10, "v:1")
18 SG = G[5:8]
19 # very basic test, only make sure no error is raised
20 assert len(str(SG))
21 assert len(repr(SG))
22
23
24 def test_state_variables():
25 """
26 Test the setting and accessing of state variables in subgroups.
27 """
28 G = NeuronGroup(10, "v : volt")
29 SG = G[4:9]
30 with pytest.raises(DimensionMismatchError):
31 SG.__setattr__("v", -70)
32 SG.v_ = float(-80 * mV)
33 assert_allclose(G.v, np.array([0, 0, 0, 0, -80, -80, -80, -80, -80, 0]) * mV)
34 assert_allclose(SG.v, np.array([-80, -80, -80, -80, -80]) * mV)
35 assert_allclose(
36 G.v_, np.array([0, 0, 0, 0, -80, -80, -80, -80, -80, 0]) * float(mV)
37 )
38 assert_allclose(SG.v_, np.array([-80, -80, -80, -80, -80]) * float(mV))
39 # You should also be able to set variables with a string
40 SG.v = "v + i*mV"
41 assert_allclose(SG.v[0], -80 * mV)
42 assert_allclose(SG.v[4], -76 * mV)
43 assert_allclose(G.v[4:9], -80 * mV + np.arange(5) * mV)
44
45 # Calculating with state variables should work too
46 assert all(G.v[4:9] - SG.v == 0)
47
48 # And in-place modification should work as well
49 SG.v += 10 * mV
50 assert_allclose(G.v[4:9], -70 * mV + np.arange(5) * mV)
51 SG.v *= 2
52 assert_allclose(G.v[4:9], 2 * (-70 * mV + np.arange(5) * mV))
53 # with unit checking
54 with pytest.raises(DimensionMismatchError):
55 SG.v.__iadd__(3 * second)
56 with pytest.raises(DimensionMismatchError):
57 SG.v.__iadd__(3)
58 with pytest.raises(DimensionMismatchError):
59 SG.v.__imul__(3 * second)
60
61 # Indexing with subgroups
62 assert_equal(G.v[SG], SG.v[:])
63
64
65 @pytest.mark.standalone_compatible
66 def test_state_variables_simple():
67 G = NeuronGroup(
68 10,
69 """
70 a : 1
71 b : 1
72 c : 1
73 d : 1
74 """,
75 )
76 SG = G[3:7]
77 SG.a = 1
78 SG.a["i == 0"] = 2
79 SG.b = "i"
80 SG.b["i == 3"] = "i * 2"
81 SG.c = np.arange(3, 7)
82 SG.d[1:2] = 4
83 SG.d[2:4] = [1, 2]
84 run(0 * ms)
85 assert_equal(G.a[:], [0, 0, 0, 2, 1, 1, 1, 0, 0, 0])
86 assert_equal(G.b[:], [0, 0, 0, 0, 1, 2, 6, 0, 0, 0])
87 assert_equal(G.c[:], [0, 0, 0, 3, 4, 5, 6, 0, 0, 0])
88 assert_equal(G.d[:], [0, 0, 0, 0, 4, 1, 2, 0, 0, 0])
89
90
91 def test_state_variables_string_indices():
92 """
93 Test accessing subgroups with string indices.
94 """
95 G = NeuronGroup(10, "v : volt")
96 SG = G[4:9]
97 assert len(SG.v["i>3"]) == 1
98
99 G.v = np.arange(10) * mV
100 assert len(SG.v["v>7.5*mV"]) == 1
101
102 # Combined string indexing and assignment
103 SG.v["i > 3"] = "i*10*mV"
104
105 assert_allclose(G.v[:], [0, 1, 2, 3, 4, 5, 6, 7, 40, 9] * mV)
106
107
108 @pytest.mark.codegen_independent
109 def test_state_variables_group_as_index():
110 G = NeuronGroup(10, "v : 1")
111 SG = G[4:9]
112 G.v[SG] = 1
113 assert_equal(G.v[:], np.array([0, 0, 0, 0, 1, 1, 1, 1, 1, 0]))
114 G.v = 1
115 G.v[SG] = "2*v"
116 assert_equal(G.v[:], np.array([1, 1, 1, 1, 2, 2, 2, 2, 2, 1]))
117
118
119 @pytest.mark.codegen_independent
120 def test_state_variables_group_as_index_problematic():
121 G = NeuronGroup(10, "v : 1")
122 SG = G[4:9]
123 G.v = 1
124 tests = [
125 ("i", 1),
126 ("N", 1),
127 ("N + i", 2),
128 ("v", 0),
129 ]
130 for value, n_ambiguous in tests:
131 with catch_logs() as l:
132 G.v.__setitem__(SG, value)
133 ambiguous_found = sum(
134 [1 for entry in l if entry[1].endswith("ambiguous_string_expression")]
135 )
136 assert ambiguous_found == n_ambiguous, (
137 f"Expected {n_ambiguous} ambiguous warnings for value '{value}', "
138 f"but got {ambiguous_found}"
139 )
140
141
142 @pytest.mark.standalone_compatible
143 def test_variableview_calculations():
144 # Check that you can directly calculate with "variable views"
145 G = NeuronGroup(
146 10,
147 """
148 x : 1
149 y : volt
150 idx : integer
151 """,
152 )
153 G.x = np.arange(10)
154 G.y = np.arange(10)[::-1] * mV
155 G.idx = np.arange(10, dtype=int)
156 SG = G[3:8]
157
158 assert_allclose(SG.x * SG.y, np.arange(3, 8) * np.arange(6, 1, -1) * mV)
159 assert_allclose(-SG.x, -np.arange(3, 8))
160 assert_allclose(-SG.y, -np.arange(6, 1, -1) * mV)
161
162 assert_allclose(3 * SG.x, 3 * np.arange(3, 8))
163 assert_allclose(3 * SG.y, 3 * np.arange(6, 1, -1) * mV)
164 assert_allclose(SG.x * 3, 3 * np.arange(3, 8))
165 assert_allclose(SG.y * 3, 3 * np.arange(6, 1, -1) * mV)
166 assert_allclose(SG.x / 2.0, np.arange(3, 8) / 2.0)
167 assert_allclose(SG.y / 2, np.arange(6, 1, -1) * mV / 2)
168 assert_equal(SG.idx % 2, np.arange(3, 8, dtype=int) % 2)
169 assert_allclose(SG.x + 2, 2 + np.arange(3, 8))
170 assert_allclose(SG.y + 2 * mV, 2 * mV + np.arange(6, 1, -1) * mV)
171 assert_allclose(2 + SG.x, 2 + np.arange(3, 8))
172 assert_allclose(2 * mV + SG.y, 2 * mV + np.arange(6, 1, -1) * mV)
173 assert_allclose(SG.x - 2, np.arange(3, 8) - 2)
174 assert_allclose(SG.y - 2 * mV, np.arange(6, 1, -1) * mV - 2 * mV)
175 assert_allclose(2 - SG.x, 2 - np.arange(3, 8))
176 assert_allclose(2 * mV - SG.y, 2 * mV - np.arange(6, 1, -1) * mV)
177 assert_allclose(SG.x**2, np.arange(3, 8) ** 2)
178 assert_allclose(SG.y**2, (np.arange(6, 1, -1) * mV) ** 2)
179 assert_allclose(2**SG.x, 2 ** np.arange(3, 8))
180
181 # incorrect units
182 with pytest.raises(DimensionMismatchError):
183 SG.x + SG.y
184 with pytest.raises(DimensionMismatchError):
185 SG.x[:] + SG.y
186 with pytest.raises(DimensionMismatchError):
187 SG.x + SG.y[:]
188 with pytest.raises(DimensionMismatchError):
189 SG.x + 3 * mV
190 with pytest.raises(DimensionMismatchError):
191 3 * mV + SG.x
192 with pytest.raises(DimensionMismatchError):
193 SG.y + 3
194 with pytest.raises(DimensionMismatchError):
195 3 + SG.y
196 with pytest.raises(TypeError):
197 2**SG.y # raising to a power with units
198
199
200 @pytest.mark.standalone_compatible
201 def test_variableview_properties():
202 G = NeuronGroup(
203 10,
204 """
205 x : 1
206 y : volt
207 idx : integer
208 """,
209 )
210 # The below properties should not require access to the values
211 G.x = "rand()"
212 G.y = "rand()*mV"
213 G.idx = "int(rand()*10)"
214 SG = G[3:8]
215
216 assert have_same_dimensions(SG.x.unit, DIMENSIONLESS)
217 assert have_same_dimensions(SG.y.unit, volt)
218 assert have_same_dimensions(SG.idx.unit, DIMENSIONLESS)
219 # See github issue #1555
220 assert SG.x.shape == SG.y.shape == SG.idx.shape == (5,)
221 assert SG.x.ndim == SG.y.ndim == SG.idx.ndim == 1
222 assert SG.x.dtype == SG.y.dtype == prefs.core.default_float_dtype
223 assert SG.idx.dtype == np.int32
224
225
226 @pytest.mark.standalone_compatible
227 def test_state_monitor():
228 G = NeuronGroup(10, "v : volt")
229 G.v = np.arange(10) * volt
230 SG = G[5:]
231 mon_all = StateMonitor(SG, "v", record=True)
232 mon_0 = StateMonitor(SG, "v", record=0)
233 run(defaultclock.dt)
234
235 assert_allclose(mon_0[0].v, mon_all[0].v)
236 assert_allclose(mon_0[0].v, np.array([5]) * volt)
237 assert_allclose(mon_all.v.flatten(), np.arange(5, 10) * volt)
238
239 with pytest.raises(IndexError):
240 mon_all[5]
241
242
243 def test_shared_variable():
244 """Make sure that shared variables work with subgroups"""
245 G = NeuronGroup(10, "v : volt (shared)")
246 G.v = 1 * volt
247 SG = G[5:]
248 assert SG.v == 1 * volt
249
250
251 @pytest.mark.standalone_compatible
252 def test_synapse_creation():
253 G1 = NeuronGroup(10, "")
254 G2 = NeuronGroup(20, "")
255 SG1 = G1[:5]
256 SG2 = G2[10:]
257 S = Synapses(SG1, SG2)
258 S.connect(i=2, j=2) # Should correspond to (2, 12)
259 S.connect("i==2 and j==5") # Should correspond to (2, 15)
260
261 run(0 * ms) # for standalone
262
263 # Internally, the "real" neuron indices should be used
264 assert_equal(S._synaptic_pre[:], np.array([2, 2]))
265 assert_equal(S._synaptic_post[:], np.array([12, 15]))
266 # For the user, the subgroup-relative indices should be presented
267 assert_equal(S.i[:], np.array([2, 2]))
268 assert_equal(S.j[:], np.array([2, 5]))
269 # N_incoming and N_outgoing should also be correct
270 assert all(S.N_outgoing[2, :] == 2)
271 assert all(S.N_incoming[:, 2] == 1)
272 assert all(S.N_incoming[:, 5] == 1)
273
274
275 @pytest.mark.standalone_compatible
276 def test_synapse_creation_state_vars():
277 G1 = NeuronGroup(10, "v : 1")
278 G2 = NeuronGroup(20, "v : 1")
279 G1.v = "i"
280 G2.v = "10 + i"
281 SG1 = G1[:5]
282 SG2 = G2[10:]
283
284 # connect based on pre-/postsynaptic state variables
285 S2 = Synapses(SG1, SG2, "w:1")
286 S2.connect("v_pre > 2")
287
288 S3 = Synapses(SG1, SG2, "w:1")
289 S3.connect("v_post < 25")
290
291 S4 = Synapses(SG2, SG1, "w:1")
292 S4.connect("v_post > 2")
293
294 S5 = Synapses(SG2, SG1, "w:1")
295 S5.connect("v_pre < 25")
296
297 run(0 * ms) # for standalone
298
299 assert len(S2) == 2 * len(SG2), str(len(S2))
300 assert all(S2.v_pre[:] > 2)
301 assert len(S3) == 5 * len(SG1), f"{len(S3)} != {5 * len(SG1)} "
302 assert all(S3.v_post[:] < 25)
303
304 assert len(S4) == 2 * len(SG2), str(len(S4))
305 assert all(S4.v_post[:] > 2)
306 assert len(S5) == 5 * len(SG1), f"{len(53)} != {5 * len(SG1)} "
307 assert all(S5.v_pre[:] < 25)
308
309
310 @pytest.mark.standalone_compatible
311 def test_synapse_creation_generator():
312 G1 = NeuronGroup(10, "v:1")
313 G2 = NeuronGroup(20, "v:1")
314 G1.v = "i"
315 G2.v = "10 + i"
316 SG1 = G1[:5]
317 SG2 = G2[10:]
318 S = Synapses(SG1, SG2, "w:1")
319 S.connect(j="i*2 + k for k in range(2)") # diverging connections
320
321 # connect based on pre-/postsynaptic state variables
322 S2 = Synapses(SG1, SG2, "w:1")
323 S2.connect(j="k for k in range(N_post) if v_pre > 2")
324
325 S3 = Synapses(SG1, SG2, "w:1")
326 S3.connect(j="k for k in range(N_post) if v_post < 25")
327
328 S4 = Synapses(SG2, SG1, "w:1")
329 S4.connect(j="k for k in range(N_post) if v_post > 2")
330
331 S5 = Synapses(SG2, SG1, "w:1")
332 S5.connect(j="k for k in range(N_post) if v_pre < 25")
333
334 run(0 * ms) # for standalone
335
336 # Internally, the "real" neuron indices should be used
337 assert_equal(S._synaptic_pre[:], np.arange(5).repeat(2))
338 assert_equal(S._synaptic_post[:], np.arange(10) + 10)
339 # For the user, the subgroup-relative indices should be presented
340 assert_equal(S.i[:], np.arange(5).repeat(2))
341 assert_equal(S.j[:], np.arange(10))
342
343 # N_incoming and N_outgoing should also be correct
344 assert all(S.N_outgoing[:] == 2)
345 assert all(S.N_incoming[:] == 1)
346
347 assert len(S2) == 2 * len(SG2), str(len(S2))
348 assert all(S2.v_pre[:] > 2)
349 assert len(S3) == 5 * len(SG1), f"{len(S3)} != {5 * len(SG1)} "
350 assert all(S3.v_post[:] < 25)
351
352 assert len(S4) == 2 * len(SG2), str(len(S4))
353 assert all(S4.v_post[:] > 2)
354 assert len(S5) == 5 * len(SG1), f"{len(S5)} != {5 * len(SG1)} "
355 assert all(S5.v_pre[:] < 25)
356
357
358 @pytest.mark.standalone_compatible
359 def test_synapse_creation_generator_multiple_synapses():
360 G1 = NeuronGroup(10, "v:1")
361 G2 = NeuronGroup(20, "v:1")
362 G1.v = "i"
363 G2.v = "10 + i"
364 SG1 = G1[:5]
365 SG2 = G2[10:]
366 S1 = Synapses(SG1, SG2)
367 S1.connect(j="k for k in range(N_post)", n="i")
368
369 S2 = Synapses(SG1, SG2)
370 S2.connect(j="k for k in range(N_post)", n="j")
371
372 S3 = Synapses(SG2, SG1)
373 S3.connect(j="k for k in range(N_post)", n="i")
374
375 S4 = Synapses(SG2, SG1)
376 S4.connect(j="k for k in range(N_post)", n="j")
377
378 S5 = Synapses(SG1, SG2)
379 S5.connect(j="k for k in range(N_post)", n="i+j")
380
381 S6 = Synapses(SG2, SG1)
382 S6.connect(j="k for k in range(N_post)", n="i+j")
383
384 S7 = Synapses(SG1, SG2)
385 S7.connect(j="k for k in range(N_post)", n="int(v_pre>2)*2")
386
387 S8 = Synapses(SG2, SG1)
388 S8.connect(j="k for k in range(N_post)", n="int(v_post>2)*2")
389
390 S9 = Synapses(SG1, SG2)
391 S9.connect(j="k for k in range(N_post)", n="int(v_post>22)*2")
392
393 S10 = Synapses(SG2, SG1)
394 S10.connect(j="k for k in range(N_post)", n="int(v_pre>22)*2")
395
396 run(0 * ms) # for standalone
397
398 # straightforward loop instead of doing something clever...
399 for source in range(len(SG1)):
400 assert_equal(S1.j[source, :], np.arange(len(SG2)).repeat(source))
401 assert_equal(S2.j[source, :], np.arange(len(SG2)).repeat(np.arange(len(SG2))))
402 assert_equal(S3.i[:, source], np.arange(len(SG2)).repeat(np.arange(len(SG2))))
403 assert_equal(S4.i[:, source], np.arange(len(SG2)).repeat(source))
404 assert_equal(
405 S5.j[source, :], np.arange(len(SG2)).repeat(np.arange(len(SG2)) + source)
406 )
407 assert_equal(
408 S6.i[:, source], np.arange(len(SG2)).repeat(np.arange(len(SG2)) + source)
409 )
410 if source > 2:
411 assert_equal(S7.j[source, :], np.arange(len(SG2)).repeat(2))
412 assert_equal(S8.i[:, source], np.arange(len(SG2)).repeat(2))
413 else:
414 assert len(S7.j[source, :]) == 0
415 assert len(S8.i[:, source]) == 0
416 assert_equal(S9.j[source, :], np.arange(3, len(SG2)).repeat(2))
417 assert_equal(S10.i[:, source], np.arange(3, len(SG2)).repeat(2))
418
419
420 @pytest.mark.standalone_compatible
421 def test_synapse_creation_generator_complex_ranges():
422 G1 = NeuronGroup(10, "v:1")
423 G2 = NeuronGroup(20, "v:1")
424 G1.v = "i"
425 G2.v = "10 + i"
426 SG1 = G1[:5]
427 SG2 = G2[10:]
428 S = Synapses(SG1, SG2)
429 S.connect(j="i+k for k in range(N_post-i)") # Connect to all j>i
430
431 # connect based on pre-/postsynaptic state variables
432 S2 = Synapses(SG1, SG2)
433 S2.connect(j="k for k in range(N_post * int(v_pre > 2))")
434
435 # connect based on pre-/postsynaptic state variables
436 S3 = Synapses(SG2, SG1)
437 S3.connect(j="k for k in range(N_post * int(v_pre > 22))")
438
439 run(0 * ms) # for standalone
440
441 for syn_source in range(5):
442 # Internally, the "real" neuron indices should be used
443 assert_equal(
444 S._synaptic_post[syn_source, :],
445 10 + syn_source + np.arange(10 - syn_source),
446 )
447 # For the user, the subgroup-relative indices should be presented
448 assert_equal(S.j[syn_source, :], syn_source + np.arange(10 - syn_source))
449
450 assert len(S2) == 2 * len(SG2), str(len(S2))
451 assert all(S2.v_pre[:] > 2)
452 assert len(S3) == 7 * len(SG1), str(len(S3))
453 assert all(S3.v_pre[:] > 22)
454
455
456 @pytest.mark.standalone_compatible
457 def test_synapse_creation_generator_random():
458 G1 = NeuronGroup(10, "v:1")
459 G2 = NeuronGroup(20, "v:1")
460 G1.v = "i"
461 G2.v = "10 + i"
462 SG1 = G1[:5]
463 SG2 = G2[10:]
464
465 # connect based on pre-/postsynaptic state variables
466 S2 = Synapses(SG1, SG2)
467 S2.connect(j="k for k in sample(N_post, p=1.0*int(v_pre > 2))")
468
469 S3 = Synapses(SG2, SG1)
470 S3.connect(j="k for k in sample(N_post, p=1.0*int(v_pre > 22))")
471
472 run(0 * ms) # for standalone
473
474 assert len(S2) == 2 * len(SG2), str(len(S2))
475 assert all(S2.v_pre[:] > 2)
476 assert len(S3) == 7 * len(SG1), str(len(S3))
477 assert all(S3.v_pre[:] > 22)
478
479
480 def test_synapse_access():
481 G1 = NeuronGroup(10, "v:1")
482 G1.v = "i"
483 G2 = NeuronGroup(20, "v:1")
484 G2.v = "i"
485 SG1 = G1[:5]
486 SG2 = G2[10:]
487 S = Synapses(SG1, SG2, "w:1")
488 S.connect(True)
489 S.w["j == 0"] = 5
490 assert all(S.w["j==0"] == 5)
491 S.w[2, 2] = 7
492 assert all(S.w["i==2 and j==2"] == 7)
493 S.w = "2*j"
494 assert all(S.w[:, 1] == 2)
495
496 assert len(S.w[:, 10]) == 0
497 assert len(S.w["j==10"]) == 0
498
499 # Test referencing pre- and postsynaptic variables
500 assert_equal(S.w[2:, :], S.w["v_pre >= 2"])
501 assert_equal(S.w[:, :5], S.w["v_post < 15"])
502 S.w = "v_post"
503 assert_equal(S.w[:], S.j[:] + 10)
504 S.w = "v_post + v_pre"
505 assert_equal(S.w[:], S.j[:] + 10 + S.i[:])
506
507 # Test using subgroups as indices
508 assert len(S) == len(S.w[SG1, SG2])
509 assert_equal(S.w[SG1, 1], S.w[:, 1])
510 assert_equal(S.w[1, SG2], S.w[1, :])
511 assert len(S.w[SG1, 10]) == 0
512
513
514 def test_synapses_access_subgroups():
515 G1 = NeuronGroup(5, "x:1")
516 G2 = NeuronGroup(10, "y:1")
517 SG1 = G1[2:5]
518 SG2 = G2[4:9]
519 S = Synapses(G1, G2, "w:1")
520 S.connect()
521 S.w[SG1, SG2] = 1
522 assert_equal(S.w["(i>=2 and i<5) and (j>=4 and j<9)"], 1)
523 assert_equal(S.w["not ((i>=2 and i<5) and (j>=4 and j<9))"], 0)
524 S.w = 0
525 S.w[SG1, :] = 1
526 assert_equal(S.w["i>=2 and i<5"], 1)
527 assert_equal(S.w["not (i>=2 and i<5)"], 0)
528 S.w = 0
529 S.w[:, SG2] = 1
530 assert_equal(S.w["j>=4 and j<9"], 1)
531 assert_equal(S.w["not (j>=4 and j<9)"], 0)
532
533
534 @pytest.mark.codegen_independent
535 def test_synapses_access_subgroups_problematic():
536 G1 = NeuronGroup(5, "x:1")
537 G2 = NeuronGroup(10, "y:1")
538 SG1 = G1[2:5]
539 SG2 = G2[4:9]
540 S = Synapses(G1, G2, "w:1")
541 S.connect()
542
543 # Note that "j" is not ambiguous, because the equivalent in the target group
544 # is called "i" (this previously raised a warning)
545 tests = [
546 ((SG1, slice(None)), "i", 1),
547 ((SG1, slice(None)), "i + N_pre", 2),
548 ((SG1, slice(None)), "N_pre", 1),
549 ((slice(None), SG2), "j", 0),
550 ((slice(None), SG2), "N_post", 1),
551 ((slice(None), SG2), "N", 1),
552 ((SG1, SG2), "i", 1),
553 ((SG1, SG2), "i + j", 1),
554 ((SG1, SG2), "N_pre", 1),
555 ((SG1, SG2), "j", 0),
556 ((SG1, SG2), "N_post", 1),
557 ((SG1, SG2), "N", 1),
558 # These should not raise a warning
559 ((SG1, SG2), "w", 0),
560 ((SG1, SG2), "x_pre", 0),
561 ((SG1, SG2), "y_post", 0),
562 ((SG1, SG2), "y", 0),
563 ]
564 for item, value, n_warnings in tests:
565 with catch_logs() as l:
566 S.w.__setitem__(item, value)
567 assert len(l) == n_warnings, (
568 f"expected {int(n_warnings)}, got {len(l)} warnings"
569 )
570 assert all(
571 [entry[1].endswith("ambiguous_string_expression") for entry in l]
572 )
573
574
575 @pytest.mark.standalone_compatible
576 def test_subgroup_summed_variable():
577 # Check in particular that only neurons targeted are reset to 0 (see github issue #925)
578 source = NeuronGroup(1, "")
579 target = NeuronGroup(5, "Iin : 1")
580 target.Iin = 10
581 target1 = target[1:2]
582 target2 = target[3:]
583
584 syn1 = Synapses(source, target1, "Iin_post = 5 : 1 (summed)")
585 syn1.connect(True)
586 syn2 = Synapses(source, target2, "Iin_post = 1 : 1 (summed)")
587 syn2.connect(True)
588
589 run(2 * defaultclock.dt)
590
591 assert_array_equal(target.Iin, [10, 5, 10, 1, 1])
592
593
594 def test_subexpression_references():
595 """
596 Assure that subexpressions in targeted groups are handled correctly.
597 """
598 G = NeuronGroup(
599 10,
600 """
601 v : 1
602 v2 = 2*v : 1
603 """,
604 )
605 G.v = np.arange(10)
606 SG1 = G[:5]
607 SG2 = G[5:]
608
609 S1 = Synapses(
610 SG1,
611 SG2,
612 """
613 w : 1
614 u = v2_post + 1 : 1
615 x = v2_pre + 1 : 1
616 """,
617 )
618 S1.connect("i==(5-1-j)")
619 assert_equal(S1.i[:], np.arange(5))
620 assert_equal(S1.j[:], np.arange(5)[::-1])
621 assert_equal(S1.u[:], np.arange(10)[:-6:-1] * 2 + 1)
622 assert_equal(S1.x[:], np.arange(5) * 2 + 1)
623
624 S2 = Synapses(
625 G,
626 SG2,
627 """
628 w : 1
629 u = v2_post + 1 : 1
630 x = v2_pre + 1 : 1
631 """,
632 )
633 S2.connect("i==(5-1-j)")
634 assert_equal(S2.i[:], np.arange(5))
635 assert_equal(S2.j[:], np.arange(5)[::-1])
636 assert_equal(S2.u[:], np.arange(10)[:-6:-1] * 2 + 1)
637 assert_equal(S2.x[:], np.arange(5) * 2 + 1)
638
639 S3 = Synapses(
640 SG1,
641 G,
642 """
643 w : 1
644 u = v2_post + 1 : 1
645 x = v2_pre + 1 : 1
646 """,
647 )
648 S3.connect("i==(10-1-j)")
649 assert_equal(S3.i[:], np.arange(5))
650 assert_equal(S3.j[:], np.arange(10)[:-6:-1])
651 assert_equal(S3.u[:], np.arange(10)[:-6:-1] * 2 + 1)
652 assert_equal(S3.x[:], np.arange(5) * 2 + 1)
653
654
655 def test_subexpression_no_references():
656 """
657 Assure that subexpressions are handled correctly, even
658 when the subgroups are created on-the-fly.
659 """
660 G = NeuronGroup(
661 10,
662 """
663 v : 1
664 v2 = 2*v : 1
665 """,
666 )
667 G.v = np.arange(10)
668
669 assert_equal(G[5:].v2, np.arange(5, 10) * 2)
670
671 S1 = Synapses(
672 G[:5],
673 G[5:],
674 """
675 w : 1
676 u = v2_post + 1 : 1
677 x = v2_pre + 1 : 1
678 """,
679 )
680 S1.connect("i==(5-1-j)")
681 assert_equal(S1.i[:], np.arange(5))
682 assert_equal(S1.j[:], np.arange(5)[::-1])
683 assert_equal(S1.u[:], np.arange(10)[:-6:-1] * 2 + 1)
684 assert_equal(S1.x[:], np.arange(5) * 2 + 1)
685
686 S2 = Synapses(
687 G,
688 G[5:],
689 """
690 w : 1
691 u = v2_post + 1 : 1
692 x = v2_pre + 1 : 1
693 """,
694 )
695 S2.connect("i==(5-1-j)")
696 assert_equal(S2.i[:], np.arange(5))
697 assert_equal(S2.j[:], np.arange(5)[::-1])
698 assert_equal(S2.u[:], np.arange(10)[:-6:-1] * 2 + 1)
699 assert_equal(S2.x[:], np.arange(5) * 2 + 1)
700
701 S3 = Synapses(
702 G[:5],
703 G,
704 """
705 w : 1
706 u = v2_post + 1 : 1
707 x = v2_pre + 1 : 1
708 """,
709 )
710 S3.connect("i==(10-1-j)")
711 assert_equal(S3.i[:], np.arange(5))
712 assert_equal(S3.j[:], np.arange(10)[:-6:-1])
713 assert_equal(S3.u[:], np.arange(10)[:-6:-1] * 2 + 1)
714 assert_equal(S3.x[:], np.arange(5) * 2 + 1)
715
716
717 @pytest.mark.standalone_compatible
718 def test_synaptic_propagation():
719 G1 = NeuronGroup(10, "v:1", threshold="v>1", reset="v=0")
720 G1.v["i%2==1"] = 1.1 # odd numbers should spike
721 G2 = NeuronGroup(20, "v:1")
722 SG1 = G1[1:6]
723 SG2 = G2[10:]
724 S = Synapses(SG1, SG2, on_pre="v+=1")
725 S.connect("i==j")
726 run(defaultclock.dt + schedule_propagation_offset())
727 expected = np.zeros(len(G2))
728 # Neurons 1, 3, 5 spiked and are connected to 10, 12, 14
729 expected[[10, 12, 14]] = 1
730 assert_equal(np.asarray(G2.v).flatten(), expected)
731
732
733 @pytest.mark.standalone_compatible
734 def test_synaptic_propagation_2():
735 # This tests for the bug in github issue #461
736 source = NeuronGroup(100, "", threshold="True")
737 sub_source = source[99:]
738 target = NeuronGroup(1, "v:1")
739 syn = Synapses(sub_source, target, on_pre="v+=1")
740 syn.connect()
741 run(defaultclock.dt + schedule_propagation_offset())
742 assert target.v[0] == 1.0
743
744
745 @pytest.mark.standalone_compatible
746 def test_run_regularly():
747 # See github issue #922
748
749 group = NeuronGroup(10, "v: integer")
750 # Full group
751 group.run_regularly("v += 16")
752 # Subgroup with explicit reference
753 subgroup = group[:2]
754 subgroup.run_regularly("v += 8")
755 # Subgroup with explicit reference and reference for run_regularly operation
756 subgroup2 = group[2:4]
757 updater = subgroup2.run_regularly("v += 4")
758 # Subgroup without reference
759 group[4:6].run_regularly("v += 2")
760 # Subgroup without reference, with reference for run_regularly operation
761 updater2 = group[6:8].run_regularly("v += 1")
762
763 run(defaultclock.dt)
764 assert_array_equal(group.v, [24, 24, 20, 20, 18, 18, 17, 17, 16, 16])
765
766
767 @pytest.mark.standalone_compatible
768 def test_spike_monitor():
769 G = NeuronGroup(10, "v:1", threshold="v>1", reset="v=0")
770 G.v[0] = 1.1
771 G.v[2] = 1.1
772 G.v[5] = 1.1
773 SG = G[3:]
774 SG2 = G[:3]
775 s_mon = SpikeMonitor(G)
776 sub_s_mon = SpikeMonitor(SG)
777 sub_s_mon2 = SpikeMonitor(SG2)
778 run(defaultclock.dt)
779 assert_equal(s_mon.i, np.array([0, 2, 5]))
780 assert_equal(s_mon.t_, np.zeros(3))
781 assert_equal(sub_s_mon.i, np.array([2]))
782 assert_equal(sub_s_mon.t_, np.zeros(1))
783 assert_equal(sub_s_mon2.i, np.array([0, 2]))
784 assert_equal(sub_s_mon2.t_, np.zeros(2))
785 expected = np.zeros(10, dtype=int)
786 expected[[0, 2, 5]] = 1
787 assert_equal(s_mon.count, expected)
788 expected = np.zeros(7, dtype=int)
789 expected[[2]] = 1
790 assert_equal(sub_s_mon.count, expected)
791 assert_equal(sub_s_mon2.count, np.array([1, 0, 1]))
792
793
794 @pytest.mark.codegen_independent
795 def test_wrong_indexing():
796 G = NeuronGroup(10, "v:1")
797 with pytest.raises(TypeError):
798 G["string"]
799
800 with pytest.raises(IndexError):
801 G[10]
802 with pytest.raises(IndexError):
803 G[10:]
804 with pytest.raises(IndexError):
805 G[::2]
806 with pytest.raises(IndexError):
807 G[3:2]
808 with pytest.raises(IndexError):
809 G[[5, 4, 3]]
810 with pytest.raises(IndexError):
811 G[[2, 4, 6]]
812 with pytest.raises(IndexError):
813 G[[-1, 0, 1]]
814 with pytest.raises(IndexError):
815 G[[9, 10, 11]]
816 with pytest.raises(IndexError):
817 G[[9, 10]]
818 with pytest.raises(IndexError):
819 G[[10, 11]]
820 with pytest.raises(TypeError):
821 G[[2.5, 3.5, 4.5]]
822
823
824 @pytest.mark.codegen_independent
825 def test_alternative_indexing():
826 G = NeuronGroup(10, "v : integer")
827 G.v = "i"
828 assert_equal(G[-3:].v, np.array([7, 8, 9]))
829 assert_equal(G[3].v, np.array([3]))
830 assert_equal(G[[3, 4, 5]].v, np.array([3, 4, 5]))
831
832
833 def test_no_reference_1():
834 """
835 Using subgroups without keeping an explicit reference. Basic access.
836 """
837 G = NeuronGroup(10, "v:1")
838 G.v = np.arange(10)
839 assert_equal(G[:5].v[:], G.v[:5])
840
841
842 @pytest.mark.standalone_compatible
843 def test_no_reference_2():
844 """
845 Using subgroups without keeping an explicit reference. Monitors
846 """
847 G = NeuronGroup(2, "v:1", threshold="v>1", reset="v=0")
848 G.v = [0, 1.1]
849 state_mon = StateMonitor(G[:1], "v", record=True)
850 spike_mon = SpikeMonitor(G[1:])
851 rate_mon = PopulationRateMonitor(G[:2])
852 run(2 * defaultclock.dt)
853 assert_equal(state_mon[0].v[:], np.zeros(2))
854 assert_equal(spike_mon.i[:], np.array([0]))
855 assert_equal(spike_mon.t[:], np.array([0]) * second)
856 assert_equal(rate_mon.rate[:], np.array([0.5, 0]) / defaultclock.dt)
857
858
859 @pytest.mark.standalone_compatible
860 def test_no_reference_3():
861 """
862 Using subgroups without keeping an explicit reference. Monitors
863 """
864 G = NeuronGroup(2, "v:1", threshold="v>1", reset="v=0")
865 G.v = [1.1, 0]
866 S = Synapses(G[:1], G[1:], on_pre="v+=1")
867 S.connect()
868 run(defaultclock.dt + schedule_propagation_offset())
869 assert_equal(G.v[:], np.array([0, 1]))
870
871
872 @pytest.mark.standalone_compatible
873 def test_no_reference_4():
874 """
875 Using subgroups without keeping an explicit reference. Synapses
876 """
877 G1 = NeuronGroup(10, "v:1", threshold="v>1", reset="v=0")
878 G1.v["i%2==1"] = 1.1 # odd numbers should spike
879 G2 = NeuronGroup(20, "v:1")
880 S = Synapses(G1[1:6], G2[10:], on_pre="v+=1")
881 S.connect("i==j")
882 run(defaultclock.dt + schedule_propagation_offset())
883 expected = np.zeros(len(G2))
884 # Neurons 1, 3, 5 spiked and are connected to 10, 12, 14
885 expected[[10, 12, 14]] = 1
886 assert_equal(np.asarray(G2.v).flatten(), expected)
887
888
889 def test_recursive_subgroup():
890 """
891 Create a subgroup of a subgroup
892 """
893 G = NeuronGroup(10, "v : 1")
894 G.v = "i"
895 SG = G[3:8]
896 SG2 = SG[2:4]
897 assert_equal(SG2.v[:], np.array([5, 6]))
898 assert_equal(SG2.v[:], SG.v[2:4])
899 assert SG2.source.name == G.name
900
901
902 if __name__ == "__main__":
903 test_str_repr()
904 test_state_variables()
905 test_state_variables_simple()
906 test_state_variables_string_indices()
907 test_state_variables_group_as_index()
908 test_state_variables_group_as_index_problematic()
909 test_state_monitor()
910 test_shared_variable()
911 test_synapse_creation()
912 test_synapse_creation_state_vars()
913 test_synapse_creation_generator()
914 test_synapse_creation_generator_complex_ranges()
915 test_synapse_creation_generator_random()
916 test_synapse_creation_generator_multiple_synapses()
917 test_synapse_access()
918 test_synapses_access_subgroups()
919 test_synapses_access_subgroups_problematic()
920 test_subgroup_summed_variable()
921 test_subexpression_references()
922 test_subexpression_no_references()
923 test_synaptic_propagation()
924 test_synaptic_propagation_2()
925 test_run_regularly()
926 test_spike_monitor()
927 test_wrong_indexing()
928 test_no_reference_1()
929 test_no_reference_2()
930 test_no_reference_3()
931 test_no_reference_4()
932 test_recursive_subgroup()