wlav / cppyy

Other
413 stars 42 forks source link

feat(add): numpy ndarray--template-less init #255

Open Khushiyant opened 2 months ago

Khushiyant commented 2 months ago

Initially following example use to raise error:

Example

from cppyy.gbl.std import vector
import numpy as np

def test():
    arr = np.random.randint(0, 10, size=(2,3,4))
    v1 = vector(arr)
    print(v1)
test()

Error:

Traceback (most recent call last):
  File "/workspaces/codespaces-blank/test.py", line 12, in <module>
    test()
  File "/workspaces/codespaces-blank/test.py", line 9, in test
    v1 = vector(arr)
         ^^^^^^^^^^^
  File "/workspaces/codespaces-blank/.venv/lib/python3.12/site-packages/cppyy/_cpython_cppyy.py", line 117, in __call__
    if args0 and (type(args0) is tuple or type(args0) is list):
       ^^^^^
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Hence, it was not possible to initialise the vector from numpy array without defining vector template and numpy array dtype

Current support

from cppyy.gbl.std import vector
import numpy as np

def test():
    arr = np.random.randint(0, 10, size=(2,3,4,2), dtype=np.int32)
    v1 = vector[vector[vector[vector[int]]]](arr)
    print(v1)
test()

It is not a feasible option to define the vector templates at time of writing code especially in with usage with various ML backends

CPyCppyy#28 was the cpp side implementation to provide this support but cppyy frondend implementation is better approach in comparison