Skip to content

array_typing.numpy._utils

Functions:

as_dict_of_numpy

as_dict_of_numpy(
    obj: Mapping[str, ArrayLike] | None
) -> dict[str, ndarray]
Source code in src/array_typing/numpy/_utils/_as_numpy.py
19
20
21
22
def as_dict_of_numpy(obj: Mapping[str, at.ArrayLike] | None) -> dict[str, np.ndarray]:
    if obj is None:
        return {}
    return {k: at.as_numpy(v) for k, v in obj.items()}

as_dtype

as_dtype(x: ArrayLike, dtype: DTypeLike) -> NDArray[...]
Source code in src/array_typing/numpy/_utils/_as_dtype.py
 9
10
11
12
13
14
15
16
17
18
19
20
def as_dtype(x: npt.ArrayLike, dtype: npt.DTypeLike) -> npt.NDArray[...]:
    x: npt.NDArray = tn.as_numpy(x)
    dtype: np.dtype = np.dtype(dtype)
    if np.issubdtype(x.dtype, dtype):
        return x
    if np.isdtype(dtype, "bool"):
        if np.ptp(x) > 0:
            return x > np.median(x)
        return x > 0.5
    if np.isdtype(dtype, "integral"):
        x = np.rint(x)
    return x.astype(dtype)

as_numpy

as_numpy(obj: Any) -> ndarray
Source code in src/array_typing/numpy/_utils/_as_numpy.py
11
12
13
14
15
16
def as_numpy(obj: Any) -> np.ndarray:
    if at.is_numpy(obj):
        return obj
    if at.is_torch(obj):
        return obj.numpy(force=True)
    return np.asarray(obj)

is_numpy

is_numpy(obj: Any) -> TypeGuard[ndarray]
Source code in src/array_typing/numpy/_utils/_is.py
10
11
def is_numpy(obj: Any) -> TypeGuard[np.ndarray]:
    return at.is_instance_named_partial(obj, "numpy.ndarray")

scale

scale(x: ArrayLike, a: float = 0, b: float = 1) -> NDArray
Source code in src/array_typing/numpy/_utils/_scale.py
 9
10
11
12
13
def scale(x: npt.ArrayLike, a: float = 0, b: float = 1) -> npt.NDArray:
    x: npt.NDArray[...] = tn.as_numpy(x)
    x = (x - x.min()) / np.ptp(x)
    x = x * (b - a) + a
    return x