1

I am going to have an option to choose integratiom method in ode solver wrapped in swig. I have defined simple harmonic oscillator in a class:

class HO
{
    double gamma;

public:
    HO(double gamma_) : gamma(gamma_) {}

    void operator()(const vector<double> &y, vector<double> &dydt, const double t)
    {
        dydt[0] = y[1];
        dydt[1] = -y[0] - gamma * y[1];
    }
};

and the euler integrator as a function that accept std::function as argument:

typedef std::vector<double> dim1;
typedef std::vector<vector<double>> dim2;

dim2 integrate_euler(
    std::function<void(const dim1 &, dim1 &, const double)> func,
    dim1 &y0,
    double ti,
    double tf,
    double dt);

after compiling with swig, I import the library in python :

import odesolver
dt = 0.01
ode = odesolver.HO(0.05)
x0 = [0.5, 1.0]
s =  odesolver.integrate_euler(ode, x0, 0., 100., dt)

and I get the following error:

Traceback (most recent call last):
  File "runme.py", line 19, in <module>
    s =  odesolver.integrate_euler(ode, x0, 0., 100., dt)
  File "/home/ziaee/git/04_SOLVERS/ode_solver/CPP/using_operator/swig/odesolver.py", line 459, in integrate_euler
    return _odesolver.integrate_euler(func, y0, ti, tf, dt)
TypeError: in method 'integrate_euler', argument 1 of type 'std::function< void (dim1 const &,dim1 &,double const) >'

I put the complete code here if you are interested to test it.

The question is somehow like this question, with this difference that I am passing a std::function. Do you have any solution or replace idea?

Abolfazl
  • 1,047
  • 2
  • 12
  • 29
  • The tricky thing here is getting SWIG to realise that it's legal to construct a std::function from that operator(). I'll put my thinking hat on – Flexo Jun 15 '21 at 19:43
  • I've a rather ugly hack - can you comment a little more on the other kinds of functions you might want to pass into integrate_euler? Will they all be C++ objects, with known set of types at the point in time you run SWIG? Or are you hoping to be able to write implementations in python? or pass arbitrary function pointers in too? – Flexo Jun 15 '21 at 20:33
  • The models are all defined in C++ with known types. The efficiency is the priority for me. – Abolfazl Jun 15 '21 at 21:23

0 Answers0