| 1 |
Adding support for new functions |
| 2 |
================================ |
| 3 |
|
| 4 |
For a description of Brian's function system from the user point of view, see |
| 5 |
:doc:`../advanced/functions`. |
| 6 |
|
| 7 |
The default functions available in Brian are stored in the `DEFAULT_FUNCTIONS` |
| 8 |
dictionary. New `Function` objects can be added to this dictionary to make them |
| 9 |
available to all Brian code, independent of its namespace. |
| 10 |
|
| 11 |
To add a new implementation for a code generation target, a |
| 12 |
`FunctionImplementation` can be added to the `Function.implementations` |
| 13 |
dictionary. The key for this dictionary has to be either a `CodeGenerator` class |
| 14 |
object, or a `CodeObject` class object. The `CodeGenerator` of a `CodeObject` |
| 15 |
(e.g. `CPPCodeGenerator` for `CPPStandaloneCodeObject`) is used as a fallback if no |
| 16 |
implementation specific to the `CodeObject` class exists. |
| 17 |
|
| 18 |
If a function is already provided for the target language (e.g. it is part of |
| 19 |
a library imported by default), using the same name, all that is needed is to |
| 20 |
add an empty `FunctionImplementation` object to mark the function as |
| 21 |
implemented. For example, ``exp`` is a standard function in C++:: |
| 22 |
|
| 23 |
DEFAULT_FUNCTIONS['exp'].implementations[CPPCodeGenerator] = FunctionImplementation() |
| 24 |
|
| 25 |
Some functions are implemented but have a different name in the target language. |
| 26 |
In this case, the `FunctionImplementation` object only has to specify the new |
| 27 |
name:: |
| 28 |
|
| 29 |
DEFAULT_FUNCTIONS['arcsin'].implementations[CPPCodeGenerator] = FunctionImplementation('asin') |
| 30 |
|
| 31 |
Finally, the function might not exist in the target language at all, in this |
| 32 |
case the code for the function has to be provided, the exact form of this |
| 33 |
code is language-specific. In the case of C++, it's a dictionary of code blocks:: |
| 34 |
|
| 35 |
clip_code = {'support_code': ''' |
| 36 |
double _clip(const float value, const float a_min, const float a_max) |
| 37 |
{ |
| 38 |
if (value < a_min) |
| 39 |
return a_min; |
| 40 |
if (value > a_max) |
| 41 |
return a_max; |
| 42 |
return value; |
| 43 |
} |
| 44 |
'''} |
| 45 |
DEFAULT_FUNCTIONS['clip'].implementations[CPPCodeGenerator] = FunctionImplementation('_clip', |
| 46 |
code=clip_code) |