0
votes

Example code with a NumPy ufunc:

import numpy as np

nums = np.array([1, 2, 3])
times = nums.astype('timedelta64[ns]')

np.less(nums, 2)
np.less(nums, np.timedelta64(2))

Both of those give the same result:

array([ True, False, False], dtype=bool)

Now I want to do something similar with Numba:

import numba

@numba.vectorize(nopython=True)
def myless(a, b):
    return a < b

myless(nums, 2)
myless(times, np.timedelta64(2)) # fails

The first gives the correct result, but the second fails:

TypeError: ufunc 'myless' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

What's wrong? How can I fix it?

2

2 Answers

0
votes

I found a hint in the Numba 0.17 release notes (which by now is quite an old version):

Issue #917: Allow vectorizing with datetime64 and timedelta64 in the signature (only with unit-less values, though, because of a Numpy limitation).

which leads to this comment:

it seems numpy won't less us call ufuncs with non-unitless datetimes and timedeltas, so we're cooked [...]

So apparently you cannot ever use Numba vectorized ufuncs with NumPy timedelta64 in nopython mode, unless the timedelta64 has no units specified (in my example the array type had [ns] for nanoseconds, and even adding the units to the scalar doesn't help).

0
votes

It's only a workaround, but you can always zero-copy view your timedeltas as integers (and vice-versa)

In [80]: i8 = np.dtype('int64')

In [81]: myless(times.view(i8), np.timedelta64(2).view(i8))
Out[81]: array([ True, False, False], dtype=bool)