Skip to content

Utils

pynapple.core.utils

Utility functions

convert_to_numpy_array

convert_to_numpy_array(array, array_name)

Convert any array like object to numpy ndarray.

Parameters:

Name Type Description Default
array ArrayLike
required

array_name : str Array name if RuntimeError is raised

Returns:

Type Description
ndarray

Numpy array object

Raises:

Type Description
RuntimeError

If input can't be converted to numpy array

Source code in pynapple/core/utils.py
def convert_to_numpy_array(array, array_name):
    """Convert any array like object to numpy ndarray.

    Parameters
    ----------
    array : ArrayLike

    array_name : str
        Array name if RuntimeError is raised

    Returns
    -------
    numpy.ndarray
        Numpy array object

    Raises
    ------
    RuntimeError
        If input can't be converted to numpy array
    """
    if isinstance(array, Number):
        return np.array([array])
    elif isinstance(array, (list, tuple)):
        return np.array(array)
    elif isinstance(array, np.ndarray):
        return array
    elif is_array_like(array):
        return cast_to_numpy(array, array_name)
    else:
        raise RuntimeError(
            "Unknown format for {}. Accepted formats are numpy.ndarray, list, tuple or any array-like objects.".format(
                array_name
            )
        )

get_backend

get_backend()

Return the current backend of pynapple. Possible backends are 'numba' or 'jax'.

Source code in pynapple/core/utils.py
def get_backend():
    """
    Return the current backend of pynapple. Possible backends are
    'numba' or 'jax'.
    """
    return nap_config.backend

is_array_like

is_array_like(obj)

Check if an object is array-like.

This function determines if an object has array-like properties. An object is considered array-like if it has attributes typically associated with arrays (such as .shape, .dtype, and .ndim), supports indexing, and is iterable.

Parameters:

Name Type Description Default
obj object

The object to check for array-like properties.

required

Returns:

Type Description
bool

True if the object is array-like, False otherwise.

Notes

This function uses a combination of checks for attributes (shape, dtype, ndim), indexability, and iterability to determine if the given object behaves like an array. It is designed to be flexible and work with various types of array-like objects, including but not limited to NumPy arrays and JAX arrays. However, it may not be full proof for all possible array-like types or objects that mimic these properties without being suitable for numerical operations.

Source code in pynapple/core/utils.py
def is_array_like(obj):
    """
    Check if an object is array-like.

    This function determines if an object has array-like properties.
    An object is considered array-like if it has attributes typically associated with arrays
    (such as `.shape`, `.dtype`, and `.ndim`), supports indexing, and is iterable.

    Parameters
    ----------
    obj : object
        The object to check for array-like properties.

    Returns
    -------
    bool
        True if the object is array-like, False otherwise.

    Notes
    -----
    This function uses a combination of checks for attributes (`shape`, `dtype`, `ndim`),
    indexability, and iterability to determine if the given object behaves like an array.
    It is designed to be flexible and work with various types of array-like objects, including
    but not limited to NumPy arrays and JAX arrays. However, it may not be full proof for all
    possible array-like types or objects that mimic these properties without being suitable for
    numerical operations.

    """
    # Check for array-like attributes
    has_shape = hasattr(obj, "shape")
    has_dtype = hasattr(obj, "dtype")
    has_ndim = hasattr(obj, "ndim")

    # Check for indexability (try to access the first element)
    try:
        obj[0]
        is_indexable = True
    except Exception:
        is_indexable = False

    # Check for iterable property
    try:
        iter(obj)
        is_iterable = True
    except Exception:
        is_iterable = False

    # not_tsd_type = not isinstance(obj, _AbstractTsd)

    return (
        has_shape
        and has_dtype
        and has_ndim
        and is_indexable
        and is_iterable
        # and not_tsd_type
    )

cast_to_numpy

cast_to_numpy(array, array_name)

Convert an input array-like object to a NumPy array.

This function attempts to convert an input object to a NumPy array using np.asarray. If the input is not already a NumPy ndarray, it issues a warning indicating that a conversion has taken place and shows the original type of the input. This function is useful for ensuring compatibility with Numba operations in cases where the input might come from various array-like sources (for instance, jax.numpy.Array).

Parameters:

Name Type Description Default
array array_like

The input object to convert. This can be any object that np.asarray is capable of converting to a NumPy array, such as lists, tuples, and other array-like objects, including those from libraries like JAX or TensorFlow that adhere to the array interface.

required
array_name str

The name of the variable that we are converting, printed in the warning message.

required

Returns:

Type Description
ndarray

A NumPy ndarray representation of the input values. If values is already a NumPy ndarray, it is returned unchanged. Otherwise, a new NumPy ndarray is created and returned.

Warnings

A warning is issued if the input values is not already a NumPy ndarray, indicating that a conversion has taken place and showing the original type of the input.

Source code in pynapple/core/utils.py
def cast_to_numpy(array, array_name):
    """
    Convert an input array-like object to a NumPy array.

    This function attempts to convert an input object to a NumPy array using `np.asarray`.
    If the input is not already a NumPy ndarray, it issues a warning indicating that a conversion
    has taken place and shows the original type of the input. This function is useful for
    ensuring compatibility with Numba operations in cases where the input might come from
    various array-like sources (for instance, jax.numpy.Array).

    Parameters
    ----------
    array : array_like
        The input object to convert. This can be any object that `np.asarray` is capable of
        converting to a NumPy array, such as lists, tuples, and other array-like objects,
        including those from libraries like JAX or TensorFlow that adhere to the array interface.
    array_name : str
        The name of the variable that we are converting, printed in the warning message.

    Returns
    -------
    ndarray
        A NumPy ndarray representation of the input `values`. If `values` is already a NumPy
        ndarray, it is returned unchanged. Otherwise, a new NumPy ndarray is created and returned.

    Warnings
    --------
    A warning is issued if the input `values` is not already a NumPy ndarray, indicating
    that a conversion has taken place and showing the original type of the input.

    """
    if (
        not isinstance(array, np.ndarray)
        and not nap_config.suppress_conversion_warnings
    ):
        original_type = type(array).__name__
        warnings.warn(
            f"Converting '{array_name}' to numpy.array. The provided array was of type '{original_type}'.",
            UserWarning,
        )
    return np.asarray(array)