Numpy __array_interface__ does not return dict

I use an external program to calculate the matrix, which is written in C ++ and is paired with python via boost::python . I would like to pass this C array to numpy, and according to the authors, this ability is already implemented with numpy obj.__array_interface__ . If I call this in a python script and assign a C ++ X object, I get the following:

 print X #<sprint.Matrix object at 0x107c5c320> print X.__array_interface__ #<bound method Matrix.__array_interface__ of <sprint.Matrix object at 0x107c5c320>> print X.__array_interface__() #{'shape': (5, 5), 'data': (4416696960, True), 'typestr': '<f8'} print np.array(X) #Traceback (most recent call last): # File "<string>", line 96, in <module> #ValueError: Invalid __array_interface__ value, must be a dict 

From my limited understanding, I believe that the X.__array_interface__ does not actually return anything without () . Is there a way to pass these arguments to np.array explicitly or a workaround for this problem.

I'm really brand new for mixing C ++ and python, if that doesn't make sense or I need to outline any part, let me know!

+6
source share
1 answer

__ array_interface__ should be a property (instance variable), not a method. Therefore, in C ++ or wherever the sprint.Matrix object is specified, change it so that instead:

 print X.__array_interface__ #<bound method Matrix.__array_interface__ of <sprint.Matrix object at 0x107c5c320>> 

you have

 print X.__array_interface__ #{'shape': (5, 5), 'data': (4416696960, True), 'typestr': '<f8'} 

An alternative would be to define a custom wrapper class:

 class SprintMatrixWrapper(object): def __init__(self, sprint_matrix): self.__array_interface__ = sprint_matrix.__array_interface__() 

and then just do:

 numpy.array(SprintMatrixWrapper(X)) 
+2
source

Source: https://habr.com/ru/post/949858/


All Articles