Using scipy.integrate.ode with cython

北战南征 提交于 2019-12-24 06:59:13

问题


I'm currently trying to use my already written python code with Cython in the hope of a better performance. However, I encounter problems at a point I use scipy.interpolate.ode:

TypeError: f() takes exactly 3 positional arguments (2 given)

This can be reproduced with the following code:

import scipy.integrate as inte
import scipy.interpolate
import numpy as np


class model(object):
   def __init__(self):
    self.r = np.arange(10) #a variable
    self.val = np.arange(10,20) #some values already calculated
    self.interpol = scipy.interpolate.interp1d(self.r,self.val) #interpolation

   #works with python but produces an error with cython
   def do_integration(self):

       abbrev = lambda i: self.interpol(i) #this is more complex in reality

       def f(x,y,i):
           return x+abbrev(i)

       ode = inte.ode(f,None)
       ode.set_integrator('dopri5')
       ode.set_f_params(5)
       ode.set_initial_value(0,1)

       for i in np.arange(0,1,0.1):
           ode.integrate(i)

If f is defined outside of do_integration, it works also with cython. However, in the real code I define 4-5 lambda functions which are then used in f (mainly to get some derivatives from interpolated values, probably this is a bad style?). Thus, it would mean a lot of work to define f outside of do_integration.

I think my question is similar to this one, however the proposed solution does not work out for me:

Just defining

cpdef double f(double x,double y,double i):

gives

C function definition not allowed here

As I'm new to Cython, I'm not really sure what is the reason for that error messages. Is there anyone who can help me out?

Thanks a lot!

来源:https://stackoverflow.com/questions/38263794/using-scipy-integrate-ode-with-cython

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!