Help needed! How to specify numba.jit arguments for read-only numpy arrays?

0 views
Skip to first unread message

Jason Sachs

unread,
Sep 13, 2017, 2:13:58 PM9/13/17
to Numba Public Discussion - Public
I am in the process of upgrading some old code from numba 0.16.0 (!!!) to numba 0.33.0 and it looks like one aspect of my old code is broken; I get a TypeError because one of the arguments to a function is a read-only numpy array, and it's incompatible with the numba.jit type signature I gave it.

How do you specify a type is read-only?

Here's a short example that illustrates the problem; this worked fine on numba 0.16 but gives a TypeError on numba 0.33:

-----

import numba
import numpy as np

@numba.jit('f8(u4[:])')
def jabberwocky(data):
    x = 0.0
    w = 1
    for item in data:
        x += 1.0*(item*w)
        w = -w
    return x
    
data = np.array([1,2,3,4,5],dtype=np.uint32)
data.flags.writeable = False
print data
print jabberwocky(data)

-----

> python numba_test1.py
[1 2 3 4 5]
Traceback (most recent call last):
  File "numba_test1.py", line 16, in <module>
    print jabberwocky(data)
  File "\path\to\anaconda\envs\myenv\lib\site-packages\numba\dispatcher.py", line 399, in _explain_matching_error
    raise TypeError(msg)
TypeError: No matching definition for argument type(s) readonly array(uint32, 1d, C)

-----

Is there a way to fix?

Jason Sachs

unread,
Sep 13, 2017, 2:27:21 PM9/13/17
to Numba Public Discussion - Public
I figured out an option after studying http://numba.pydata.org/numba-doc/dev/reference/types.html and http://numba.pydata.org/numba-doc/dev/reference/jit-compilation.html

This works in both 0.16.0 and 0.33.0, using numba type objects rather than a string signature:

-----

import numba
import numpy as np

x0 = np.empty((0,0), dtype=np.uint32)
x0.flags.writeable = False
@numba.jit(numba.double(numba.typeof(x0)))
def jabberwocky(data):
    x = 0.0
    w = 1
    for item in data:
        x += 1.0*(item*w)
        w = -w
    return x
    
data = np.array([1,2,3,4,5],dtype=np.uint32)
data.flags.writeable = False
print data
print jabberwocky(data)

----

Is there any way to avoid making this dummy object x0, and somehow create a type object directly that specifies read-only?

Jason Sachs

unread,
Sep 13, 2017, 2:28:22 PM9/13/17
to Numba Public Discussion - Public
oops that should have been:

x0 = np.empty((0), dtype=np.uint32)

odd how that still worked... :/
Reply all
Reply to author
Forward
0 new messages