Skip to content

Commit 6e105e1

Browse files
committed
FEAT: Adding interop module
1 parent 1e11f9b commit 6e105e1

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

arrayfire/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,11 @@
5252
from .graphics import *
5353
from .bcast import *
5454
from .index import *
55+
from .interop import *
5556

5657
# do not export default modules as part of arrayfire
5758
del ct
5859
del inspect
5960
del numbers
6061
del os
62+
del np

arrayfire/interop.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#######################################################
2+
# Copyright (c) 2015, ArrayFire
3+
# All rights reserved.
4+
#
5+
# This file is distributed under 3-clause BSD license.
6+
# The complete license agreement can be obtained at:
7+
# http://arrayfire.com/licenses/BSD-3-Clause
8+
########################################################
9+
10+
"""
11+
Interop with other python packages.
12+
13+
This module provides interoperability with the following python packages.
14+
15+
1. numpy
16+
"""
17+
18+
from .array import *
19+
from .data import reorder
20+
21+
try:
22+
import numpy as np
23+
AF_NP_FOUND=True
24+
25+
def np_to_af_array(np_arr):
26+
"""
27+
Convert numpy.ndarray to arrayfire.Array.
28+
29+
Parameters
30+
----------
31+
np_arr : numpy.ndarray()
32+
33+
Returns
34+
---------
35+
af_arry : arrayfire.Array()
36+
"""
37+
if (np_arr.flags['F_CONTIGUOUS']):
38+
return Array(np_arr.ctypes.data, np_arr.shape, np_arr.dtype.char)
39+
elif (np_arr.flags['C_CONTIGUOUS']):
40+
if np_arr.ndim == 1:
41+
return Array(np_arr.ctypes.data, np_arr.shape, np_arr.dtype.char)
42+
elif np_arr.ndim == 2:
43+
shape = (np_arr.shape[1], np_arr.shape[0])
44+
res = Array(np_arr.ctypes.data, shape, np_arr.dtype.char)
45+
return reorder(res, 1, 0)
46+
elif np_arr.ndim == 3:
47+
shape = (np_arr.shape[2], np_arr.shape[1], np_arr.shape[0])
48+
res = Array(np_arr.ctypes.data, shape, np_arr.dtype.char)
49+
return reorder(res, 2, 1, 0)
50+
elif np_arr.ndim == 4:
51+
shape = (np_arr.shape[3], np_arr.shape[2], np_arr.shape[1], np_arr.shape[0])
52+
res = Array(np_arr.ctypes.data, shape, np_arr.dtype.char)
53+
return reorder(res, 3, 2, 1, 0)
54+
else:
55+
raise RuntimeError("Unsupported ndim")
56+
else:
57+
return np_to_af_array(np.ascontiguousarray(np_arr))
58+
except:
59+
AF_NP_FOUND=False

0 commit comments

Comments
 (0)