Multiple calls to (stateful) user defined functions


I have the following

#!/usr/bin/env python3

from brian2 import *

@check_units(x=1, result=1)
def heaviside(x):
    return (x > 0).astype(int)

neuron = NeuronGroup(1, "dv/dt = -v/(1*ms) : 1", method='euler')
ssg = SpikeGeneratorGroup(1, [0], [0*ms])

syn = Synapses(ssg, neuron, "dx/dt = 3/ms*heaviside(x - 1) - 4/ms*heaviside(-(x+2)) : 1")


Which fails with

NotImplementedError: The expression "3/ms*heaviside(x - 1) - 4/ms*heaviside(-(x+2))" contains more than one call of heaviside, this is currently not supported since heaviside is a stateful function and its multiple calls might be treated incorrectly (e.g."rand() - rand()" could be  simplified to "0.0").

How do I tell Brian2 that my function is not stateful?



Hmm, that’s odd, user-defined functions should default to being stateless I think. I’ll have to check this again, but in the meantime adding the following (somewhat redundant) statement after your function definition should do the trick:

heaviside = Function(heaviside)

Also note that you don’t really need to define your own heaviside function, you can use e.g. int(x > 1) directly in the equations (which will then work with C++ etc. automatically).

1 Like