Fausto Arinos Barbuto
Fausto Arinos Barbuto

Reputation: 398

Strings and numba

I'm writing a quite simple Python code using classes and numba and everything was OK until I had the 'brilliant' idea of passing an array of strings to __init__(). The first relevant lines of code are shown below:

import numpy as np
from numba import float64, types
from numba.experimental import jitclass

spec = [('p_', float64), ('T_', float64), ('pc_', float64), ('Tc_', float64), \
        ('rhoc', float64), ('omega_', float64), ('MW_', float64), \
        ('zf', float64), ('rho', float64), ('visc', float64), \
        ('Comps', types.unicode_type[:]), ('Y', float64[:])]

@jitclass(spec)
class Viscosity:

    def __init__(self, p_, T_, Comps, Y):
        ....

Comps is what is giving me trouble. Typically, Comps would be something like np.array(['CH4','C2H6']). I might have made it simply a list, ['CH4','C2H6'], instead of an array, but that doesn't matter as it would not work anyway. No numerical or string manipulations are done on those strings anywhere in the code; I just want to have them passed to __init__().

I found a simple example where a string is declared as types.unicode_type and tried to adapt it to my slightly more complicated case, but it didn't work.

There should be a way to circumvent this, since no processing is done on the strings. I might as well wipe numba completely out from my code, as execution time is not critical in this little project and probably will never be an issue. But I don't like the idea of giving up easily on things like those.

Thanks for any help.

Upvotes: 1

Views: 658

Answers (1)

polkas
polkas

Reputation: 4184

It starts working correctly when I replaced [:] to types.ListType. Take into account that all methods of a jitclass are compiled into nopython functions.

import numpy as np
from numba import float64, f8, types
from numba.experimental import jitclass

spec = [('p_', float64), ('T_', float64), ('pc_', float64), ('Tc_', float64), \
        ('rhoc', float64), ('omega_', float64), ('MW_', float64), \
        ('zf', float64), ('rho', float64), ('visc', float64), \
        ('Comps', types.ListType(types.unicode_type)), ('Y', types.ListType(f8))]

@jitclass(spec)
class Viscosity:

    def __init__(self, p_, T_, Comps, Y):
        return print(Comps)
    
    
Viscosity(2.0, 2.0, ["a", "b"], [1.0, 2.0])
# ['a' 'b']

Upvotes: 1

Related Questions