简体   繁体   English

使用Cython在numpy网格上评估C函数

[英]Evaluating C function on a numpy grid using Cython

The example in Simple wrapping of C code with cython describes nicely how to evaluate a function written in C on an array passed from numpy and return the result in a numpy array. 用cython简单包装C代码的示例很好地描述了如何在从numpy传递的数组上评估用C编写的函数并将结果返回到numpy数组中。

How would one go about doing the same thing but returning a 2D array? 如何做同样的事情但返回2D数组呢? Ie I'd like to evaluate a C function on a grid defined by two numpy arrays, and return the result as a numpy 2D array. 即我想在由两个Numpy数组定义的网格上评估C函数,并将结果作为Numpy 2D数组返回。

It would be something like this (using same functions as in the link above). 就像这样(使用与上面链接相同的功能)。 Obviously one can't use double z[] now, but I'm not sure how to pass a 2D numpy array to C. 显然,现在不能使用double z [],但是我不确定如何将2D numpy数组传递给C。

/*  fc.cpp    */
int fc( int N, const double a[], const double b[], double z[] )
    {
    for( int i = 0;  i < N;  i ++ ){
        for( int j = 0;  j < N;  j ++ ){
            z[i][j] = somefunction(a[i],b[j]);
    }
    return N;
}

This is the original .pyx file (see below). 这是原始的.pyx文件(请参见下文)。

import numpy as np
cimport numpy as np
cdef extern from "fc.h": 
    int fc( int N, double* a, double* b, double* z )  # z = a + b

def fpy( N,
    np.ndarray[np.double_t,ndim=1] A,
    np.ndarray[np.double_t,ndim=1] B,
    np.ndarray[np.double_t,ndim=1] Z ):
    """ wrap np arrays to fc( a.data ... ) """
       assert N <= len(A) == len(B) == len(Z)
       fcret = fc( N, <double*> A.data, <double*> B.data, <double*> Z.data )

    return fcret

Many thanks. 非常感谢。

You can use a normal array for a 2D Matrix. 您可以将普通阵列用于2D矩阵。 You need only give the length of the dimension to the function. 您只需要为函数指定尺寸的长度即可。

In the C file do something as that: (z is now an array of length N*N) 在C文件中执行以下操作:(z现在是长度为N * N的数组)

int fc( int N, const double a[], const double b[], double z[] )
{
    for( int i = 0;  i < N;  i++ ){
        for( int j = 0;  j < N;  j ++ ){
            z[(i*N)+j] = somefunction(a[i],b[j]);
    }
    return N;
}

In Python you need to do the same, so you can use a 1D Array with N*N elements instead of an 2D Matrix. 在Python中,您需要执行相同的操作,因此可以使用具有N * N个元素的1D数组而不是2D矩阵。

Update 3D case 更新3D外壳

(z is now an array of length N*N*N) (z现在是长度为N * N * N的数组)

int fc( int N, const double a[], const double b[],const double c[], double z[] )
{
    for( int i = 0;  i < N;  i++ ){
        for( int j = 0;  j < N;  j ++ ){
           for( int k = 0;  k < N;  k ++ ){
            z[((i*N)+j)*N+k] = somefunction(a[i],b[j],c[k]);
    }
    return N;
}

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

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