File: test_refractory.py

package info (click to toggle)
brian 2.9.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,872 kB
  • sloc: python: 51,820; cpp: 2,033; makefile: 108; sh: 72
file content (386 lines) | stat: -rw-r--r-- 11,864 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
from collections import Counter

import pytest
from numpy.testing import assert_equal

from brian2 import *
from brian2.core.functions import timestep
from brian2.devices.device import reinit_and_delete
from brian2.equations.refractory import add_refractoriness
from brian2.tests.utils import assert_allclose, exc_isinstance
from brian2.utils.logger import catch_logs


@pytest.mark.codegen_independent
def test_add_refractoriness():
    eqs = Equations(
        """
        dv/dt = -x*v/second : volt (unless refractory)
        dw/dt = -w/second : amp
        x : 1
        """
    )
    # only make sure it does not throw an error
    eqs = add_refractoriness(eqs)
    # Check that the parameters were added
    assert "not_refractory" in eqs
    assert "lastspike" in eqs


@pytest.mark.codegen_independent
def test_missing_refractory_warning():
    # Forgotten refractory argument
    with catch_logs() as l:
        group = NeuronGroup(
            1,
            "dv/dt = -v / (10*ms) : 1 (unless refractory)",
            threshold="v > 1",
            reset="v = 0",
        )
    assert len(l) == 1
    assert l[0][0] == "WARNING" and l[0][1].endswith("no_refractory")


@pytest.mark.standalone_compatible
def test_refractoriness_basic():
    G = NeuronGroup(
        1,
        """
        dv/dt = 99.999*Hz : 1 (unless refractory)
        dw/dt = 99.999*Hz : 1
        """,
        threshold="v>1",
        reset="v=0;w=0",
        refractory=5 * ms,
    )
    # It should take 10ms to reach the threshold, then v should stay at 0
    # for 5ms, while w continues to increase
    mon = StateMonitor(G, ["v", "w"], record=True, when="end")
    run(20 * ms)
    # No difference before the spike
    assert_allclose(
        mon[0].v[: timestep(10 * ms, defaultclock.dt)],
        mon[0].w[: timestep(10 * ms, defaultclock.dt)],
    )
    # v is not updated during refractoriness
    in_refractoriness = mon[0].v[
        timestep(10 * ms, defaultclock.dt) : timestep(15 * ms, defaultclock.dt)
    ]
    assert_equal(in_refractoriness, np.zeros_like(in_refractoriness))
    # w should evolve as before
    assert_allclose(
        mon[0].w[: timestep(5 * ms, defaultclock.dt)],
        mon[0].w[
            timestep(10 * ms, defaultclock.dt)
            + 1 : timestep(15 * ms, defaultclock.dt)
            + 1
        ],
    )
    assert np.all(
        mon[0].w[
            timestep(10 * ms, defaultclock.dt)
            + 1 : timestep(15 * ms, defaultclock.dt)
            + 1
        ]
        > 0
    )
    # After refractoriness, v should increase again
    assert np.all(
        mon[0].v[
            timestep(15 * ms, defaultclock.dt) : timestep(20 * ms, defaultclock.dt)
        ]
        > 0
    )


