File: datatypes.py

package info (click to toggle)
python-sigima 1.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 24,956 kB
  • sloc: python: 33,326; makefile: 3
file content (26 lines) | stat: -rw-r--r-- 806 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.

"""
.. Data Type Conversion Algorithms (see parent package :mod:`sigima.algorithms`)
"""

from __future__ import annotations

import numpy as np


def clip_astype(data: np.ndarray, dtype: np.dtype) -> np.ndarray:
    """Convert array to a new data type, after having clipped values to the new
    data type's range if it is an integer type.
    If data type is not integer, this is equivalent to ``data.astype(dtype)``.

    Args:
        data: Array to convert
        dtype: Data type to convert to

    Returns:
        Array converted to new data type
    """
    if np.issubdtype(dtype, np.integer):
        return np.clip(data, np.iinfo(dtype).min, np.iinfo(dtype).max).astype(dtype)
    return data.astype(dtype)