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?
You can convert numpy array elements to int using the astype() method. You have to just pass the entire array inside the function.
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.
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.
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 ).
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.]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With