|
| 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