2010-12-01 37 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)};