How do I handle inhomogenous list/array returns of functions?

Hello,

I do have sometimes functions that return (unstructured) lists or inhomogenous arrays like as examples:

def tsp_algorithm(coordinates, distance_matrix):
...
route = np.array(idx_h) # array of indices
distance = distance_calc(distance_matrix, [route, 1]) # float

return route, distance # or sometimes
return [route, distance]

or

def convexHull(points):
...
return (hull, usedPoints) # 2 arrays of different length

In later functions I woud normally (without numba) fetch the results as:

tspIndices, totalDistanceNew = tsp_algorithm(points, distMatrix)

and

hull, usedpoints = convexHull(coordinates)

Is there a way to deliver this kind of results [(unstructured) lists or inhomogenous arrays] from functions compatible to numba?

How do I code it?
Are there type definitions for these kind of results?

You can return heterogenous Tuple of your arrays. Their layout is a particular case of a structure, i.e., it wants to know types of the members of the tuple and will arrange them sequentially one after another. Here’s a demo:

import numba
import numpy


@numba.njit
def aux():
    a1 = numpy.array([137], dtype=numpy.int32)
    a2 = numpy.array([2.17, 1.41, 1.72], dtype=numpy.float64)
    return a1, a2


if __name__ == "__main__":
    a1_, a2_ = aux()
    print(a1_) # [137]
    print(a2_) # [2.17 1.41 1.72]
    print(aux.nopython_signatures[0]) # () -> Tuple(array(int32, 1d, C), array(float64, 1d, C))
2 Likes

Thanks a lot. It works. :folded_hands: