2013-05-16 161 views
6

为了学习新东西,我正在尝试在C中重新实现numpy.mean()函数。它应该采用3D数组并返回一个二维数组,其平均值为沿着轴0的元素。我设法计算所有值的平均值,但并不真正知道如何将新数组返回给Python。从我读到的消息来源来看,我认为这涉及到一些严重的杂耍,我不太熟悉(但愿意这样做)。从C扩展返回numpy数组

我迄今为止代码:

#include <Python.h> 
#include <numpy/arrayobject.h> 

// Actual magic here: 
static PyObject* 
myexts_std(PyObject *self, PyObject *args) 
{ 
    PyArrayObject *input=NULL; 
    int i, j, k, x, y, z, dims[2]; 
    double out = 0.0; 

    if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &input)) 
     return NULL; 

    x = input->dimensions[0]; 
    y = input->dimensions[1]; 
    z = input->dimensions[2]; 

    for(k=0;k<z;k++){ 
     for(j=0;j<y;j++){ 
      for(i=0;i < x; i++){ 
       out += *(double*)(input->data + i*input->strides[0] 
+j*input->strides[1] + k*input->strides[2]); 
      } 
     } 
    } 
    out /= x*y*z; 
    return Py_BuildValue("f", out); 
} 

// Methods table - this defines the interface to python by mapping names to 
// c-functions  
static PyMethodDef myextsMethods[] = { 
    {"std", myexts_std, METH_VARARGS, 
     "Calculate the standard deviation pixelwise."}, 
    {NULL, NULL, 0, NULL} 
}; 

PyMODINIT_FUNC initmyexts(void) 
{ 
    (void) Py_InitModule("myexts", myextsMethods); 
    import_array(); 
} 

我明白为止(和请纠正我,如果我错了)是,我需要创建一个新的PyArrayObject,这将是我的输出(可能与PyArray_FromDims?)。然后我需要一个地址阵列来存储这个数组,并用数据填充它。我将如何去做这件事?

编辑:

做的指针(这里:http://pw1.netcom.com/~tjensen/ptr/pointers.htm)更多阅读后,我实现了我的宗旨。现在又出现了另一个问题:我在哪里可以找到numpy.mean()的原始实现?我想看看它是如何,python操作比我的版本快得多。我假设它避免了丑陋的循环。

这里是我的解决方案:

static PyObject* 
myexts_std(PyObject *self, PyObject *args) 
{ 
    PyArrayObject *input=NULL, *output=NULL; // will be pointer to actual numpy array ? 
    int i, j, k, x, y, z, dims[2]; // array dimensions ? 
    double *out = NULL; 
    if (!PyArg_ParseTuple(args, "O!", &PyArray_Type, &input)) 
     return NULL; 

    x = input->dimensions[0]; 
    y = dims[0] = input->dimensions[1]; 
    z = dims[1] = input->dimensions[2]; 
    output = PyArray_FromDims(2, dims, PyArray_DOUBLE);  
    for(k=0;k<z;k++){ 
     for(j=0;j<y;j++){ 
      out = output->data + j*output->strides[0] + k*output->strides[1]; 
      *out = 0; 
      for(i=0;i < x; i++){ 
       *out += *(double*)(input->data + i*input->strides[0] +j*input->strides[1] + k*input->strides[2]); 
      } 
      *out /= x; 
     } 
    } 
    return PyArray_Return(output); 
} 
+3

这里是numpy的的平均值的源代码:https://github.com/numpy/numpy/blob/3abd8699dc3c71e389356ca6d80a2cb9efa16151/numpy/core/src/multiarray/calculation.c#L744 – SingleNegationElimination

回答

0

的numpy的API有一个函数PyArray_Mean是完成你想要什么没有“丑循环”做)。