Source code for buffalo_core.numeric

"""Shared numeric normalization helpers."""

from __future__ import annotations

import numpy as np

from buffalo_core.typing import FloatArray, FloatInput, IntArray, IntInput

__all__ = [
    "as_float_array",
    "as_float_scalar",
    "as_int_array",
    "as_int_scalar",
]


[docs] def as_float_array(value: FloatInput) -> FloatArray: """ Normalize numeric input to a ``float64`` NumPy array. Parameters ---------- value : FloatInput Scalar, sequence, or NumPy floating input to normalize. Returns ------- FloatArray NumPy array with ``float64`` dtype containing the normalized values. Notes ----- This helper is intended for function-boundary normalization in public and shared numeric APIs. It preserves the broadcastable NumPy array form expected by vectorized downstream code. """ return np.asarray(value, dtype=np.float64)
[docs] def as_float_scalar(value: FloatInput) -> float: """ Normalize a scalar-like numeric value to a Python ``float``. Parameters ---------- value : FloatInput Scalar-like numeric input expected to contain exactly one value. Returns ------- float Python ``float`` extracted from the normalized input. Notes ----- This helper is useful at third-party boundaries and other scalar-only interfaces that require a native Python float rather than a NumPy scalar or one-element array. """ return float(as_float_array(value).item())
[docs] def as_int_array(value: IntInput) -> IntArray: """ Normalize numeric input to an ``int32`` NumPy array. Parameters ---------- value : IntInput Scalar, sequence, or NumPy integer input to normalize. Returns ------- IntArray NumPy array with ``int32`` dtype containing the normalized values. Notes ----- This helper is intended for function-boundary normalization in public and shared numeric APIs. It produces the stable integer array form used throughout Buffalo Core. """ return np.asarray(value, dtype=np.int32)
[docs] def as_int_scalar(value: IntInput) -> int: """ Normalize a scalar-like numeric value to a Python ``int``. Parameters ---------- value : IntInput Scalar-like numeric input expected to contain exactly one value. Returns ------- int Python ``int`` extracted from the normalized input. Notes ----- This helper is useful at third-party boundaries and other scalar-only interfaces that require a native Python int rather than a NumPy scalar or one-element array. """ return int(as_int_array(value).item())