High Performance Array Operations with Cython | Set 1



Code # 1: Cython function to trim values ​​in a simple one-dimensional array of twins

# work.pyx (Cython file)
cimport cython

 

@ cython . boundscheck ( False )

@ cython . wraparound ( False )

 

cpdef clip (double [:] a, double min , double max , double [:] out):

 

  " ""

Trim values ​​in to be between

min and max. Result out

"" "

if min & gt;  max :

raise ValueError ( "min must be & lt; = max" )

 

  if a.shape [ 0 ]! = out.shape [ 0 ]:

raise ValueError ( "input and output arrays must be the same size" )

 

for i in range (a.shape [ 0 ]):

if a [i] & lt;  min :

out [i] = min

elif a [i] & gt;  max :

out [i] = max

else :

  out [i] = a [i]

File work.py required to compile and build the extension.

Code # 2:

# import libraries

from distutils.core import setup

from distutils.extension import Extension

from Cython.Distutils import build_ext

 

ext_modules = [Extension (

`sample`

[ `sample.pyx` ])]

  

setup (name = `Sample app`

cmdclass = { ` build_ext` : build_ext}, 

ext_modules = ext_modules)

Having completed the above task, we can now check the operation of the resulting arrays of clips of functions with different types array objects.

Code # 3: Working with a clipping array.

# example of an array module

import work

import array

import numpy

 

arr  = array.array ( `d` , [ 1 , - 3 , 4 , 7 , 2 , 0 ])

print ( "Array:" , arr)

 
# Array clipping

work.clip (arr, 1 , 4 , arr)

print ( "Clipping array: " , arr)

  
# example example

arr2 = numpy.random.uniform ( - 10 , 10 , size = 1000000 )

print ( "arr2:" , arr2)

  

arr3 = numpy.zeros_like (arr2)

print ( "arr3:" , arr3)

  

work.clip (arr2, - 5 , 5 , arr3)

print ( "Clipping arr3:" , ar3)

print ( "Minimum in arr3:" , min ( arr3))

print ( "Maximum in arr3: " , min (arr3))

Output:

 Array: array (`d`, [1.0, -3.0, 4.0, 7.0, 2.0, 0.0]) Clipping array: array (` d`, [1.0, 1.0, 4.0, 4.0, 2.0, 1.0]) arr2: [-9.55546017, 7.45599334, 0.69248932, ..., 0.69583148, -3.86290931, 2.37266888] arr3: array ([0., 0., 0., ..., 0., 0., 0.]) Clipping arr3: [-5., 5., 0.69248932, ..., 0.69583148, -3.86290931, 2.37266888] Minimum in arr3: 5.0 Maximum in arr3: 5.0