Skip to content

Commit 1030103

Browse files
committed
Adding a simple "to_array" function to ease interoperability
1 parent 54a0cab commit 1030103

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

arrayfire/interop.py

+38-2
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121

2222
try:
2323
import numpy as np
24+
from numpy import ndarray as NumpyArray
2425
from .data import reorder
2526

2627
AF_NUMPY_FOUND=True
@@ -69,7 +70,8 @@ def np_to_af_array(np_arr):
6970
AF_NUMPY_FOUND=False
7071

7172
try:
72-
import pycuda.gpuarray as CudaArray
73+
import pycuda.gpuarray
74+
from pycuda.gpuarray import GPUArray as CudaArray
7375
AF_PYCUDA_FOUND=True
7476

7577
def pycuda_to_af_array(pycu_arr):
@@ -83,6 +85,10 @@ def pycuda_to_af_array(pycu_arr):
8385
Returns
8486
----------
8587
af_arr : arrayfire.Array()
88+
89+
Note
90+
----------
91+
The input array is copied to af.Array
8692
"""
8793

8894
in_ptr = pycu_arr.ptr
@@ -92,6 +98,7 @@ def pycuda_to_af_array(pycu_arr):
9298
if (pycu_arr.flags.f_contiguous):
9399
res = Array(in_ptr, in_shape, in_dtype, is_device=True)
94100
lock_array(res)
101+
res = res.copy()
95102
return res
96103
elif (pycu_arr.flags.c_contiguous):
97104
if pycu_arr.ndim == 1:
@@ -119,7 +126,7 @@ def pycuda_to_af_array(pycu_arr):
119126
AF_PYCUDA_FOUND=False
120127

121128
try:
122-
import pyopencl.array as CLArray
129+
from pyopencl.array import Array as OpenclArray
123130
from .opencl import add_device_context as _add_device_context
124131
from .opencl import set_device_context as _set_device_context
125132
from .opencl import get_device_id as _get_device_id
@@ -137,6 +144,10 @@ def pyopencl_to_af_array(pycl_arr):
137144
Returns
138145
----------
139146
af_arr : arrayfire.Array()
147+
148+
Note
149+
----------
150+
The input array is copied to af.Array
140151
"""
141152

142153
ctx = pycl_arr.context.int_ptr
@@ -189,3 +200,28 @@ def pyopencl_to_af_array(pycl_arr):
189200
return pyopencl_to_af_array(pycl_arr.copy())
190201
except:
191202
AF_PYOPENCL_FOUND=False
203+
204+
205+
def to_array(in_array):
206+
"""
207+
Helper function to convert input from a different module to af.Array
208+
209+
Parameters
210+
-------------
211+
212+
in_array : array like object
213+
Can be one of numpy.ndarray, pycuda.GPUArray, pyopencl.Array, array.array, list
214+
215+
Returns
216+
--------------
217+
af.Array of same dimensions as input after copying the data from the input
218+
219+
220+
"""
221+
if AF_NUMPY_FOUND and isinstance(in_array, NumpyArray):
222+
return np_to_af_array(in_array)
223+
if AF_PYCUDA_FOUND and isinstance(in_array, CudaArray):
224+
return pycuda_to_af_array(in_array)
225+
if AF_PYOPENCL_FOUND and isinstance(in_array, OpenclArray):
226+
return pyopencl_to_af_array(in_array)
227+
return Array(src=in_array)

0 commit comments

Comments
 (0)