2010-12-01 71 views
2

我试图加快我NumPy的代码,并决定,我想实现一个特定的功能在我的代码大部分时间都在C.扩展NumPy的与C函数

我其实是在C新秀,但我设法写一个矩阵的每一行进行归一化的函数总和为1.我可以编译它,并用一些数据(C语言)对它进行测试,并且它按照我的要求进行了测试。那时我为自己感到骄傲。

现在我试图从Python调用我的光荣函数,它应该接受2d-Numpy数组。

我已经试过各种事情

  • 痛饮

  • 痛饮+ numpy.i

  • ctypes的

我的函数原型

void normalize_logspace_matrix(size_t nrow, size_t ncol, double mat[nrow][ncol]); 

因此,它需要一个指向可变长度数组的指针并将其修改到位。

我尝试以下纯痛饮接口文件:

%module c_utils 

%{ 
extern void normalize_logspace_matrix(size_t, size_t, double mat[*][*]); 
%} 

extern void normalize_logspace_matrix(size_t, size_t, double** mat); 

然后我会做(在Mac OS X 64位):

> swig -python c-utils.i 

> gcc -fPIC c-utils_wrap.c -o c-utils_wrap.o \ 
    -I/Library/Frameworks/Python.framework/Versions/6.2/include/python2.6/ \ 
    -L/Library/Frameworks/Python.framework/Versions/6.2/lib/python2.6/ -c 
c-utils_wrap.c: In function ‘_wrap_normalize_logspace_matrix’: 
c-utils_wrap.c:2867: warning: passing argument 3 of ‘normalize_logspace_matrix’ from incompatible pointer type 

> g++ -dynamiclib c-utils.o -o _c_utils.so 

在Python然后我得到导入下面的错误我模块:

>>> import c_utils 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ImportError: dynamic module does not define init function (initc_utils) 

接下来我尝试了这种方法使用SWIG + numpy.i

%module c_utils 

%{ 
#define SWIG_FILE_WITH_INIT 
#include "c-utils.h" 
%} 
%include "numpy.i" 
%init %{ 
import_array(); 
%} 

%apply (int DIM1, int DIM2, DATA_TYPE* INPLACE_ARRAY2) 
     {(size_t nrow, size_t ncol, double* mat)}; 

%include "c-utils.h" 

不过,我并不比这得到任何进一步的:

> swig -python c-utils.i 
c-utils.i:13: Warning 453: Can't apply (int DIM1,int DIM2,DATA_TYPE *INPLACE_ARRAY2). No typemaps are defined. 

痛饮似乎并没有找到numpy.i定义的typemaps,但我不明白为什么,因为numpy.i是在同一个目录下,SWIG不会抱怨它找不到它。

随着ctypes我没有得到很远,但很快就迷失在文档中,因为我无法弄清楚如何将它传递给一个二维数组,然后得到结果。

所以有人可以告诉我魔术如何使我的功能在Python/Numpy中可用?

回答

7

除非你有一个非常好的理由,否则你应该使用cython来连接C和python。 (我们开始使用cython而不是原生C在numpy/scipy中)。

你可以在我的scikits talkbox中看到一个简单的例子(因为从那以后cython已经有了很大的改进,我认为你今天可以写得更好)。

def cslfilter(c_np.ndarray b, c_np.ndarray a, c_np.ndarray x): 
    """Fast version of slfilter for a set of frames and filter coefficients. 
    More precisely, given rank 2 arrays for coefficients and input, this 
    computes: 

    for i in range(x.shape[0]): 
     y[i] = lfilter(b[i], a[i], x[i]) 

    This is mostly useful for processing on a set of windows with variable 
    filters, e.g. to compute LPC residual from a signal chopped into a set of 
    windows. 

    Parameters 
    ---------- 
     b: array 
      recursive coefficients 
     a: array 
      non-recursive coefficients 
     x: array 
      signal to filter 

    Note 
    ---- 

    This is a specialized function, and does not handle other types than 
    double, nor initial conditions.""" 

    cdef int na, nb, nfr, i, nx 
    cdef double *raw_x, *raw_a, *raw_b, *raw_y 
    cdef c_np.ndarray[double, ndim=2] tb 
    cdef c_np.ndarray[double, ndim=2] ta 
    cdef c_np.ndarray[double, ndim=2] tx 
    cdef c_np.ndarray[double, ndim=2] ty 

    dt = np.common_type(a, b, x) 

    if not dt == np.float64: 
     raise ValueError("Only float64 supported for now") 

    if not x.ndim == 2: 
     raise ValueError("Only input of rank 2 support") 

    if not b.ndim == 2: 
     raise ValueError("Only b of rank 2 support") 

    if not a.ndim == 2: 
     raise ValueError("Only a of rank 2 support") 

    nfr = a.shape[0] 
    if not nfr == b.shape[0]: 
     raise ValueError("Number of filters should be the same") 

    if not nfr == x.shape[0]: 
     raise ValueError, \ 
       "Number of filters and number of frames should be the same" 

    tx = np.ascontiguousarray(x, dtype=dt) 
    ty = np.ones((x.shape[0], x.shape[1]), dt) 

    na = a.shape[1] 
    nb = b.shape[1] 
    nx = x.shape[1] 

    ta = np.ascontiguousarray(np.copy(a), dtype=dt) 
    tb = np.ascontiguousarray(np.copy(b), dtype=dt) 

    raw_x = <double*>tx.data 
    raw_b = <double*>tb.data 
    raw_a = <double*>ta.data 
    raw_y = <double*>ty.data 

    for i in range(nfr): 
     filter_double(raw_b, nb, raw_a, na, raw_x, nx, raw_y) 
     raw_b += nb 
     raw_a += na 
     raw_x += nx 
     raw_y += nx 

    return ty 

