使用cython_gsl进行集成(加上将numpy.array解析为cython)

时间:2014-06-09 17:38:47

标签: c arrays numpy cython gsl

我想提高代码的速度,所以我将原来的Python代码转移到Cython。代码的瓶颈是我使用scipy.integral.quad进行的集成部分,然后在2D数组的每一行上连接numpy.arraysum。所以我试图重新编写我在Cython中使用的类。

我的课程如下:

import numpy as np
import cosmology
from cython_gsl cimport *

ctypedef double * double_ptr
ctypedef void * void_ptr


cdef class Cosmology(object):
    cdef double omega_c
    def __init__(self, double omega_m=0.3, double omega_lam=0.7):
        # no quintessence, no radiation in this universe!
        self.omega_m = omega_m
        self.omega_lam = omega_lam
        self.omega_c = (1. - omega_m - omega_lam)

    cdef double a(self, double z):
        return 1./(1+z)

    cdef double E(self, double a):
        return (self.omega_m*a**(-3) + self.omega_c*a**(-2) + self.omega_lam)**0.5

    cdef double __angKernel(self, double x, void * params) nogil:
        cdef double alpha, f
        alpha = (<double_ptr> params)[0]
        f=self.E(alpha*x**-1)**-1
        return f

    cdef double Da(self, int size, double *z, double z_ref=0):
        cdef gsl_integration_workspace *w
        cdef double result, error, expected, alpha
        w = gsl_integration_workspace_alloc (1000)
        cdef gsl_function F
        if size>1:
           da = np.zeros(size)
           for i in range(size):
               da[i] = self.Da(1, &z[i], z_ref)
           return da
        else:
           if z[0] < 0:
                    raise ValueError("Redshift z must not be negative")
           if z[0] < z_ref:
                    raise ValueError("Redshift z must not be smaller than the reference redshift")

           expected = -4.0
           alpha = 1

           F.function = &self.__angKernel
           F.params = &alpha

           gsl_integration_qags (&F, z_ref+1, z[0]+1, 0, 1e-7, 1000, w, &result, &error)
           d=result
           rk = (abs(self.omega_c))**0.5
           if (rk*d > 0.01):
              if self.omega_c > 0:
                 d = sinh(rk*d)/rk
              if self.omega_c < 0:
                 d = sin(rk*d)/rk
           return d/(1+z[0])


cdef class halo_positions(object):
    cdef double *x 
    cdef double *y 
    def __init__(self, double[:] positions):
        self.x = &positions[0]
        self.y = &positions[1]

我正在尝试使用cython_gsl进行集成,之后我尝试将其实现为我的积分并构建cnfw_model.pyx代码。我收到此错误消息:

Error compiling Cython file:
------------------------------------------------------------
...
                    raise ValueError("Redshift z must not be smaller than the reference redshift")

           expected = -4.0
           alpha = 1

           F.function = &self.__angKernel
                       ^
------------------------------------------------------------

cnfw_model.pyx:102:24: Cannot assign type 'double (*)(Cosmology, double, void *) nogil' to 'double (*)(double, void *) nogil'

Error compiling Cython file:
------------------------------------------------------------
...
    cdef double __angKernel(self, double x, void * params) nogil:
        cdef double alpha, f
        alpha = (<double_ptr> params)[0]
        """Integration kernel for angular diameter distance computation.
        """
        f=self.E(alpha*x**-1)**-1
               ^
------------------------------------------------------------

cnfw_model.pyx:73:16: Calling gil-requiring function not allowed without gil

我不知道如何定义function F以避免此问题。

:在class halo_positions中,我想更改它以获得2xN维数组并将其划分为两个1xN维数组并将其分配给x并且y

1 个答案:

答案 0 :(得分:0)

似乎类似于在C ++中也会发生的问题(我不在python中编写代码,但问题似乎是相同的)。您无法将成员函数转换为全局函数。请记住,gsl_function是以下c_struct

struct gsl_function_struct 
{
   double (* function) (double x, void * params);
   void * params;
};

typedef struct gsl_function_struct gsl_function ;

你可以看到gsl.function是一个指向全局函数的指针(成员函数有一个额外的参数来保存指针&#34;这个&#34;)。

cython_gsl的github有an example,其中集成在全局函数上完成。

from cython_gsl cimport *

ctypedef double * double_ptr
ctypedef void * void_ptr

cdef double normal(double x, void * params) nogil:
  cdef double mu = (<double_ptr> params)[0]
  cdef double sigma = (<double_ptr> params)[1]

  return gsl_ran_gaussian_pdf(x - mu, sigma)

def cdf_numerical(double x, double mu, double sigma):
  cdef double alpha, result, error, expected
  cdef gsl_integration_workspace * W
  W = gsl_integration_workspace_alloc(1000)
  cdef gsl_function F
  cdef double params[1]
  cdef size_t neval

  params[0] = mu
  params[1] = sigma

  F.function = &normal
  F.params = params

  gsl_integration_qag(&F, -10, x, 1e-2, 1e-2, 1000, GSL_INTEG_GAUSS15, W, &result, &error)
  gsl_integration_workspace_free(W)

  return result

解决此问题的一种方法是创建一个包装成员函数的全局函数。在这种情况下,您需要在void参数中发送类指针。