2011-01-07 13 views
2

私はいくつかのNumpy C-extensionsをこれまでの大きな助けを借りて作成しましたが、返されるパラメータはすべて固定長です。Numpy C-エクステンションの可変長配列を返しますか?

Numpy C-エクステンションに可変長numpy配列を返す方法はありますか?

+2

「可変長の配列」とは何ですか?限り、私の知る限り、numpy配列は、サイズが設定された後にサイズ変更することはできません。 – albertov

答えて

3

サイプレスでは、PythonとCオブジェクトを混在させることができるので、プロセスを簡略化するNumpy C-APIを使って簡単にnumpy拡張を行うことができます。その場合、可変長配列を作成することはほとんどできません。任意の形状の配列を指定するだけで済みます。

Cython numpy tutorialはおそらくこのトピックのベストソースです。

import numpy as np 
cimport numpy as np 
cimport cython 

dtype = np.double 
ctypedef double dtype_t 

np.import_ufunc() 
np.import_array() 

def ewma(a, d, axis): 
    #Calculates the exponentially weighted moving average of array a along axis using the parameter d. 
    cdef void *args[1] 

    cdef double weight[1] 
    weight[0] = <double>np.exp(-d) 


    args[0] = &weight[0] 

    return apply_along_axis(&ewma_func, np.array(a, dtype = float), np.double, np.double, False, &(args[0]), <int>axis) 

cdef void ewma_func(int n, void* aData,int astride, void* oData, int ostride, void** args): 
    #Exponentially weighted moving average calculation function 

    cdef double avg = 0.0 
    cdef double weight = (<double*>(args[0]))[0] 
    cdef int i = 0 

    for i in range(n): 

     avg = (<double*>((<char*>aData) + i * astride))[0]*weight + avg * (1.0 - weight) 


     (<double*>((<char*>oData) + i * ostride))[0] = avg 

ctypedef void (*func_1d)(int, void*, int, void*, int, void **) 

cdef apply_along_axis(func_1d function, a, adtype, odtype, reduce, void** args, int axis): 
    #generic function for applying a cython function along a particular dimension 

    oshape = list(a.shape) 

    if reduce : 
     oshape[axis] = 1 

    out = np.empty(oshape, odtype) 

    cdef np.flatiter ita, ito 

    ita = np.PyArray_IterAllButAxis(a, &axis) 
    ito = np.PyArray_IterAllButAxis(out, &axis) 

    cdef int axis_length = a.shape[axis] 
    cdef int a_axis_stride = a.strides[axis] 
    cdef int o_axis_stride = out.strides[axis] 

    if reduce: 
     o_axis_stride = 0 

    while np.PyArray_ITER_NOTDONE(ita): 

     function(axis_length, np.PyArray_ITER_DATA (ita), a_axis_stride, np.PyArray_ITER_DATA (ito), o_axis_stride, args) 

     np.PyArray_ITER_NEXT(ita) 
     np.PyArray_ITER_NEXT(ito) 

    if reduce: 
     oshape.pop(axis) 
     out.shape = oshape 

    return out 

これがあなたに合っていない場合は、任意の形状(link)で新しい空の配列を作成するための機能があります:

例えば、ここで私が最近書いた関数です。

関連する問題