Search code examples
pythoncythonearthpy

How to use cython compiler in python


in this link: http://earthpy.org/speed.html I found the following

%%cython
import numpy as np

def useless_cython(year):

    # define types of variables
    cdef int i, j, n
    cdef double a_cum

    from netCDF4 import Dataset
    f = Dataset('air.sig995.'+year+'.nc')
    a = f.variables['air'][:]

    a_cum = 0.
    for i in range(a.shape[0]):
        for j in range(a.shape[1]):
            for n in range(a.shape[2]):
                #here we have to convert numpy value to simple float
                a_cum = a_cum+float(a[i,j,n])

    # since a_cum is not numpy variable anymore,
    # we introduce new variable d in order to save
    # data to the file easily
    d = np.array(a_cum)
    d.tofile(year+'.bin')
    print(year)
    return d

It seems to be as easy as to just write %%cython over the function. However this just doesnt work for me -> "Statement seems to have no effect" says my IDE. After a bit of research I found that the %% syntax comes from iphyton which I did also install (as well as cython). Still doesnt work. Iam using python3.6 Any ideas?


Solution

  • Once you are in the IPython interpreter you have to load the extension prior to using it. It can be done with the statement %load_ext, so in your case :

    %load_ext cython

    These two tools are pretty well documented, if you have not seen it yet, take a look at the relevant part of the document on cython side and on IPython side.