| 1 |
Functions |
| 2 |
========= |
| 3 |
|
| 4 |
.. contents:: |
| 5 |
:local: |
| 6 |
:depth: 2 |
| 7 |
|
| 8 |
All equations, expressions and statements in Brian can make use of mathematical |
| 9 |
functions. However, functions have to be prepared for use with Brian for two |
| 10 |
reasons: 1) Brian is strict about checking the consistency of units, therefore |
| 11 |
every function has to specify how it deals with units; 2) functions need to |
| 12 |
be implemented differently for different code generation targets. |
| 13 |
|
| 14 |
Brian provides a number of default functions that are already prepared for use |
| 15 |
with numpy and C++ and also provides a mechanism for preparing new functions |
| 16 |
for use (see below). |
| 17 |
|
| 18 |
.. _default_functions: |
| 19 |
|
| 20 |
Default functions |
| 21 |
----------------- |
| 22 |
The following functions (stored in the `DEFAULT_FUNCTIONS` dictionary) are |
| 23 |
ready for use: |
| 24 |
|
| 25 |
* Random numbers: ``rand`` (random numbers drawn from a uniform distribution |
| 26 |
between 0 and 1), ``randn`` (random numbers drawn from the standard normal |
| 27 |
distribution, i.e. with mean 0 and standard deviation 1), |
| 28 |
and ``poisson`` (discrete random numbers from a Poisson distribution with rate |
| 29 |
parameter :math:`\lambda`) |
| 30 |
* Elementary functions: ``sqrt``, ``exp``, ``log``, ``log10``, ``abs``, ``sign`` |
| 31 |
* Trigonometric functions: ``sin``, ``cos``, ``tan``, ``sinh``, ``cosh``, |
| 32 |
``tanh``, ``arcsin``, ``arccos``, ``arctan`` |
| 33 |
* Functions for improved numerical accuracy: ``expm1`` (calculates ``exp(x) - 1``, more accurate |
| 34 |
for ``x`` close to 0), ``log1p`` (calculates ``log(1 + x)``, more accurate for ``x`` close to 0), |
| 35 |
and ``exprel`` (calculates ``(exp(x) - 1)/x``, more accurate for ``x`` close to 0, and returning |
| 36 |
1.0 instead of ``NaN`` for ``x == 0`` |
| 37 |
* General utility functions: ``clip``, ``floor``, ``ceil`` |
| 38 |
|
| 39 |
Brian also provides a special purpose function ``int``, which can be used to |
| 40 |
convert an expression or variable into an integer value. This is especially |
| 41 |
useful for boolean values (which will be converted into 0 or 1), for example to |
| 42 |
have a conditional evaluation as part of an equation or statement which |
| 43 |
sometimes allows to circumvent the lack of an ``if`` statement. For |
| 44 |
example, the following reset statement resets the variable `v` to either `v_r1` |
| 45 |
or `v_r2`, depending on the value of `w`: |
| 46 |
``'v = v_r1 * int(w <= 0.5) + v_r2 * int(w > 0.5)'`` |
| 47 |
|
| 48 |
Finally, the function `~brian2.core.functions.timestep` is a function that takes |
| 49 |
a time and the length of a time step as an input and returns an integer |
| 50 |
corresponding to the respective time step. The advantage of using this function |
| 51 |
over a simple division is that it slightly shifts the time before dividing to |
| 52 |
avoid floating point issues. This function is used as part of the |
| 53 |
:doc:`../user/refractoriness` mechanism. |
| 54 |
|
| 55 |
.. _user_functions: |
| 56 |
|
| 57 |
User-provided functions |
| 58 |
----------------------- |
| 59 |
|
| 60 |
Python code generation |
| 61 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 62 |
If a function is only used in contexts that use Python code generation, |
| 63 |
preparing a function for use with Brian only means specifying its units. The |
| 64 |
simplest way to do this is to use the `check_units` decorator:: |
| 65 |
|
| 66 |
@check_units(x1=meter, y1=meter, x2=meter, y2=meter, result=meter) |
| 67 |
def distance(x1, y1, x2, y2): |
| 68 |
return sqrt((x1 - x2)**2 + (y1 - y2)**2) |
| 69 |
|
| 70 |
Another option is to wrap the function in a `Function` object:: |
| 71 |
|
| 72 |
def distance(x1, y1, x2, y2): |
| 73 |
return sqrt((x1 - x2)**2 + (y1 - y2)**2) |
| 74 |
# wrap the distance function |
| 75 |
distance = Function(distance, arg_units=[meter, meter, meter, meter], |
| 76 |
return_unit=meter) |
| 77 |
|
| 78 |
The use of Brian's unit system has the benefit of checking the consistency of |
| 79 |
units for every operation but at the expense of performance. |
| 80 |
Consider the following function, for example:: |
| 81 |
|
| 82 |
@check_units(I=amp, result=Hz) |
| 83 |
def piecewise_linear(I): |
| 84 |
return clip((I-1*nA) * 50*Hz/nA, 0*Hz, 100*Hz) |
| 85 |
|
| 86 |
When Brian runs a simulation, the state variables are stored and passed around |
| 87 |
without units for performance reasons. If the above function is used, however, |
| 88 |
Brian adds units to its input argument so that the operations inside the |
| 89 |
function do not fail with dimension mismatches. Accordingly, units are removed |
| 90 |
from the return value so that the function output can be used with the rest |
| 91 |
of the code. For better performance, Brian can alter the namespace of the |
| 92 |
function when it is executed as part of the simulation and remove all the |
| 93 |
units, then pass values without units to the function. In the above example, |
| 94 |
this means making the symbol ``nA`` refer to ``1e-9`` and ``Hz`` to ``1``. To |
| 95 |
use this mechanism, add the decorator `implementation` with the |
| 96 |
``discard_units`` keyword:: |
| 97 |
|
| 98 |
@implementation('numpy', discard_units=True) |
| 99 |
@check_units(I=amp, result=Hz) |
| 100 |
def piecewise_linear(I): |
| 101 |
return clip((I-1*nA) * 50*Hz/nA, 0*Hz, 100*Hz) |
| 102 |
|
| 103 |
Note that the use of the function *outside of simulation runs* is not affected, |
| 104 |
i.e. using ``piecewise_linear`` still requires a current in Ampere and returns |
| 105 |
a rate in Hertz. The ``discard_units`` mechanism does not work in all cases, |
| 106 |
e.g. it does not work if the function refers to units as ``brian2.nA`` instead |
| 107 |
of ``nA``, if it uses imports inside the function (e.g. |
| 108 |
``from brian2 import nA``), etc. The ``discard_units`` can also be switched on |
| 109 |
for all functions without having to use the `implementation` decorator by |
| 110 |
setting the `codegen.runtime.numpy.discard_units` preference. |
| 111 |
|
| 112 |
Other code generation targets |
| 113 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 114 |
To make a function available for other code generation targets (e.g. C++), |
| 115 |
implementations for these targets have to be added. This can be achieved using |
| 116 |
the `implementation` decorator. The form of the code (e.g. a simple string or |
| 117 |
a dictionary of strings) necessary is target-dependent, for C++ both options |
| 118 |
are allowed, a simple string will be interpreted as filling the |
| 119 |
``'support_code'`` block. Note that ``'cpp'`` is used |
| 120 |
to provide C++ implementations. An |
| 121 |
implementation for the C++ target could look like this:: |
| 122 |
|
| 123 |
@implementation('cpp', ''' |
| 124 |
double piecewise_linear(double I) { |
| 125 |
if (I < 1e-9) |
| 126 |
return 0; |
| 127 |
if (I > 3e-9) |
| 128 |
return 100; |
| 129 |
return (I/1e-9 - 1) * 50; |
| 130 |
} |
| 131 |
''') |
| 132 |
@check_units(I=amp, result=Hz) |
| 133 |
def piecewise_linear(I): |
| 134 |
return clip((I-1*nA) * 50*Hz/nA, 0*Hz, 100*Hz) |
| 135 |
|
| 136 |
Alternatively, `FunctionImplementation` objects can be added to the `Function` |
| 137 |
object. |
| 138 |
|
| 139 |
The same sort of approach as for C++ works for Cython using the |
| 140 |
``'cython'`` target. The example above would look like this:: |
| 141 |
|
| 142 |
@implementation('cython', ''' |
| 143 |
cdef double piecewise_linear(double I): |
| 144 |
if I<1e-9: |
| 145 |
return 0.0 |
| 146 |
elif I>3e-9: |
| 147 |
return 100.0 |
| 148 |
return (I/1e-9-1)*50 |
| 149 |
''') |
| 150 |
@check_units(I=amp, result=Hz) |
| 151 |
def piecewise_linear(I): |
| 152 |
return clip((I-1*nA) * 50*Hz/nA, 0*Hz, 100*Hz) |
| 153 |
|
| 154 |
Dependencies between functions |
| 155 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 156 |
The code generation mechanism for user-defined functions only adds the source |
| 157 |
code for a function when it is necessary. If a user-defined function refers to |
| 158 |
another function in its source code, it therefore has to explicitly state this |
| 159 |
dependency so that the code of the dependency is added as well:: |
| 160 |
|
| 161 |
@implementation('cpp',''' |
| 162 |
double rectified_linear(double x) |
| 163 |
{ |
| 164 |
return clip(x, 0, INFINITY); |
| 165 |
}''', |
| 166 |
dependencies={'clip': DEFAULT_FUNCTIONS['clip']} |
| 167 |
) |
| 168 |
@check_units(x=1, result=1) |
| 169 |
def rectified_linear(x): |
| 170 |
return np.clip(x, 0, np.inf) |
| 171 |
|
| 172 |
.. note:: |
| 173 |
The dependency mechanism is unnecessary for the ``numpy`` code generation |
| 174 |
target, since functions are defined as actual Python functions and not as |
| 175 |
code given in a string. |
| 176 |
|
| 177 |
Additional compiler arguments |
| 178 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 179 |
If the code for a function needs additional compiler options to work, e.g. to |
| 180 |
link to an external library, these options can be provided as keyword |
| 181 |
arguments to the ``@implementation`` decorator. E.g. to link C++ code to the |
| 182 |
``foo`` library which is stored in the directory ``/usr/local/foo``, use:: |
| 183 |
|
| 184 |
@implementation('cpp', '...', |
| 185 |
libraries=['foo'], library_dirs=['/usr/local/foo']) |
| 186 |
|
| 187 |
These arguments can also be used to refer to external source files, see |
| 188 |
:ref:`below <external_sources>`. Equivalent arguments can also be set as global |
| 189 |
:doc:`preferences` in which case they apply to all code and not only to code |
| 190 |
referring to the respective function. Note that in C++ standalone mode, all |
| 191 |
files are compiled together, and therefore the additional compiler arguments |
| 192 |
provided to functions are always combined with the preferences into a common |
| 193 |
set of settings that is applied to all code. |
| 194 |
|
| 195 |
The list of currently supported additional arguments (for further explications, |
| 196 |
see the respective :doc:`preferences` and the Python documentation of the |
| 197 |
`distutils.core.Extension` class): |
| 198 |
|
| 199 |
======================== ============== ====== |
| 200 |
keyword C++ standalone Cython |
| 201 |
======================== ============== ====== |
| 202 |
``headers`` ✓ ❌ |
| 203 |
``sources`` ✓ ✓ |
| 204 |
``define_macros`` ✓ ❌ |
| 205 |
``libraries`` ✓ ✓ |
| 206 |
``include_dirs`` ✓ ✓ |
| 207 |
``library_dirs`` ✓ ✓ |
| 208 |
``runtime_library_dirs`` ✓ ✓ |
| 209 |
======================== ============== ====== |
| 210 |
|
| 211 |
Arrays vs. scalar values in user-provided functions |
| 212 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 213 |
Equations, expressions and abstract code statements are always implicitly |
| 214 |
referring to all the neurons in a `NeuronGroup`, all the synapses in a |
| 215 |
`Synapses` object, etc. Therefore, function calls also apply to more than a |
| 216 |
single value. The way in which this is handled differs between code generation |
| 217 |
targets that support vectorized expressions (e.g. the ``numpy`` target) and |
| 218 |
targets that don't (e.g. the ``cpp_standalone`` mode). |
| 219 |
If the code generation target supports vectorized expressions, it will receive |
| 220 |
an array of values. For example, in the ``piecewise_linear`` example above, the |
| 221 |
argument ``I`` will be an array of values and the function returns an array of |
| 222 |
values. For code generation without support for vectorized expressions, all |
| 223 |
code will be executed in a loop (over neurons, over synapses, ...), the function |
| 224 |
will therefore be called several times with a single value each time. |
| 225 |
|
| 226 |
In both cases, the function will only receive the "relevant" values, meaning |
| 227 |
that if for example a function is evaluated as part of a reset statement, it |
| 228 |
will only receive values for the neurons that just spiked. |
| 229 |
|
| 230 |
.. _function_vectorisation: |
| 231 |
|
| 232 |
Functions with context-dependent return values |
| 233 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 234 |
When using the ``numpy`` target, functions have to return an array of values |
| 235 |
(e.g. one value for each neuron). In some cases, the number of values to return |
| 236 |
cannot be deduced from the function's arguments. Most importantly, this is the |
| 237 |
case for random numbers: a call to `rand()` has to return one value for each |
| 238 |
neuron if it is part of a neuron's equations, but only one value for each neuron |
| 239 |
that spiked during the time step if it is part of the reset statement. Such |
| 240 |
function are said to "auto vectorise", which means that their implementation |
| 241 |
receives an additional array argument ``_vectorisation_idx``; the length of this |
| 242 |
array determines the number of values the function should return. This argument |
| 243 |
is also provided to functions for other code generation targets, but in these |
| 244 |
cases it is a single value (e.g. the index of the neuron), and is currently |
| 245 |
ignored. To enable this property on a user-defined function, you'll currently |
| 246 |
have to manually create a `Function` object:: |
| 247 |
|
| 248 |
def exponential_rand(l, _vectorisation_idx): |
| 249 |
'''Generate a number from an exponential distribution using inverse |
| 250 |
transform sampling''' |
| 251 |
uniform = np.random.rand(len(_vectorisation_idx)) |
| 252 |
return -(1/l)*np.log(1 - uniform) |
| 253 |
|
| 254 |
exponential_rand = Function(exponential_rand, arg_units=[1], return_unit=1, |
| 255 |
stateless=False, auto_vectorise=True) |
| 256 |
|
| 257 |
Implementations for other code generation targets can then be added using the |
| 258 |
`~FunctionImplementationContainer.add_implementation` mechanism:: |
| 259 |
|
| 260 |
cpp_code = ''' |
| 261 |
double exponential_rand(double l, int _vectorisation_idx) |
| 262 |
{ |
| 263 |
double uniform = rand(_vectorisation_idx); |
| 264 |
return -(1/l)*log(1 - uniform); |
| 265 |
} |
| 266 |
''' |
| 267 |
exponential_rand.implementations.add_implementation('cpp', cpp_code, |
| 268 |
dependencies={'rand': DEFAULT_FUNCTIONS['rand'], |
| 269 |
'log': DEFAULT_FUNCTIONS['log']}) |
| 270 |
|
| 271 |
Note that by referring to the `rand` function, the new random number generator will |
| 272 |
automatically generate reproducible random numbers if the `seed` function is use to set |
| 273 |
its seed. Restoring the random number state with `restore` will have the expected effect |
| 274 |
as well. |
| 275 |
|
| 276 |
Additional namespace |
| 277 |
~~~~~~~~~~~~~~~~~~~~ |
| 278 |
Some functions need additional data to compute a result, e.g. a `TimedArray` |
| 279 |
needs access to the underlying array. For the ``numpy`` target, a function can |
| 280 |
simply use a reference to an object defined outside the function, there is no |
| 281 |
need to explicitly pass values in a namespace. For the other code language |
| 282 |
targets, values can be passed in the ``namespace`` argument of the |
| 283 |
`implementation` decorator or the |
| 284 |
`~brian2.core.functions.FunctionImplementationContainer.add_implementation` method. The namespace |
| 285 |
values are then accessible in the function code under the given name, prefixed |
| 286 |
with ``_namespace``. Note that this mechanism should only be used for numpy |
| 287 |
arrays or general objects (e.g. function references to call Python functions |
| 288 |
from Cython code). Scalar values should be directly included in the |
| 289 |
function code, by using a "dynamic implemention" (see |
| 290 |
`~brian2.core.functions.FunctionImplementationContainer.add_dynamic_implementation`). |
| 291 |
|
| 292 |
See `TimedArray` and `BinomialFunction` for examples that use this mechanism. |
| 293 |
|
| 294 |
Data types |
| 295 |
~~~~~~~~~~ |
| 296 |
|
| 297 |
By default, functions are assumed to take any type of argument, and return a floating |
| 298 |
point value. If you want to put a restriction on the type of an argument, or specify |
| 299 |
that the return type should be something other than float, either declare it as a |
| 300 |
`Function` (and see its documentation on specifying types) or use the `declare_types` |
| 301 |
decorator, e.g.:: |
| 302 |
|
| 303 |
@check_units(a=1, b=1, result=1) |
| 304 |
@declare_types(a='integer', result='highest') |
| 305 |
def f(a, b): |
| 306 |
return a*b |
| 307 |
|
| 308 |
This is potentially important if you have functions that return integer or boolean |
| 309 |
values, because Brian's code generation optimisation step will make some potentially |
| 310 |
incorrect simplifications if it assumes that the return type is floating point. |
| 311 |
|
| 312 |
.. _external_sources: |
| 313 |
|
| 314 |
External source files |
| 315 |
~~~~~~~~~~~~~~~~~~~~~ |
| 316 |
|
| 317 |
Code for functions can also be provided via external files in the target |
| 318 |
language. This can be especially useful for linking to existing code without |
| 319 |
having to include it a second time in the Python script. For C++-based code |
| 320 |
generation targets (i.e. the C++ standalone mode), the external |
| 321 |
code should be in a file that is provided as an argument to the ``sources`` |
| 322 |
keyword, together with a header file whose name is provided to ``headers`` |
| 323 |
(see the note for the `codegen.cpp.headers` preference about the necessary |
| 324 |
format). Since the main simulation code is compiled and executed in a different |
| 325 |
directory, you should also point the compiler towards the directory of the |
| 326 |
header file via the ``include_dirs`` keyword. For the same reason, use an |
| 327 |
absolute path for the source file. |
| 328 |
For example, the ``piecewise_linear`` function from above can be implemented |
| 329 |
with external files as follows: |
| 330 |
|
| 331 |
.. code-block:: cpp |
| 332 |
|
| 333 |
//file: piecewise_linear.h |
| 334 |
double piecewise_linear(double); |
| 335 |
|
| 336 |
.. code-block:: cpp |
| 337 |
|
| 338 |
//file: piecewise_linear.cpp |
| 339 |
double piecewise_linear(double I) { |
| 340 |
if (I < 1e-9) |
| 341 |
return 0; |
| 342 |
if (I > 3e-9) |
| 343 |
return 100; |
| 344 |
return (I/1e-9 - 1) * 50; |
| 345 |
} |
| 346 |
|
| 347 |
.. code:: |
| 348 |
|
| 349 |
# Python script |
| 350 |
|
| 351 |
# Get the absolute directory of this Python script, the C++ files are |
| 352 |
# expected to be stored alongside of it |
| 353 |
import os |
| 354 |
current_dir = os.path.abspath(os.path.dirname(__file__)) |
| 355 |
|
| 356 |
@implementation('cpp', '// all code in piecewise_linear.cpp', |
| 357 |
sources=[os.path.join(current_dir, |
| 358 |
'piecewise_linear.cpp')], |
| 359 |
headers=['"piecewise_linear.h"'], |
| 360 |
include_dirs=[current_dir]) |
| 361 |
@check_units(I=amp, result=Hz) |
| 362 |
def piecewise_linear(I): |
| 363 |
return clip((I-1*nA) * 50*Hz/nA, 0*Hz, 100*Hz) |
| 364 |
|
| 365 |
|
| 366 |
For Cython, the process is very similar (see the |
| 367 |
`Cython documentation <https://cython.readthedocs.io/en/latest/src/userguide/sharing_declarations.html>`_ |
| 368 |
for general information). The name of the header file does not need to be |
| 369 |
specified, it is expected to have the same name as the source file (except for |
| 370 |
the ``.pxd`` extension). The source and header files will be automatically |
| 371 |
copied to the cache directory where Cython files are compiled, they therefore |
| 372 |
have to be imported as top-level modules, regardless of whether the executed |
| 373 |
Python code is itself in a package or module. |
| 374 |
|
| 375 |
A Cython equivalent of above's C++ example can be written as: |
| 376 |
|
| 377 |
.. code-block:: cython |
| 378 |
|
| 379 |
# file: piecewise_linear.pxd |
| 380 |
cdef double piecewise_linear(double) |
| 381 |
|
| 382 |
.. code-block:: cython |
| 383 |
|
| 384 |
# file: piecewise_linear.pyx |
| 385 |
cdef double piecewise_linear(double I): |
| 386 |
if I<1e-9: |
| 387 |
return 0.0 |
| 388 |
elif I>3e-9: |
| 389 |
return 100.0 |
| 390 |
return (I/1e-9-1)*50 |
| 391 |
|
| 392 |
.. code:: |
| 393 |
|
| 394 |
# Python script |
| 395 |
|
| 396 |
# Get the absolute directory of this Python script, the Cython files |
| 397 |
# are expected to be stored alongside of it |
| 398 |
import os |
| 399 |
current_dir = os.path.abspath(os.path.dirname(__file__)) |
| 400 |
|
| 401 |
@implementation('cython', |
| 402 |
'from piecewise_linear cimport piecewise_linear', |
| 403 |
sources=[os.path.join(current_dir, |
| 404 |
'piecewise_linear.pyx')]) |
| 405 |
@check_units(I=amp, result=Hz) |
| 406 |
def piecewise_linear(I): |
| 407 |
return clip((I-1*nA) * 50*Hz/nA, 0*Hz, 100*Hz) |