A user-defined c++ unction calling another user defined python function

Is it possible for a user-defined c++ function to call another user defined python function with dependency options? For example:

 from brian2 import *

 set_device('cpp_standalone', directory='standalone', debug=True)

 @check_units(result=Hz)
 def add_more():
     return 100;

 @implementation('cpp', '''
      double ttt() {
         return 100 + add_more();
      }
      ''', dependencies={'add_more':add_more})
 @check_units(result=Hz)
 def ttt():
     raise NotImplementedError('use standalone mode')
 ##
 input = PoissonGroup(10, rates='ttt()')
 run(1*second, report='text')

the running will lead to the following errors:

  AttributeError: 'function' object has no attribute 'implementations'

I’m not sure, but it seems you need to add cpp implementation for function add_more. So it will appear in cpp namespace, and Brian would know how to compile it.
Something like that

 @implementation('cpp', '''
      double add_more() {
         return 100 .;
      }
      ''')
@check_units(result=Hz)
 def add_more():
     return 100;

1 Like

Thanks for the response. I’m hoping to add a python function into a cpp because python function sometime is easier to code. One can add a brian-defined function into the cpp code without issue. It would be nice to be able to add a user-defined python function.

@DavidKing2020, I’m not sure, but it seems it isn’t possible in Brian. I may be wrong, and @mstimberg is the best person to ask this question.

One general note. Python functions are slow, in general, much slower than C or C++ functions. Although it’s technically possible to call a python function from a C/C++ code, this drastically decreases performance.
Brian, in C++ mode, splits into 3 parts:

  1. python - network preparation
  2. C++ - network simulation
  3. python - result processing

If you add any call of python functions in the C++ part, you will kill the performance, and so you have to implement your function in C++ code to keep your simulations optimal.

Hi @rth, there’s a misunderstanding on what I’m trying to achieve. I’m hoping the brian2 code generator could generate the cpp version of the python function. Hopefully Marcel will be back from vacation soon to answer this question :wink:

Hi @DavidKing2020 . I’m back :blush:
Unfortunately, @rth is right, this is not possible with Brian. The code generation transforms a restricted subset of Python (what we call “abstract code”) with some Brian-specific semantics (everything written as if referring to a single neuron/synapse, but implicitly applied to a population). It is not a general Python-to-C++ converter.

1 Like