@pytest.mark.standalone_compatible
@pytest.mark.parametrize(
    "ref_time",
    [
        "5*ms",
        "(t-lastspike + 1e-3*dt) < 5*ms",
        "time_since_spike + 1e-3*dt < 5*ms",
        "ref_subexpression",
        "(t-lastspike + 1e-3*dt) < ref",
        "ref",
        "ref_no_unit*ms",
    ],
)
def test_refractoriness_variables(ref_time):
    # Try a string evaluating to a quantity, and an explicit boolean
    # condition -- all should do the same thing
    G = NeuronGroup(
        1,
        """
        dv/dt = 99.999*Hz : 1 (unless refractory)
        dw/dt = 99.999*Hz : 1
        ref : second
        ref_no_unit : 1
        time_since_spike = (t - lastspike) +1e-3*dt : second
        ref_subexpression = (t - lastspike + 1e-3*dt) < ref : boolean
        """,
        threshold="v>1",
        reset="v=0;w=0",
        refractory=ref_time,
        dtype={
            "ref": defaultclock.variables["t"].dtype,
            "ref_no_unit": defaultclock.variables["t"].dtype,
            "lastspike": defaultclock.variables["t"].dtype,
            "time_since_spike": defaultclock.variables["t"].dtype,
        },
    )
    G.ref = 5 * ms
    G.ref_no_unit = 5
    # It should take 10ms to reach the threshold, then v should stay at 0
    # for 5ms, while w continues to increase
    mon = StateMonitor(G, ["v", "w"], record=True, when="end")
    run(20 * ms)
    try:
        # No difference before the spike
        assert_allclose(
            mon[0].v[: timestep(10 * ms, defaultclock.dt)],
            mon[0].w[: timestep(10 * ms, defaultclock.dt)],
        )
        # v is not updated during refractoriness
        in_refractoriness = mon[0].v[
            timestep(10 * ms, defaultclock.dt) : timestep(15 * ms, defaultclock.dt)
        ]
        assert_allclose(in_refractoriness, np.zeros_like(in_refractoriness))
        # w should evolve as before
        assert_allclose(
            mon[0].w[: timestep(5 * ms, defaultclock.dt)],
            mon[0].w[
                timestep(10 * ms, defaultclock.dt)
                + 1 : timestep(15 * ms, defaultclock.dt)
                + 1
            ],
        )
        assert np.all(
            mon[0].w[
                timestep(10 * ms, defaultclock.dt)
                + 1 : timestep(15 * ms, defaultclock.dt)
                + 1
            ]
            > 0
        )
        # After refractoriness, v should increase again
        assert np.all(
            mon[0].v[
                timestep(15 * ms, defaultclock.dt) : timestep(20 * ms, defaultclock.dt)
            ]
            > 0
        )
    except AssertionError as ex:
        raise
        raise AssertionError(
            f"Assertion failed when using {ref_time!r} as refractory argument:\n{ex}"
        )


@pytest.mark.standalone_compatible
def test_refractoriness_threshold_basic():
    G = NeuronGroup(
        1,
        """
        dv/dt = 199.99*Hz : 1
        """,
        threshold="v > 1",
        reset="v=0",
        refractory=10 * ms,
    )
    # The neuron should spike after 5ms but then not spike for the next
    # 10ms. The state variable should continue to integrate so there should
    # be a spike after 15ms
    spike_mon = SpikeMonitor(G)
    run(16 * ms)
    assert_allclose(spike_mon.t, [5, 15] * ms)


@pytest.mark.standalone_compatible
def test_refractoriness_repeated():
    # Create a group that spikes whenever it can
    group = NeuronGroup(1, "", threshold="True", refractory=10 * defaultclock.dt)
    spike_mon = SpikeMonitor(group)
    run(10000 * defaultclock.dt)
    assert spike_mon.t[0] == 0 * ms
    assert_allclose(np.diff(spike_mon.t), 10 * defaultclock.dt)


@pytest.mark.standalone_compatible
def test_refractoriness_repeated_legacy():
    if prefs.core.default_float_dtype == np.float32:
        pytest.skip(
            "Not testing legacy refractory mechanism with single precision floats."
        )
    # Switch on behaviour from versions <= 2.1.2
    prefs.legacy.refractory_timing = True
    # Create a group that spikes whenever it can
    group = NeuronGroup(1, "", threshold="True", refractory=10 * defaultclock.dt)
    spike_mon = SpikeMonitor(group)
    run(10000 * defaultclock.dt)
    assert spike_mon.t[0] == 0 * ms

    # Empirical values from running with earlier Brian versions
    assert_allclose(
        np.diff(spike_mon.t)[:10], [1.1, 1, 1.1, 1, 1.1, 1.1, 1.1, 1.1, 1, 1.1] * ms
    )
    steps = Counter(np.diff(np.int_(np.round(spike_mon.t / defaultclock.dt))))
    assert len(steps) == 2 and steps[10] == 899 and steps[11] == 91
    prefs.legacy.refractory_timing = False


@pytest.mark.standalone_compatible
@pytest.mark.parametrize(
    "ref_time",
    [
        10 * ms,
        "10*ms",
        "timestep(t-lastspike, dt) < timestep(10*ms, dt)",
        "timestep(t-lastspike, dt) < timestep(ref, dt)",
        "ref",
        "ref_no_unit*ms",
    ],
)
def test_refractoriness_threshold(ref_time):
    # Try a quantity, a string evaluating to a quantity, and an explicit boolean
    # condition -- all should do the same thing
    G = NeuronGroup(
        1,
        """
        dv/dt = 199.999*Hz : 1
        ref : second
        ref_no_unit : 1
        """,
        threshold="v > 1",
        reset="v=0",
        refractory=ref_time,
        dtype={
            "ref": defaultclock.variables["t"].dtype,
            "ref_no_unit": defaultclock.variables["t"].dtype,
        },
    )
    G.ref = 10 * ms
    G.ref_no_unit = 10
    # The neuron should spike after 5ms but then not spike for the next
    # 10ms. The state variable should continue to integrate so there should
    # be a spike after 15ms
    spike_mon = SpikeMonitor(G)
    run(16 * ms)
    assert_allclose(spike_mon.t, [5, 15] * ms)


