简体   繁体   English

Numpy / Scipy如何将C函数转换为矢量化Python函数?

[英]How does Numpy/Scipy turn C functions into vectorized Python functions?

As I understand it, vectorized numpy functions are faster than Python loops because loops are done in C or Fortran. 据我了解,矢量化的numpy函数比Python循环快,因为循环是在C或Fortran中完成的。 I would like to know where in the source code this happens. 我想知道这在源代码中的什么地方发生。

For example, the scipy.special.bdtr binomial CDF function accepts array-like arguments k,n,p and will return an ndarray provided the arguments are broadcastable. 例如, scipy.special.bdtr二项式CDF函数接受类似数组的参数k,n,p ,并返回一个ndarray,前提是该参数是可广播的。 The documentation says that scipy.special.bdtr is a wrapper for a routine in the Cephes Mathematical Functions Library. 该文档说scipy.special.bdtr是Cephes数学函数库中例程的包装。 Digging through the source code on Github, I found a scipy/special/cephes/bdtr.c file containing the C code for the routine; 在Github上浏览源代码,我发现了一个scipy/special/cephes/bdtr.c文件,其中包含该例程的C代码。 here are what I believe to be the first three lines of the relevant C function: 我认为这是相关C函数的前三行:

double bdtr(k, n, p) 双bdtr(k,n,p)

int k, n; int k,n;

double p; 双p;

It appears that the underlying C function does not operate on arrays, and I can't find the source code where this function is converted to a Python function that operates on arrays. 似乎底层的C函数不能在数组上运行,并且我找不到该函数转换为可在数组上运行的Python函数的源代码。

In the case of scipy.special functions, the C code only contains the "kernels" of the functions, that is, how to apply the function to scalars. 对于scipy.special函数,C代码仅包含函数的“内核”,即,如何将函数应用于标量。 Each of these is then wrapped into a ufunc with automatically generated Cython code. 然后这些各个被包裹成ufunc与自动生成用Cython代码。 To do this, it uses C header files, like scipy/special/cephes.h , Cython declaration files, like scipy/special/_cephes.pxd , the file scipy/special/functions.json , where all the functions to be generated for scipy.special are listed, and finally scipy/special/_generate_pyx.py , which is where the Cython code is actually produced. 为此,它使用C头文件,例如scipy/special/cephes.h ; Cython声明文件,例如scipy/special/_cephes.pxd ;文件scipy/special/functions.json ,其中将生成所有函数列出scipy.special ,最后列出scipy/special/_generate_pyx.py ,这是实际生成Cython代码的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM