Array creation#
Introduction#
Currently, there are 3 general mechanisms for creating CrossPy arrays:
Conversion from a mixture of NumPy-compatible arrays or other Python sequences (i.e. lists and tuples)
Intrinsic CrossPy array creation functions (e.g. arange, ones, zeros, etc.)
Use of special library functions (e.g., random)
We start with importing the CrossPy library, as well as NumPy and CuPy for demostration.
import crosspy as xp
import numpy as np
import cupy as cp
1) Converting NumPy-compatible arrays or Python sequences to CrossPy Arrays#
Heterogeneous CrossPy arrays can be defined using a sequence of NumPy-compatible arrays. These arrays can be on different devices.
We create a NumPy array and a CuPy and then merge them into a CrossPy array.
a = np.array([1, 2, 3])
b = cp.array([4, 5])
x = xp.array([a, b], axis=0)
x
array([1, 2, 3])@<CPU 0>; array([4, 5])@<CUDA Device 0>
axis=0
{l=python} specifies that the input object (i.e. the list) should be “concatenated” along the first axis.
a.shape
b.shape
x.shape
(5,)
Note that the dtype of the components should match.
>>> x = xp.array([np.array([1, 2], dtype=np.int32), cp.array([3, 4], dtype=cp.int64)], axis=0)
Traceback (most recent call last):
...
ValueError: Incompatible shapes with 2 different dims
x.device
[<CPU 0>, <CUDA Device 0>]
# xp.array([x_cpu, x_cpu.T])