High-Performance Array Operations with Cython | Set 1

Although libraries like NumPy can perform high-performance array processing functions to operate on arrays. But Cython can also work really well. But how ?

Code #1 : Cython function for clipping the values in a simple 1D array of doubles

filter_none

edit
close

play_arrow

link
brightness_4
code

# work.pyx (Cython file)
cimport cython
  
@cython.boundscheck(False)
@cython.wraparound(False)
  
cpdef clip(double[:] a, double min, double max, double[:] out):
  
    '''
    Clip the values in a to be between 
    min and max. Result in out
    '''
    if min > max:
        raise ValueError("min must be <= 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] < min:
            out[i] = min
        elif a[i] > max:
            out[i] = max
        else:
            out[i] = a[i]

chevron_right


 
work.py file is required to compile and build the extension.

Code #2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing 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)

chevron_right


 
After performing the task above, now we can check the working of resulting function clips arrays, with many different kinds of array objects.



Code #3 : Working of Clipping Array.

filter_none

edit
close

play_arrow

link
brightness_4
code

# array module example
import work
import array
import numpy
  
arr = array.array('d', [1, -3, 4, 7, 2, 0])
print ("Array : ", arr)
  
# Clipping the array
work.clip(arr, 1, 4, arr)
print ("\nClipping array : ", arr)
  
# numpy example
arr2 = numpy.random.uniform(-10, 10, size = 1000000)
print ("\narr2 : \n", arr2)
  
arr3 = numpy.zeros_like(arr2)
print ("\narr3 : \n", arr3)
  
work.clip(arr2, -5, 5, arr3)
print ("\nClipping arr3 : \n", ar3)
print ("\nMinimum in arr3 : ", min(arr3))
print ("\nMaximum in arr3 : ", min(arr3))

chevron_right


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

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.