@pytest.mark.codegen_independent
def test_refractoriness_types():
    # make sure that using a wrong type of refractoriness does not work
    group = NeuronGroup(1, "", refractory="3*Hz")
    with pytest.raises(BrianObjectException) as exc:
        Network(group).run(0 * ms)
    assert exc_isinstance(exc, TypeError)
    group = NeuronGroup(1, "ref: Hz", refractory="ref")
    with pytest.raises(BrianObjectException) as exc:
        Network(group).run(0 * ms)
    assert exc_isinstance(exc, TypeError)
    group = NeuronGroup(1, "", refractory="3")
    with pytest.raises(BrianObjectException) as exc:
        Network(group).run(0 * ms)
    assert exc_isinstance(exc, TypeError)
    group = NeuronGroup(1, "ref: 1", refractory="ref")
    with pytest.raises(BrianObjectException) as exc:
        Network(group).run(0 * ms)
    assert exc_isinstance(exc, TypeError)


@pytest.mark.codegen_independent
def test_conditional_write_set():
    """
    Test that the conditional_write attribute is set correctly
    """
    G = NeuronGroup(
        1,
        """
        dv/dt = 10*Hz : 1 (unless refractory)
        dw/dt = 10*Hz : 1
        """,
        refractory=2 * ms,
    )
    assert G.variables["v"].conditional_write is G.variables["not_refractory"]
    assert G.variables["w"].conditional_write is None


@pytest.mark.standalone_compatible
def test_conditional_write_behaviour():
    H = NeuronGroup(1, "v:1", threshold="v>-1")

    tau = 1 * ms
    eqs = """
    dv/dt = (2-v)/tau : 1 (unless refractory)
    dx/dt = 0/tau : 1 (unless refractory)
    dy/dt = 0/tau : 1
    """
    reset = """
    v = 0
    x -= 0.05
    y -= 0.05
    """
    G = NeuronGroup(1, eqs, threshold="v>1", reset=reset, refractory=1 * ms)

    Sx = Synapses(H, G, on_pre="x += dt*100*Hz")
    Sx.connect(True)

    Sy = Synapses(H, G, on_pre="y += dt*100*Hz")
    Sy.connect(True)

    M = StateMonitor(G, variables=True, record=True)

    run(10 * ms)

    assert G.x[0] < 0.2
    assert G.y[0] > 0.2
    assert G.v[0] < 1.1


@pytest.mark.standalone_compatible
def test_conditional_write_automatic_and_manual():
    source = NeuronGroup(1, "", threshold="True")  # spiking all the time
    target = NeuronGroup(
        2,
        """
        dv/dt = 0/ms : 1 (unless refractory)
        dw/dt = 0/ms : 1
        """,
        threshold="t == 0*ms",
        refractory="False",
    )  # only refractory for the first time step
    # Cell is spiking/refractory only in the first time step
    syn = Synapses(
        source,
        target,
        on_pre="""
        v += 1
        w += 1 * int(not_refractory_post)
        """,
    )
    syn.connect()
    mon = StateMonitor(target, ["v", "w"], record=True, when="end")
    run(2 * defaultclock.dt)

    # Synapse should not have been effective in the first time step
    assert_allclose(mon.v[:, 0], 0)
    assert_allclose(mon.v[:, 1], 1)
    assert_allclose(mon.w[:, 0], 0)
    assert_allclose(mon.w[:, 1], 1)


if __name__ == "__main__":
    test_add_refractoriness()
    test_missing_refractory_warning()
    test_refractoriness_basic()
    test_refractoriness_variables()
    test_refractoriness_threshold()
    test_refractoriness_threshold_basic()
    test_refractoriness_repeated()
    test_refractoriness_repeated_legacy()
    test_refractoriness_types()
    test_conditional_write_set()
    test_conditional_write_behaviour()
    test_conditional_write_automatic_and_manual()