正如你所看到的,除了通常的说法检查,你会在Python这样做,这几乎是同样的事情(filter_double是可以的,如果你想被写在纯C在一个单独的库函数) 。当然,由于它是编译代码,因此如果未能检查你的参数将会导致你的解释器崩溃而不是引发异常(尽管有近期的cython有几个安全级别与速度折衷关系)。

2

首先,你确定你在写最快的numpy代码吗?如果正常化你的意思是它的总和除以整行,那么你可以写快速矢量化代码看起来是这样的:

matrix /= matrix.sum(axis=0) 

如果这不是你脑子里什么,你还是看你需要一个快速的C扩展,我强烈建议你将它写在cython而不是C中。这样可以节省代码中的所有开销和困难,并允许你编写一些看起来像Python代码但可以运行的东西在大多数情况下快速为C.

+0

我在日志空间正常化,避免数值溢出。我有很长的,但苗条的矩阵(即100,000x10)。这是我的代码中唯一的一点,我必须遍历根据行剖析器的行,这是代码花费大部分时间的地方。我也看了一下cython,但这也是我的一个教育项目,所以我只想学习如何将我的Python与某些C混合在一起(如果需要的话)。 – oceanhug 2010-12-01 04:21:39

2

我同意别人的看法,一点Cython非常值得学习。 但如果你必须编写C或C++中,使用一维数组,其覆盖的2D,就像这样:

// sum1rows.cpp: 2d A as 1d A1 
// Unfortunately 
//  void f(int m, int n, double a[m][n]) { ... } 
// is valid c but not c++ . 
// See also 
// http://stackoverflow.com/questions/3959457/high-performance-c-multi-dimensional-arrays 
// http://stackoverflow.com/questions/tagged/multidimensional-array c++ 

#include <stdio.h> 

void sum1(int n, double x[]) // x /= sum(x) 
{ 
    float sum = 0; 
    for(int j = 0; j < n; j ++ ) 
     sum += x[j]; 
    for(int j = 0; j < n; j ++ ) 
     x[j] /= sum; 
} 

void sum1rows(int nrow, int ncol, double A1[]) // 1d A1 == 2d A[nrow][ncol] 
{ 
    for(int j = 0; j < nrow*ncol; j += ncol ) 
     sum1(ncol, &A1[j]); 
} 

int main(int argc, char** argv) 
{ 
    int nrow = 100, ncol = 10; 
    double A[nrow][ncol]; 
    for(int j = 0; j < nrow; j ++) 
    for(int k = 0; k < ncol; k ++) 
     A[j][k] = (j+1) * k; 

    double* A1 = &A[0][0]; // A as 1d array -- bad practice 
    sum1rows(nrow, ncol, A1); 

    for(int j = 0; j < 2; j ++){ 
     for(int k = 0; k < ncol; k ++){ 
      printf("%.2g ", A[j][k]); 
     } 
     printf("\n"); 
    } 
} 

新增11月8日:你可能知道,numpy.reshape可以覆盖一个numpy的二维数组与一维视图传递给sum1rows,像这样:

import numpy as np 
A = np.arange(10).reshape((2,5)) 
A1 = A.reshape(A.size) # a 1d view of A, not a copy 
# sum1rows(2, 5, A1) 
A[1,1] += 10 
print "A:", A 
print "A1:", A1 
3

要回答的真正问题:痛饮不会告诉你它找不到任何typemaps。它告诉你它不能应用类型映射(int DIM1,int DIM2,DATA_TYPE *INPLACE_ARRAY2),这是因为没有为DATA_TYPE *定义的类型映射。你需要告诉它你想将它应用到double*

%apply (int DIM1, int DIM2, double* INPLACE_ARRAY2) 
     {(size_t nrow, size_t ncol, double* mat)};