Skip to content

toolkit.array.numpy._utils

Functions:

as_dict_of_numpy

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

as_dtype

as_dtype(x: Annotated[ndarray, Numpy], dtype: Annotated[dtype, BeforeValidator(dtype)]) -> NDArray[...]
Source code in src/toolkit/array/numpy/_utils/_as_dtype.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@pydantic.validate_call
def as_dtype(
    x: Annotated[np.ndarray, tv.Numpy],
    dtype: Annotated[np.dtype, pydantic.BeforeValidator(np.dtype)],
) -> npt.NDArray[...]:
    if np.issubdtype(x.dtype, dtype):
        return x
    if np.isdtype(dtype, "bool"):
        if np.ptp(x) > 0:
            x = tk.array.numpy.scale(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/toolkit/array/numpy/_utils/_as_numpy.py
12
13
14
15
16
17
def as_numpy(obj: Any) -> np.ndarray:
    if tk.is_numpy(obj):
        return obj
    if tk.is_torch(obj):
        return obj.numpy(force=True)
    return np.asarray(obj)

is_numpy

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

scale

scale(x: Annotated[ndarray, Numpy], a: float = 0, b: float = 1) -> ndarray
Source code in src/toolkit/array/numpy/_utils/_scale.py
11
12
13
14
15
@pydantic.validate_call
def scale(x: Annotated[np.ndarray, tv.Numpy], a: float = 0, b: float = 1) -> np.ndarray:
    x = (x - x.min()) / np.ptp(x)
    x = x * (b - a) + a
    return x