Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I cast a float numpy array value to an int inside of a numba jitted function in nopython mode

Inside a numba jitted nopython function, I need to index an array with the values inside of an another array. Both arrays are numpy arrays floats.

For example

@numba.jit("void(f8[:], f8[:], f8[:])", nopython=True)
def need_a_cast(sources, indices, destinations):
    for i in range(indices.size):
        destinations[i] = sources[indices[i]]

My code is different, but let's assume the problem is reproducible by this stupid example (i.e., I cannot have indices of type int). AFAIK, i cannot use int(indices[i]) nor indices[i].astype("int") inside of nopython jit function.

How do I do this?

like image 635
marcorossi Avatar asked Mar 17 '16 02:03

marcorossi


People also ask

How do I convert a NumPy array to integer?

You can convert numpy array elements to int using the astype() method. You have to just pass the entire array inside the function.

Does Numba work with NumPy arrays?

Numba excels at generating code that executes on top of NumPy arrays. NumPy support in Numba comes in many forms: Numba understands calls to NumPy ufuncs and is able to generate equivalent native code for many of them. NumPy arrays are directly supported in Numba.

What is Nopython mode?

The behaviour of the nopython compilation mode is to essentially compile the decorated function so that it will run entirely without the involvement of the Python interpreter. This is the recommended and best-practice way to use the Numba jit decorator as it leads to the best performance.

Can Numba work with lists?

Creating and returning lists from JIT-compiled functions is supported, as well as all methods and operations. Lists must be strictly homogeneous: Numba will reject any list containing objects of different types, even if the types are compatible (for example, [1, 2.5] is rejected as it contains a int and a float ).


1 Answers

Using numba 0.24 at least, you can do a simple cast:

import numpy as np
import numba as nb

@nb.jit(nopython=True)
def need_a_cast(sources, indices, destinations):
    for i in range(indices.size):
        destinations[i] = sources[int(indices[i])]

sources = np.arange(10, dtype=np.float64)
indices = np.arange(10, dtype=np.float64)
np.random.shuffle(indices)
destinations = np.empty_like(sources)

print indices
need_a_cast(sources, indices, destinations)
print destinations

# Result
# [ 3.  2.  8.  1.  5.  6.  9.  4.  0.  7.]
# [ 3.  2.  8.  1.  5.  6.  9.  4.  0.  7.]
like image 164
JoshAdel Avatar answered Nov 14 '22 21:11

JoshAdel