Thursday, June 2, 2016

Example of numpy and c integration by ctype

example.c

#include <sys/types.h>

//sum by rows only the elements less than th
void sumLowerThan(double* res, double *a, ssize_t* dims,double th)
{
  int i,j;double v;
  for (i=0; i<dims[0]; i++) {
    res[i]=0;
    for (j=0;j<dims[1];j++){
      v=a[i*dims[1]+j];
      if (v<th){
        res[i]+=v;
      }     
    }//for j   
  }
}

compile with

gcc -shared -Wl,-soname,example -o example.so -fPIC example.c

example.py

#!/usr/bin/env python
import ctypes
import numpy as np


lib = np.ctypeslib.load_library('example', '.')

lib.sumLowerThan.restype = None
lib.sumLowerThan.argtypes = [np.ctypeslib.ndpointer(float, ndim=1,  # res
                                                    flags='aligned, contiguous, writeable'),
                             np.ctypeslib.ndpointer(float, ndim=2,  # a
                                                    flags='aligned, contiguous'),
                             ctypes.POINTER(np.ctypeslib.c_intp),  # dims
                             ctypes.c_double,  # th
                             ]


def sumLowerThan(a, th):
    a = np.require(a, float, ['CONTIGUOUS', 'ALIGNED'])
    res = np.require(np.empty(np.size(a, 0)),
                     float, ['CONTIGUOUS', 'ALIGNED', 'WRITEABLE'])
    lib.sumLowerThan(res, a, a.ctypes.shape, th)
    return res


a = np.random.rand(5, 10)
print(a)
print(sumLowerThan(a, 0.5))


sources:
http://stackoverflow.com/questions/5081875/ctypes-beginner
http://docs.scipy.org/doc/numpy-1.10.1/user/c-info.python-as-glue.html






No comments:

Post a Comment