Distinct between scalar or array

0 views
Skip to first unread message

kas...@gmail.com

unread,
Jun 22, 2016, 3:27:49 AM6/22/16
to Numba Public Discussion - Public
Dear list,

I have a (nopython) function for which it would be nice if users can either provide an array or a scalar. However, i can't find a way to check whats provided from within the Numba code. And its necessary to now because an array would need to be indexed as opposed to a scalar. Python functions like isinstance, type, hasattr etc dont work. So is there a way to make this distinction within a Numba function? A workaround would be to always cast to an array on forehand, with something like np.full_like(), perhaps that's even faster then checking it in each iteration of the loop like in the example below.

A sample functions:


@numba.autojit(nopython=True)
def some_func(a, b):
   
# a is always an array
   
# b could be an array or scalar    

    c
= 0
   
   
for i in range(len(a)):
           
        ###   
       
# check if b should be indexed or not
        # something like
       
if isinstance(b, np.ndarray):
            b_val
= b[i]
       
else:
            b_val
= b
        ####

        c
+= a[i] + b_val
   
   
return c

a
= np.random.randn(10)
#b
= 5
b
= np.random.randn(10)

some_func
(a, b)

Is there a way in Numba to check if a variable is a scalar or an array?


Regards,
Rutger

Stanley Seibert

unread,
Jun 22, 2016, 9:48:17 AM6/22/16
to Numba Public Discussion - Public
Currently, I think this is your best option:

http://numba.pydata.org/numba-doc/latest/user/generated-jit.html

You can provide different implementations of the function based on the types of the arguments.  Eventually, we want the type inference algorithm to handle the case you show above (since isinstance() should always be treated as compile time constant for a given set of input types, so the branch could be optimized away), but it isn't quite there yet.

--
You received this message because you are subscribed to the Google Groups "Numba Public Discussion - Public" group.
To unsubscribe from this group and stop receiving emails from it, send an email to numba-users...@continuum.io.
To post to this group, send email to numba...@continuum.io.
To view this discussion on the web visit https://groups.google.com/a/continuum.io/d/msgid/numba-users/da387fe2-7a27-42e8-8160-df36505d3165%40continuum.io.
For more options, visit https://groups.google.com/a/continuum.io/d/optout.

kas...@gmail.com

unread,
Jun 23, 2016, 2:43:47 AM6/23/16
to Numba Public Discussion - Public
Thanks, that's a good suggestion and would work in my case. It complicates if you have many of those variables, the amount of combinations quickly gets out of hand when specifying them manually.


Regards,
Rutger
Reply all
Reply to author
Forward
0 new messages