dpnp.diag

dpnp.diag(v, /, k=0, *, device=None, usm_type=None, sycl_queue=None)[source]

Extract a diagonal or construct a diagonal array.

For full documentation refer to numpy.diag.

Parameters:
  • v (array_like) --

    Input data, in any form that can be converted to an array. This includes scalars, lists, lists of tuples, tuples, tuples of tuples, tuples of lists, and ndarrays. If v is a 1-D array, return a 2-D array with v on the k-th diagonal. If v is a 2-D array and is an instance of {dpnp.ndarray, usm_ndarray}, then:

    • If device, usm_type, and sycl_queue are set to their default values, returns a read/write view of its k-th diagonal.

    • Otherwise, returns a copy of its k-th diagonal.

  • k (int, optional) -- Diagonal in question. Use k > 0 for diagonals above the main diagonal, and k < 0 for diagonals below the main diagonal. Default: 0.

  • device ({None, string, SyclDevice, SyclQueue}, optional) -- An array API concept of device where the output array is created. The device can be None (the default), an OneAPI filter selector string, an instance of dpctl.SyclDevice corresponding to a non-partitioned SYCL device, an instance of dpctl.SyclQueue, or a Device object returned by dpnp.dpnp_array.dpnp_array.device property.

  • usm_type ({None, "device", "shared", "host"}, optional) -- The type of SYCL USM allocation for the output array. Default: None.

  • sycl_queue ({None, SyclQueue}, optional) -- A SYCL queue to use for output array allocation and copying. The sycl_queue can be passed as None (the default), which means to get the SYCL queue from device keyword if present or to use a default queue. Default: None.

Returns:

out -- The extracted diagonal or constructed diagonal array.

Return type:

dpnp.ndarray

See also

diagonal

Return specified diagonals.

diagflat

Create a 2-D array with the flattened input as a diagonal.

trace

Return the sum along diagonals of the array.

triu

Upper triangle of an array.

tril

Lower triangle of an array.

Examples

>>> import dpnp as np
>>> x = np.arange(9).reshape((3, 3))
>>> x
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.diag(x)
array([0, 4, 8])
>>> np.diag(x, k=1)
array([1, 5])
>>> np.diag(x, k=-1)
array([3, 7])
>>> np.diag(np.diag(x))
array([[0, 0, 0],
       [0, 4, 0],
       [0, 0, 8]])

Creating an array on a different device or with a specified usm_type

>>> res = np.diag(x) # default case
>>> res, res.device, res.usm_type
(array([0, 4, 8]), Device(level_zero:gpu:0), 'device')
>>> res_cpu = np.diag(x, device="cpu")
>>> res_cpu, res_cpu.device, res_cpu.usm_type
(array([0, 4, 8]), Device(opencl:cpu:0), 'device')
>>> res_host = np.diag(x, usm_type="host")
>>> res_host, res_host.device, res_host.usm_type
(array([0, 4, 8]), Device(level_zero:gpu:0), 'host')