Array Utilities#

Array utilities for handling NumPy, CuPy, and PyTorch arrays uniformly.

This module provides utilities to convert arrays from different backends into NumPy arrays for widget processing.

quantem.widget.array_utils.get_array_backend(data: Any) Literal['numpy', 'cupy', 'torch', 'unknown'][source]#

Detect the array backend of the input data.

Parameters:

data (array-like) – Input array (NumPy, CuPy, PyTorch, or other).

Returns:

One of: “numpy”, “cupy”, “torch”, “unknown”

Return type:

str

quantem.widget.array_utils.to_numpy(data: Any, dtype: dtype | None = None) ndarray[source]#

Convert any array-like (NumPy, CuPy, PyTorch) to a NumPy array.

Parameters:
  • data (array-like) – Input array from any supported backend.

  • dtype (np.dtype, optional) – Target dtype for the output array. If None, preserves original dtype.

Returns:

NumPy array with the same data.

Return type:

np.ndarray

Examples

>>> import numpy as np
>>> from quantem.widget.array_utils import to_numpy
>>>
>>> # NumPy passthrough
>>> arr = np.random.rand(10, 10)
>>> result = to_numpy(arr)
>>>
>>> # CuPy conversion (if available)
>>> import cupy as cp
>>> gpu_arr = cp.random.rand(10, 10)
>>> cpu_arr = to_numpy(gpu_arr)
>>>
>>> # PyTorch conversion (if available)
>>> import torch
>>> tensor = torch.rand(10, 10)
>>> arr = to_numpy(tensor)