0

I need to use ctypes functions to reduce the running time of quad in python. Here is my original question original question, but now i know what path i need to follow. I need to follow the same steps as in here similar problem link.

However in my case the function that will be handled in the numerical integration is calling another python function. Like this:

from sklearn.neighbors import KernelDensity
import numpy as np
    
funcA = lambda x: np.exp(kde_bad.score_samples([[x]]))
quad(funcA, 0, cut_off)

where cut_off is just a scalar that I decide in my code, and kde_bad is the kernel object created using KernelDensity.

So my question is how do I need to specify the function in C? the equivalent of this:

//testlib.c
    
double f(int n, double args[n])    
{
   return args[0] - args[1] * args[2]; //corresponds to x0 - x1 * x2
}

Any input is appreciated!

2 Answers 2

0

You can do this using ctypes's callback function facilities.

That said, it's debatable whether or not you'll actually achieve any speed gains if your function calls something from Python. There are essentially two reasons that ctypes speeds up integration: (1) the integrand function itself is faster as compiled C than as Python bytecode, and (2) it avoids calling back to Python from the compiled (Fortran!) QUADPACK routines. What you're proposing completely eliminates the second of these sources of performance gains, and might even increase the penalty if you make such a call more than once. If, however, the large bulk of the execution time of your integrand is in its own code, rather than in these other Python functions that you need to call, then you might see some benefit.

Sign up to request clarification or add additional context in comments.

Comments

0

As answered in the other question, quadpy is here to save the day with its vectorized computation capabilities.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.