我正在尝试编写一个可以从python脚本调用的cython函数,该脚本使用c gsl库使用t分布来计算spearman相关性和相应的p值。我不成功的.pyx文件如下:

import numpy as np
import numpy as np

def spearmanr(cdef double v1, cdef double v2, cdef int N):

     cdef extern from "gsl/gsl_statistics_double.h":
         double gsl_stats_spearman(double data1[],size_t stride1,double data2[],size_t stride2, size_t n)

     cdef int strides = 1
     cdef int n = N

     cdef double r = gsl_stats_spearmanr(v1,strides,v2,strides,n)

     cdef double tstat=r*((n-2)/(1-r**2))**0.5

     cdef extern from "gsl/gsl_ranhist.h":
         double gsl_cdf_tdist_Q(double x, double nu)

     cdef double nu = N  %% Do I need to Type Cast?
     cdef double pval=gsl_cdf_tdist_Q(stat,nu)

     return r,pal


当我尝试对此进行编译时,出现以下错误:

running build_ext
cythoning spear_coxen.pyx to spear_coxen.c

Error compiling Cython file:
------------------------------------------------------------
...
import numpy as np
cimport numpy as np

def spermanr(cdef double v1, cdef double  v2, cdef int N):
        ^
------------------------------------------------------------

spear_coxen.pyx:4:13: Expected an identifier, found 'cdef'

Error compiling Cython file:
------------------------------------------------------------
...
import numpy as np
cimport numpy as np

def spermanr(cdef double v1, cdef double  v2, cdef int N):
                    ^
------------------------------------------------------------

spear_coxen.pyx:4:25: Expected ')', found 'v1'
building 'spear_r' extension
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall   -Wstrict-prototypes -fPIC -I/usr/local/Anaconda2-2.5.0/envs/python27/include/python2.7 -c spear_coxen.c -o build/temp.linux-x86_64-2.7/spear_coxen.o
spear_coxen.c:1:2: error: #error Do not use this file, it is the result    of a failed Cython compilation.
error: command 'gcc' failed with exit status 1


我真的不确定这是否是正确的语法,因为我找不到,因为搜索仅产生了一些琐碎的示例。如果有人可以提供帮助,我们将不胜感激。谢谢

最佳答案

您无需在函数参数中放入cdef。即

def spearmanr(cdef double v1, cdef double v2, cdef int N):


应该只是:

cpdef spearmanr(double v1, double v2, int N):


并将您的GSL声明移到该函数声明上方,而不是在其中。然后,它可以访问您声明的函数,例如

cdef extern from "gsl/gsl_statistics_double.h":

    double gsl_stats_spearman(double data1[],size_t stride1,double data2[],size_t stride2, size_t n)


对另一个extern执行相同的操作。

另外,您的声明看起来不正确(我不是在查看GSL文档),但是double data1[]如果您的意思是将其作为数组,则对于NumPy memoryview,应为double[:,:] data1或向量double[:] data1。让我知道对声明为这样的data1data2变量执行此操作后是否无法编译...

关于python - 如何在Cython中使用GSL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45150548/

10-12 18:31