diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi index 7f6bd9db55a4..527f71d897ee 100644 --- a/numpy/__init__.pyi +++ b/numpy/__init__.pyi @@ -574,6 +574,7 @@ from numpy.lib._polynomial_impl import ( from numpy.lib._shape_base_impl import ( column_stack, + row_stack, dstack, array_split, split, @@ -730,10 +731,9 @@ __all__ = [ # noqa: RUF022 "histogram2d", "mask_indices", "tril_indices", "tril_indices_from", "triu_indices", "triu_indices_from", # lib._shape_base_impl.__all__ - # NOTE: `row_stack` is omitted because it is deprecated "column_stack", "dstack", "array_split", "split", "hsplit", "vsplit", "dsplit", "apply_over_axes", "expand_dims", "apply_along_axis", "kron", "tile", - "take_along_axis", "put_along_axis", + "take_along_axis", "put_along_axis", "row_stack", # lib._type_check_impl.__all__ "iscomplexobj", "isrealobj", "imag", "iscomplex", "isreal", "nan_to_num", "real", "real_if_close", "typename", "mintypecode", "common_type", @@ -4803,6 +4803,17 @@ class ufunc: # outputs, so we can't type it very precisely. def at(self, /, *args: Any, **kwargs: Any) -> None: ... + # + def resolve_dtypes( + self, + /, + dtypes: tuple[dtype[Any] | type | None, ...], + *, + signature: tuple[dtype[Any] | None, ...] | None = None, + casting: _CastingKind | None = None, + reduction: builtins.bool = False, + ) -> tuple[dtype[Any], ...]: ... + # Parameters: `__name__`, `ntypes` and `identity` absolute: _UFunc_Nin1_Nout1[L['absolute'], L[20], None] add: _UFunc_Nin2_Nout1[L['add'], L[22], L[0]] diff --git a/numpy/_core/_add_newdocs.pyi b/numpy/_core/_add_newdocs.pyi new file mode 100644 index 000000000000..b23c3b1adedd --- /dev/null +++ b/numpy/_core/_add_newdocs.pyi @@ -0,0 +1,3 @@ +from .overrides import get_array_function_like_doc as get_array_function_like_doc + +def refer_to_array_attribute(attr: str, method: bool = True) -> tuple[str, str]: ... diff --git a/numpy/_core/_add_newdocs_scalars.pyi b/numpy/_core/_add_newdocs_scalars.pyi new file mode 100644 index 000000000000..4a06c9b07d74 --- /dev/null +++ b/numpy/_core/_add_newdocs_scalars.pyi @@ -0,0 +1,16 @@ +from collections.abc import Iterable +from typing import Final + +import numpy as np + +possible_aliases: Final[list[tuple[type[np.number], str, str]]] = ... +_system: Final[str] = ... +_machine: Final[str] = ... +_doc_alias_string: Final[str] = ... +_bool_docstring: Final[str] = ... +int_name: str = ... +float_name: str = ... + +def numeric_type_aliases(aliases: list[tuple[str, str]]) -> list[tuple[type[np.number], str, str]]: ... +def add_newdoc_for_scalar_type(obj: str, fixed_aliases: Iterable[str], doc: str) -> None: ... +def _get_platform_and_machine() -> tuple[str, str]: ... diff --git a/numpy/_core/_dtype.pyi b/numpy/_core/_dtype.pyi new file mode 100644 index 000000000000..c3e966e3f517 --- /dev/null +++ b/numpy/_core/_dtype.pyi @@ -0,0 +1,58 @@ +from typing import Any, Final, TypeAlias, TypedDict, overload, type_check_only +from typing import Literal as L + +from typing_extensions import ReadOnly, TypeVar + +import numpy as np + +### + +_T = TypeVar("_T") + +_Name: TypeAlias = L["uint", "int", "complex", "float", "bool", "void", "object", "datetime", "timedelta", "bytes", "str"] + +@type_check_only +class _KindToStemType(TypedDict): + u: ReadOnly[L["uint"]] + i: ReadOnly[L["int"]] + c: ReadOnly[L["complex"]] + f: ReadOnly[L["float"]] + b: ReadOnly[L["bool"]] + V: ReadOnly[L["void"]] + O: ReadOnly[L["object"]] + M: ReadOnly[L["datetime"]] + m: ReadOnly[L["timedelta"]] + S: ReadOnly[L["bytes"]] + U: ReadOnly[L["str"]] + +### + +_kind_to_stem: Final[_KindToStemType] = ... + +# +def _kind_name(dtype: np.dtype[Any]) -> _Name: ... +def __str__(dtype: np.dtype[Any]) -> str: ... +def __repr__(dtype: np.dtype[Any]) -> str: ... + +# +def _isunsized(dtype: np.dtype[Any]) -> bool: ... +def _is_packed(dtype: np.dtype[Any]) -> bool: ... +def _name_includes_bit_suffix(dtype: np.dtype[Any]) -> bool: ... + +# +def _construction_repr(dtype: np.dtype[Any], include_align: bool = False, short: bool = False) -> str: ... +def _scalar_str(dtype: np.dtype[Any], short: bool) -> str: ... +def _byte_order_str(dtype: np.dtype[Any]) -> str: ... +def _datetime_metadata_str(dtype: np.dtype[Any]) -> str: ... +def _struct_dict_str(dtype: np.dtype[Any], includealignedflag: bool) -> str: ... +def _struct_list_str(dtype: np.dtype[Any]) -> str: ... +def _struct_str(dtype: np.dtype[Any], include_align: bool) -> str: ... +def _subarray_str(dtype: np.dtype[Any]) -> str: ... +def _name_get(dtype: np.dtype[Any]) -> str: ... + +# +@overload +def _unpack_field(dtype: np.dtype[Any], offset: int, title: _T) -> tuple[np.dtype[Any], int, _T]: ... +@overload +def _unpack_field(dtype: np.dtype[Any], offset: int, title: None = None) -> tuple[np.dtype[Any], int, None]: ... +def _aligned_offset(offset: int, alignment: int) -> int: ... diff --git a/numpy/_core/_dtype_ctypes.pyi b/numpy/_core/_dtype_ctypes.pyi new file mode 100644 index 000000000000..69438a2c1b4c --- /dev/null +++ b/numpy/_core/_dtype_ctypes.pyi @@ -0,0 +1,83 @@ +import _ctypes +import ctypes as ct +from typing import Any, overload + +import numpy as np + +# +@overload +def dtype_from_ctypes_type(t: type[_ctypes.Array[Any] | _ctypes.Structure]) -> np.dtype[np.void]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_bool]) -> np.dtype[np.bool]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_int8 | ct.c_byte]) -> np.dtype[np.int8]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_uint8 | ct.c_ubyte]) -> np.dtype[np.uint8]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_int16 | ct.c_short]) -> np.dtype[np.int16]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_uint16 | ct.c_ushort]) -> np.dtype[np.uint16]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_int32 | ct.c_int]) -> np.dtype[np.int32]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_uint32 | ct.c_uint]) -> np.dtype[np.uint32]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_ssize_t | ct.c_long]) -> np.dtype[np.int32 | np.int64]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_size_t | ct.c_ulong]) -> np.dtype[np.uint32 | np.uint64]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_int64 | ct.c_longlong]) -> np.dtype[np.int64]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_uint64 | ct.c_ulonglong]) -> np.dtype[np.uint64]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_float]) -> np.dtype[np.float32]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_double]) -> np.dtype[np.float64]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_longdouble]) -> np.dtype[np.longdouble]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.c_char]) -> np.dtype[np.bytes_]: ... +@overload +def dtype_from_ctypes_type(t: type[ct.py_object[Any]]) -> np.dtype[np.object_]: ... + +# NOTE: the complex ctypes on python>=3.14 are not yet supported at runtim, see +# https://github.com/numpy/numpy/issues/28360 + +# +def _from_ctypes_array(t: type[_ctypes.Array[Any]]) -> np.dtype[np.void]: ... +def _from_ctypes_structure(t: type[_ctypes.Structure]) -> np.dtype[np.void]: ... +def _from_ctypes_union(t: type[_ctypes.Union]) -> np.dtype[np.void]: ... + +# keep in sync with `dtype_from_ctypes_type` (minus the first overload) +@overload +def _from_ctypes_scalar(t: type[ct.c_bool]) -> np.dtype[np.bool]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_int8 | ct.c_byte]) -> np.dtype[np.int8]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_uint8 | ct.c_ubyte]) -> np.dtype[np.uint8]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_int16 | ct.c_short]) -> np.dtype[np.int16]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_uint16 | ct.c_ushort]) -> np.dtype[np.uint16]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_int32 | ct.c_int]) -> np.dtype[np.int32]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_uint32 | ct.c_uint]) -> np.dtype[np.uint32]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_ssize_t | ct.c_long]) -> np.dtype[np.int32 | np.int64]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_size_t | ct.c_ulong]) -> np.dtype[np.uint32 | np.uint64]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_int64 | ct.c_longlong]) -> np.dtype[np.int64]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_uint64 | ct.c_ulonglong]) -> np.dtype[np.uint64]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_float]) -> np.dtype[np.float32]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_double]) -> np.dtype[np.float64]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_longdouble]) -> np.dtype[np.longdouble]: ... +@overload +def _from_ctypes_scalar(t: type[ct.c_char]) -> np.dtype[np.bytes_]: ... +@overload +def _from_ctypes_scalar(t: type[ct.py_object[Any]]) -> np.dtype[np.object_]: ... diff --git a/numpy/_core/_exceptions.pyi b/numpy/_core/_exceptions.pyi new file mode 100644 index 000000000000..5abfc779c212 --- /dev/null +++ b/numpy/_core/_exceptions.pyi @@ -0,0 +1,73 @@ +from collections.abc import Iterable +from typing import Any, Final, overload + +from typing_extensions import TypeVar, Unpack + +import numpy as np +from numpy import _CastingKind +from numpy._utils import set_module as set_module + +### + +_T = TypeVar("_T") +_TupleT = TypeVar("_TupleT", bound=tuple[()] | tuple[Any, Any, Unpack[tuple[Any, ...]]]) +_ExceptionT = TypeVar("_ExceptionT", bound=Exception) + +### + +class UFuncTypeError(TypeError): + ufunc: Final[np.ufunc] + def __init__(self, /, ufunc: np.ufunc) -> None: ... + +class _UFuncNoLoopError(UFuncTypeError): + dtypes: tuple[np.dtype[Any], ...] + def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ... + +class _UFuncBinaryResolutionError(_UFuncNoLoopError): + dtypes: tuple[np.dtype[Any], np.dtype[Any]] + def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ... + +class _UFuncCastingError(UFuncTypeError): + casting: Final[_CastingKind] + from_: Final[np.dtype[Any]] + to: Final[np.dtype[Any]] + def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype[Any], to: np.dtype[Any]) -> None: ... + +class _UFuncInputCastingError(_UFuncCastingError): + in_i: Final[int] + def __init__( + self, + /, + ufunc: np.ufunc, + casting: _CastingKind, + from_: np.dtype[Any], + to: np.dtype[Any], + i: int, + ) -> None: ... + +class _UFuncOutputCastingError(_UFuncCastingError): + out_i: Final[int] + def __init__( + self, + /, + ufunc: np.ufunc, + casting: _CastingKind, + from_: np.dtype[Any], + to: np.dtype[Any], + i: int, + ) -> None: ... + +class _ArrayMemoryError(MemoryError): + shape: tuple[int, ...] + dtype: np.dtype[Any] + def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype[Any]) -> None: ... + @property + def _total_size(self) -> int: ... + @staticmethod + def _size_to_string(num_bytes: int) -> str: ... + +@overload +def _unpack_tuple(tup: tuple[_T]) -> _T: ... +@overload +def _unpack_tuple(tup: _TupleT) -> _TupleT: ... +def _display_as_base(cls: type[_ExceptionT]) -> type[_ExceptionT]: ... diff --git a/numpy/_core/_machar.pyi b/numpy/_core/_machar.pyi new file mode 100644 index 000000000000..5abfc779c212 --- /dev/null +++ b/numpy/_core/_machar.pyi @@ -0,0 +1,73 @@ +from collections.abc import Iterable +from typing import Any, Final, overload + +from typing_extensions import TypeVar, Unpack + +import numpy as np +from numpy import _CastingKind +from numpy._utils import set_module as set_module + +### + +_T = TypeVar("_T") +_TupleT = TypeVar("_TupleT", bound=tuple[()] | tuple[Any, Any, Unpack[tuple[Any, ...]]]) +_ExceptionT = TypeVar("_ExceptionT", bound=Exception) + +### + +class UFuncTypeError(TypeError): + ufunc: Final[np.ufunc] + def __init__(self, /, ufunc: np.ufunc) -> None: ... + +class _UFuncNoLoopError(UFuncTypeError): + dtypes: tuple[np.dtype[Any], ...] + def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ... + +class _UFuncBinaryResolutionError(_UFuncNoLoopError): + dtypes: tuple[np.dtype[Any], np.dtype[Any]] + def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ... + +class _UFuncCastingError(UFuncTypeError): + casting: Final[_CastingKind] + from_: Final[np.dtype[Any]] + to: Final[np.dtype[Any]] + def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype[Any], to: np.dtype[Any]) -> None: ... + +class _UFuncInputCastingError(_UFuncCastingError): + in_i: Final[int] + def __init__( + self, + /, + ufunc: np.ufunc, + casting: _CastingKind, + from_: np.dtype[Any], + to: np.dtype[Any], + i: int, + ) -> None: ... + +class _UFuncOutputCastingError(_UFuncCastingError): + out_i: Final[int] + def __init__( + self, + /, + ufunc: np.ufunc, + casting: _CastingKind, + from_: np.dtype[Any], + to: np.dtype[Any], + i: int, + ) -> None: ... + +class _ArrayMemoryError(MemoryError): + shape: tuple[int, ...] + dtype: np.dtype[Any] + def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype[Any]) -> None: ... + @property + def _total_size(self) -> int: ... + @staticmethod + def _size_to_string(num_bytes: int) -> str: ... + +@overload +def _unpack_tuple(tup: tuple[_T]) -> _T: ... +@overload +def _unpack_tuple(tup: _TupleT) -> _TupleT: ... +def _display_as_base(cls: type[_ExceptionT]) -> type[_ExceptionT]: ... diff --git a/numpy/_core/_methods.pyi b/numpy/_core/_methods.pyi new file mode 100644 index 000000000000..45e2b8b9f761 --- /dev/null +++ b/numpy/_core/_methods.pyi @@ -0,0 +1,24 @@ +from collections.abc import Callable +from typing import Any, TypeAlias + +from typing_extensions import Concatenate + +import numpy as np + +from . import _exceptions as _exceptions + +### + +_Reduce2: TypeAlias = Callable[Concatenate[object, ...], Any] + +### + +bool_dt: np.dtype[np.bool] = ... +umr_maximum: _Reduce2 = ... +umr_minimum: _Reduce2 = ... +umr_sum: _Reduce2 = ... +umr_prod: _Reduce2 = ... +umr_bitwise_count = np.bitwise_count +umr_any: _Reduce2 = ... +umr_all: _Reduce2 = ... +_complex_to_float: dict[np.dtype[np.complexfloating], np.dtype[np.floating]] = ... diff --git a/numpy/_core/_simd.pyi b/numpy/_core/_simd.pyi new file mode 100644 index 000000000000..70bb7077797e --- /dev/null +++ b/numpy/_core/_simd.pyi @@ -0,0 +1,25 @@ +from types import ModuleType +from typing import TypedDict, type_check_only + +# NOTE: these 5 are only defined on systems with an intel processor +SSE42: ModuleType | None = ... +FMA3: ModuleType | None = ... +AVX2: ModuleType | None = ... +AVX512F: ModuleType | None = ... +AVX512_SKX: ModuleType | None = ... + +baseline: ModuleType | None = ... + +@type_check_only +class SimdTargets(TypedDict): + SSE42: ModuleType | None + AVX2: ModuleType | None + FMA3: ModuleType | None + AVX512F: ModuleType | None + AVX512_SKX: ModuleType | None + baseline: ModuleType | None + +targets: SimdTargets = ... + +def clear_floatstatus() -> None: ... +def get_floatstatus() -> int: ... diff --git a/numpy/_core/_string_helpers.pyi b/numpy/_core/_string_helpers.pyi new file mode 100644 index 000000000000..6a85832b7a93 --- /dev/null +++ b/numpy/_core/_string_helpers.pyi @@ -0,0 +1,12 @@ +from typing import Final + +_all_chars: Final[tuple[str, ...]] = ... +_ascii_upper: Final[tuple[str, ...]] = ... +_ascii_lower: Final[tuple[str, ...]] = ... + +LOWER_TABLE: Final[tuple[str, ...]] = ... +UPPER_TABLE: Final[tuple[str, ...]] = ... + +def english_lower(s: str) -> str: ... +def english_upper(s: str) -> str: ... +def english_capitalize(s: str) -> str: ... diff --git a/numpy/_core/fromnumeric.pyi b/numpy/_core/fromnumeric.pyi index f7207db17b0c..3de05f3db362 100644 --- a/numpy/_core/fromnumeric.pyi +++ b/numpy/_core/fromnumeric.pyi @@ -108,7 +108,6 @@ __all__ = [ _SCT = TypeVar("_SCT", bound=generic) _SCT_uifcO = TypeVar("_SCT_uifcO", bound=number[Any] | object_) _ArrayT = TypeVar("_ArrayT", bound=np.ndarray[Any, Any]) -_SizeType = TypeVar("_SizeType", bound=int) _ShapeType = TypeVar("_ShapeType", bound=tuple[int, ...]) _ShapeType_co = TypeVar("_ShapeType_co", bound=tuple[int, ...], covariant=True) @@ -456,23 +455,19 @@ def searchsorted( sorter: _ArrayLikeInt_co | None = ..., # 1D int array ) -> NDArray[intp]: ... -# unlike `reshape`, `resize` only accepts positive integers, so literal ints can be used +# @overload -def resize(a: _ArrayLike[_SCT], new_shape: _SizeType) -> np.ndarray[tuple[_SizeType], np.dtype[_SCT]]: ... +def resize(a: _ArrayLike[_SCT], new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype[_SCT]]: ... @overload -def resize(a: _ArrayLike[_SCT], new_shape: SupportsIndex) -> np.ndarray[tuple[int], np.dtype[_SCT]]: ... +def resize(a: _ArrayLike[_SCT], new_shape: _AnyShapeType) -> np.ndarray[_AnyShapeType, np.dtype[_SCT]]: ... @overload -def resize(a: _ArrayLike[_SCT], new_shape: _ShapeType) -> np.ndarray[_ShapeType, np.dtype[_SCT]]: ... +def resize(a: _ArrayLike[_SCT], new_shape: _ShapeLike) -> NDArray[_SCT]: ... @overload -def resize(a: _ArrayLike[_SCT], new_shape: Sequence[SupportsIndex]) -> NDArray[_SCT]: ... +def resize(a: ArrayLike, new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype[Any]]: ... @overload -def resize(a: ArrayLike, new_shape: _SizeType) -> np.ndarray[tuple[_SizeType], np.dtype[Any]]: ... +def resize(a: ArrayLike, new_shape: _AnyShapeType) -> np.ndarray[_AnyShapeType, np.dtype[Any]]: ... @overload -def resize(a: ArrayLike, new_shape: SupportsIndex) -> np.ndarray[tuple[int], np.dtype[Any]]: ... -@overload -def resize(a: ArrayLike, new_shape: _ShapeType) -> np.ndarray[_ShapeType, np.dtype[Any]]: ... -@overload -def resize(a: ArrayLike, new_shape: Sequence[SupportsIndex]) -> NDArray[Any]: ... +def resize(a: ArrayLike, new_shape: _ShapeLike) -> NDArray[Any]: ... @overload def squeeze( diff --git a/numpy/_core/meson.build b/numpy/_core/meson.build index ec40c290f59a..6b6fbd3490ae 100644 --- a/numpy/_core/meson.build +++ b/numpy/_core/meson.build @@ -1290,17 +1290,26 @@ python_sources = [ '__init__.py', '__init__.pyi', '_add_newdocs.py', + '_add_newdocs.pyi', '_add_newdocs_scalars.py', + '_add_newdocs_scalars.pyi', '_asarray.py', '_asarray.pyi', '_dtype.py', + '_dtype.pyi', '_dtype_ctypes.py', + '_dtype_ctypes.pyi', '_exceptions.py', + '_exceptions.pyi', '_internal.py', '_internal.pyi', '_machar.py', + '_machar.pyi', '_methods.py', + '_methods.pyi', + '_simd.pyi', '_string_helpers.py', + '_string_helpers.pyi', '_type_aliases.py', '_type_aliases.pyi', '_ufunc_config.py', @@ -1327,7 +1336,9 @@ python_sources = [ 'numerictypes.py', 'numerictypes.pyi', 'overrides.py', + 'overrides.pyi', 'printoptions.py', + 'printoptions.pyi', 'records.py', 'records.pyi', 'shape_base.py', diff --git a/numpy/_core/multiarray.pyi b/numpy/_core/multiarray.pyi index 28cf5411645f..b656472dfec7 100644 --- a/numpy/_core/multiarray.pyi +++ b/numpy/_core/multiarray.pyi @@ -49,6 +49,7 @@ from numpy import ( # type: ignore[attr-defined] signedinteger, floating, complexfloating, + _AnyShapeType, _OrderKACF, _OrderCF, _CastingKind, @@ -191,8 +192,6 @@ __all__ = [ "zeros", ] -_T_co = TypeVar("_T_co", covariant=True) -_T_contra = TypeVar("_T_contra", contravariant=True) _SCT = TypeVar("_SCT", bound=generic) _DType = TypeVar("_DType", bound=np.dtype[Any]) _ArrayType = TypeVar("_ArrayType", bound=ndarray[Any, Any]) @@ -206,10 +205,9 @@ _IDType = TypeVar("_IDType") _Nin = TypeVar("_Nin", bound=int) _Nout = TypeVar("_Nout", bound=int) -_SizeType = TypeVar("_SizeType", bound=int) -_ShapeType = TypeVar("_ShapeType", bound=tuple[int, ...]) -_1DArray: TypeAlias = ndarray[tuple[_SizeType], dtype[_SCT]] -_Array: TypeAlias = ndarray[_ShapeType, dtype[_SCT]] +_ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...]) +_Array: TypeAlias = ndarray[_ShapeT, dtype[_SCT]] +_Array1D: TypeAlias = ndarray[tuple[int], dtype[_SCT]] # Valid time units _UnitKind: TypeAlias = L[ @@ -250,70 +248,78 @@ class _ConstructorEmpty(Protocol): # 1-D shape @overload def __call__( - self, /, - shape: _SizeType, + self, + /, + shape: SupportsIndex, dtype: None = ..., order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], - ) -> _Array[tuple[_SizeType], float64]: ... + ) -> _Array1D[float64]: ... @overload def __call__( - self, /, - shape: _SizeType, + self, + /, + shape: SupportsIndex, dtype: _DType | _SupportsDType[_DType], order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], - ) -> ndarray[tuple[_SizeType], _DType]: ... + ) -> ndarray[tuple[int], _DType]: ... @overload def __call__( - self, /, - shape: _SizeType, + self, + /, + shape: SupportsIndex, dtype: type[_SCT], order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], - ) -> _Array[tuple[_SizeType], _SCT]: ... + ) -> _Array1D[_SCT]: ... @overload def __call__( - self, /, - shape: _SizeType, + self, + /, + shape: SupportsIndex, dtype: DTypeLike, order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], - ) -> _Array[tuple[_SizeType], Any]: ... + ) -> _Array1D[Any]: ... # known shape @overload def __call__( - self, /, - shape: _ShapeType, + self, + /, + shape: _AnyShapeType, dtype: None = ..., order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], - ) -> _Array[_ShapeType, float64]: ... + ) -> _Array[_AnyShapeType, float64]: ... @overload def __call__( - self, /, - shape: _ShapeType, + self, + /, + shape: _AnyShapeType, dtype: _DType | _SupportsDType[_DType], order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], - ) -> ndarray[_ShapeType, _DType]: ... + ) -> ndarray[_AnyShapeType, _DType]: ... @overload def __call__( - self, /, - shape: _ShapeType, + self, + /, + shape: _AnyShapeType, dtype: type[_SCT], order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], - ) -> _Array[_ShapeType, _SCT]: ... + ) -> _Array[_AnyShapeType, _SCT]: ... @overload def __call__( - self, /, - shape: _ShapeType, + self, + /, + shape: _AnyShapeType, dtype: DTypeLike, order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], - ) -> _Array[_ShapeType, Any]: ... + ) -> _Array[_AnyShapeType, Any]: ... # unknown shape @overload @@ -1036,7 +1042,7 @@ def arange( # type: ignore[misc] dtype: None = ..., device: None | L["cpu"] = ..., like: None | _SupportsArrayFunc = ..., -) -> _1DArray[int, signedinteger[Any]]: ... +) -> _Array1D[signedinteger]: ... @overload def arange( # type: ignore[misc] start: _IntLike_co, @@ -1046,7 +1052,7 @@ def arange( # type: ignore[misc] *, device: None | L["cpu"] = ..., like: None | _SupportsArrayFunc = ..., -) -> _1DArray[int, signedinteger[Any]]: ... +) -> _Array1D[signedinteger]: ... @overload def arange( # type: ignore[misc] stop: _FloatLike_co, @@ -1054,7 +1060,7 @@ def arange( # type: ignore[misc] dtype: None = ..., device: None | L["cpu"] = ..., like: None | _SupportsArrayFunc = ..., -) -> _1DArray[int, floating[Any]]: ... +) -> _Array1D[floating]: ... @overload def arange( # type: ignore[misc] start: _FloatLike_co, @@ -1064,7 +1070,7 @@ def arange( # type: ignore[misc] *, device: None | L["cpu"] = ..., like: None | _SupportsArrayFunc = ..., -) -> _1DArray[int, floating[Any]]: ... +) -> _Array1D[floating]: ... @overload def arange( stop: _TD64Like_co, @@ -1072,7 +1078,7 @@ def arange( dtype: None = ..., device: None | L["cpu"] = ..., like: None | _SupportsArrayFunc = ..., -) -> _1DArray[int, timedelta64]: ... +) -> _Array1D[timedelta64]: ... @overload def arange( start: _TD64Like_co, @@ -1082,7 +1088,7 @@ def arange( *, device: None | L["cpu"] = ..., like: None | _SupportsArrayFunc = ..., -) -> _1DArray[int, timedelta64]: ... +) -> _Array1D[timedelta64]: ... @overload def arange( # both start and stop must always be specified for datetime64 start: datetime64, @@ -1092,7 +1098,7 @@ def arange( # both start and stop must always be specified for datetime64 *, device: None | L["cpu"] = ..., like: None | _SupportsArrayFunc = ..., -) -> _1DArray[int, datetime64]: ... +) -> _Array1D[datetime64]: ... @overload def arange( stop: Any, @@ -1100,7 +1106,7 @@ def arange( dtype: _DTypeLike[_SCT], device: None | L["cpu"] = ..., like: None | _SupportsArrayFunc = ..., -) -> _1DArray[int, _SCT]: ... +) -> _Array1D[_SCT]: ... @overload def arange( start: Any, @@ -1110,7 +1116,7 @@ def arange( *, device: None | L["cpu"] = ..., like: None | _SupportsArrayFunc = ..., -) -> _1DArray[int, _SCT]: ... +) -> _Array1D[_SCT]: ... @overload def arange( stop: Any, /, @@ -1118,7 +1124,7 @@ def arange( dtype: DTypeLike, device: None | L["cpu"] = ..., like: None | _SupportsArrayFunc = ..., -) -> _1DArray[int, Any]: ... +) -> _Array1D[Any]: ... @overload def arange( start: Any, @@ -1128,7 +1134,7 @@ def arange( *, device: None | L["cpu"] = ..., like: None | _SupportsArrayFunc = ..., -) -> _1DArray[int, Any]: ... +) -> _Array1D[Any]: ... def datetime_data( dtype: str | _DTypeLike[datetime64] | _DTypeLike[timedelta64], /, diff --git a/numpy/_core/numeric.pyi b/numpy/_core/numeric.pyi index 7966d9ac118b..a5af4d372968 100644 --- a/numpy/_core/numeric.pyi +++ b/numpy/_core/numeric.pyi @@ -44,6 +44,7 @@ from numpy import ( float64, timedelta64, object_, + _AnyShapeType, _OrderKACF, _OrderCF, ) @@ -190,7 +191,6 @@ _T = TypeVar("_T") _SCT = TypeVar("_SCT", bound=generic) _DType = TypeVar("_DType", bound=np.dtype[Any]) _ArrayType = TypeVar("_ArrayType", bound=np.ndarray[Any, Any]) -_SizeType = TypeVar("_SizeType", bound=int) _ShapeType = TypeVar("_ShapeType", bound=tuple[int, ...]) _CorrelateMode: TypeAlias = L["valid", "same", "full"] @@ -303,69 +303,69 @@ def ones_like( # 1-D shape @overload def full( - shape: _SizeType, + shape: SupportsIndex, fill_value: _SCT, dtype: None = ..., order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], -) -> _Array[tuple[_SizeType], _SCT]: ... +) -> _Array[tuple[int], _SCT]: ... @overload def full( - shape: _SizeType, + shape: SupportsIndex, fill_value: Any, dtype: _DType | _SupportsDType[_DType], order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], -) -> np.ndarray[tuple[_SizeType], _DType]: ... +) -> np.ndarray[tuple[int], _DType]: ... @overload def full( - shape: _SizeType, + shape: SupportsIndex, fill_value: Any, dtype: type[_SCT], order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], -) -> _Array[tuple[_SizeType], _SCT]: ... +) -> _Array[tuple[int], _SCT]: ... @overload def full( - shape: _SizeType, + shape: SupportsIndex, fill_value: Any, dtype: None | DTypeLike = ..., order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], -) -> _Array[tuple[_SizeType], Any]: ... +) -> _Array[tuple[int], Any]: ... # known shape @overload def full( - shape: _ShapeType, + shape: _AnyShapeType, fill_value: _SCT, dtype: None = ..., order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], -) -> _Array[_ShapeType, _SCT]: ... +) -> _Array[_AnyShapeType, _SCT]: ... @overload def full( - shape: _ShapeType, + shape: _AnyShapeType, fill_value: Any, dtype: _DType | _SupportsDType[_DType], order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], -) -> np.ndarray[_ShapeType, _DType]: ... +) -> np.ndarray[_AnyShapeType, _DType]: ... @overload def full( - shape: _ShapeType, + shape: _AnyShapeType, fill_value: Any, dtype: type[_SCT], order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], -) -> _Array[_ShapeType, _SCT]: ... +) -> _Array[_AnyShapeType, _SCT]: ... @overload def full( - shape: _ShapeType, + shape: _AnyShapeType, fill_value: Any, dtype: None | DTypeLike = ..., order: _OrderCF = ..., **kwargs: Unpack[_KwargsEmpty], -) -> _Array[_ShapeType, Any]: ... +) -> _Array[_AnyShapeType, Any]: ... # unknown shape @overload def full( diff --git a/numpy/_core/overrides.pyi b/numpy/_core/overrides.pyi new file mode 100644 index 000000000000..9babbcc26a0b --- /dev/null +++ b/numpy/_core/overrides.pyi @@ -0,0 +1,50 @@ +from collections.abc import Callable, Iterable +from typing import Any, Final, NamedTuple + +from typing_extensions import ParamSpec, TypeVar + +from numpy._typing import _SupportsArrayFunc + +_T = TypeVar("_T") +_Tss = ParamSpec("_Tss") +_FuncT = TypeVar("_FuncT", bound=Callable[..., object]) + +### + +ARRAY_FUNCTIONS: set[Callable[..., Any]] = ... +array_function_like_doc: Final[str] = ... + +class ArgSpec(NamedTuple): + args: list[str] + varargs: str | None + keywords: str | None + defaults: tuple[Any, ...] + +def get_array_function_like_doc(public_api: Callable[..., Any], docstring_template: str = "") -> str: ... +def finalize_array_function_like(public_api: _FuncT) -> _FuncT: ... + +# +def verify_matching_signatures( + implementation: Callable[_Tss, object], + dispatcher: Callable[_Tss, Iterable[_SupportsArrayFunc]], +) -> None: ... + +# NOTE: This actually returns a `_ArrayFunctionDispatcher` callable wrapper object, with +# the original wrapped callable stored in the `._implementation` attribute. It checks +# for any `__array_function__` of the values of specific arguments that the dispatcher +# specifies. Since the dispatcher only returns an iterable of passed array-like args, +# this overridable behaviour is impossible to annotate. +def array_function_dispatch( + dispatcher: Callable[_Tss, Iterable[_SupportsArrayFunc]] | None = None, + module: str | None = None, + verify: bool = True, + docs_from_dispatcher: bool = False, +) -> Callable[[_FuncT], _FuncT]: ... + +# +def array_function_from_dispatcher( + implementation: Callable[_Tss, _T], + module: str | None = None, + verify: bool = True, + docs_from_dispatcher: bool = True, +) -> Callable[[Callable[_Tss, Iterable[_SupportsArrayFunc]]], Callable[_Tss, _T]]: ... diff --git a/numpy/_core/printoptions.pyi b/numpy/_core/printoptions.pyi new file mode 100644 index 000000000000..bd7c7b40692d --- /dev/null +++ b/numpy/_core/printoptions.pyi @@ -0,0 +1,28 @@ +from collections.abc import Callable +from contextvars import ContextVar +from typing import Any, Final, TypedDict + +from .arrayprint import _FormatDict + +__all__ = ["format_options"] + +### + +class _FormatOptionsDict(TypedDict): + edgeitems: int + threshold: int + floatmode: str + precision: int + suppress: bool + linewidth: int + nanstr: str + infstr: str + sign: str + formatter: _FormatDict | None + legacy: int + override_repr: Callable[[Any], str] | None + +### + +default_format_options_dict: Final[_FormatOptionsDict] = ... +format_options: ContextVar[_FormatOptionsDict] diff --git a/numpy/_pyinstaller/__init__.pyi b/numpy/_pyinstaller/__init__.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/numpy/_pyinstaller/hook-numpy.pyi b/numpy/_pyinstaller/hook-numpy.pyi new file mode 100644 index 000000000000..2642996dad7e --- /dev/null +++ b/numpy/_pyinstaller/hook-numpy.pyi @@ -0,0 +1,13 @@ +from typing import Final + +# from `PyInstaller.compat` +is_conda: Final[bool] +is_pure_conda: Final[bool] + +# from `PyInstaller.utils.hooks` +def is_module_satisfies(requirements: str, version: None = None, version_attr: None = None) -> bool: ... + +binaries: Final[list[tuple[str, str]]] + +hiddenimports: Final[list[str]] +excludedimports: Final[list[str]] diff --git a/numpy/_utils/__init__.pyi b/numpy/_utils/__init__.pyi new file mode 100644 index 000000000000..ced45bfdeb44 --- /dev/null +++ b/numpy/_utils/__init__.pyi @@ -0,0 +1,31 @@ +from collections.abc import Callable, Iterable +from typing import Protocol, overload, type_check_only + +from _typeshed import IdentityFunction +from typing_extensions import TypeVar + +from ._convertions import asbytes as asbytes +from ._convertions import asunicode as asunicode + +### + +_T = TypeVar("_T") +_HasModuleT = TypeVar("_HasModuleT", bound=_HasModule) + +@type_check_only +class _HasModule(Protocol): + __module__: str + +### + +@overload +def set_module(module: None) -> IdentityFunction: ... +@overload +def set_module(module: _HasModuleT) -> _HasModuleT: ... + +# +def _rename_parameter( + old_names: Iterable[str], + new_names: Iterable[str], + dep_version: str | None = None, +) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ... diff --git a/numpy/_utils/_convertions.pyi b/numpy/_utils/_convertions.pyi new file mode 100644 index 000000000000..6cc599acc94f --- /dev/null +++ b/numpy/_utils/_convertions.pyi @@ -0,0 +1,4 @@ +__all__ = ["asbytes", "asunicode"] + +def asunicode(s: bytes | str) -> str: ... +def asbytes(s: bytes | str) -> str: ... diff --git a/numpy/_utils/_inspect.pyi b/numpy/_utils/_inspect.pyi new file mode 100644 index 000000000000..ba0260d3a593 --- /dev/null +++ b/numpy/_utils/_inspect.pyi @@ -0,0 +1,71 @@ +import types +from collections.abc import Callable, Mapping +from typing import Any, Final, TypeAlias, overload + +from _typeshed import SupportsLenAndGetItem +from typing_extensions import TypeIs, TypeVar + +__all__ = ["formatargspec", "getargspec"] + +### + +_T = TypeVar("_T") +_RT = TypeVar("_RT") + +_StrSeq: TypeAlias = SupportsLenAndGetItem[str] +_NestedSeq: TypeAlias = list[_T | _NestedSeq[_T]] | tuple[_T | _NestedSeq[_T], ...] + +_JoinFunc: TypeAlias = Callable[[list[_T]], _T] +_FormatFunc: TypeAlias = Callable[[_T], str] + +### + +CO_OPTIMIZED: Final = 1 +CO_NEWLOCALS: Final = 2 +CO_VARARGS: Final = 4 +CO_VARKEYWORDS: Final = 8 + +### + +def ismethod(object: object) -> TypeIs[types.MethodType]: ... +def isfunction(object: object) -> TypeIs[types.FunctionType]: ... +def iscode(object: object) -> TypeIs[types.CodeType]: ... + +### + +def getargs(co: types.CodeType) -> tuple[list[str], str | None, str | None]: ... +def getargspec(func: types.MethodType | types.FunctionType) -> tuple[list[str], str | None, str | None, tuple[Any, ...]]: ... +def getargvalues(frame: types.FrameType) -> tuple[list[str], str | None, str | None, dict[str, Any]]: ... + +# +def joinseq(seq: _StrSeq) -> str: ... + +# +@overload +def strseq(object: _NestedSeq[str], convert: Callable[[Any], Any], join: _JoinFunc[str] = ...) -> str: ... +@overload +def strseq(object: _NestedSeq[_T], convert: Callable[[_T], _RT], join: _JoinFunc[_RT]) -> _RT: ... + +# +def formatargspec( + args: _StrSeq, + varargs: str | None = None, + varkw: str | None = None, + defaults: SupportsLenAndGetItem[object] | None = None, + formatarg: _FormatFunc[str] = ..., # str + formatvarargs: _FormatFunc[str] = ..., # "*{}".format + formatvarkw: _FormatFunc[str] = ..., # "**{}".format + formatvalue: _FormatFunc[object] = ..., # "={!r}".format + join: _JoinFunc[str] = ..., # joinseq +) -> str: ... +def formatargvalues( + args: _StrSeq, + varargs: str | None, + varkw: str | None, + locals: Mapping[str, object] | None, + formatarg: _FormatFunc[str] = ..., # str + formatvarargs: _FormatFunc[str] = ..., # "*{}".format + formatvarkw: _FormatFunc[str] = ..., # "**{}".format + formatvalue: _FormatFunc[object] = ..., # "={!r}".format + join: _JoinFunc[str] = ..., # joinseq +) -> str: ... diff --git a/numpy/_utils/_pep440.pyi b/numpy/_utils/_pep440.pyi new file mode 100644 index 000000000000..29dd4c912aa9 --- /dev/null +++ b/numpy/_utils/_pep440.pyi @@ -0,0 +1,121 @@ +import re +from collections.abc import Callable +from typing import ( + Any, + ClassVar, + Final, + Generic, + NamedTuple, + TypeVar, + final, + type_check_only, +) +from typing import ( + Literal as L, +) + +from typing_extensions import TypeIs + +__all__ = ["VERSION_PATTERN", "InvalidVersion", "LegacyVersion", "Version", "parse"] + +### + +_CmpKeyT = TypeVar("_CmpKeyT", bound=tuple[object, ...]) +_CmpKeyT_co = TypeVar("_CmpKeyT_co", bound=tuple[object, ...], default=tuple[Any, ...], covariant=True) + +### + +VERSION_PATTERN: Final[str] = ... + +class InvalidVersion(ValueError): ... + +@type_check_only +@final +class _InfinityType: + def __hash__(self) -> int: ... + def __eq__(self, other: object, /) -> TypeIs[_InfinityType]: ... + def __ne__(self, other: object, /) -> bool: ... + def __lt__(self, other: object, /) -> L[False]: ... + def __le__(self, other: object, /) -> L[False]: ... + def __gt__(self, other: object, /) -> L[True]: ... + def __ge__(self, other: object, /) -> L[True]: ... + def __neg__(self) -> _NegativeInfinityType: ... + +Infinity: Final[_InfinityType] = ... + +@type_check_only +@final +class _NegativeInfinityType: + def __hash__(self) -> int: ... + def __eq__(self, other: object, /) -> TypeIs[_NegativeInfinityType]: ... + def __ne__(self, other: object, /) -> bool: ... + def __lt__(self, other: object, /) -> L[True]: ... + def __le__(self, other: object, /) -> L[True]: ... + def __gt__(self, other: object, /) -> L[False]: ... + def __ge__(self, other: object, /) -> L[False]: ... + def __neg__(self) -> _InfinityType: ... + +NegativeInfinity: Final[_NegativeInfinityType] = ... + +class _Version(NamedTuple): + epoch: int + release: tuple[int, ...] + dev: tuple[str, int] | None + pre: tuple[str, int] | None + post: tuple[str, int] | None + local: tuple[str | int, ...] | None + +class _BaseVersion(Generic[_CmpKeyT_co]): + _key: _CmpKeyT_co + def __hash__(self) -> int: ... + def __eq__(self, other: _BaseVersion, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + def __ne__(self, other: _BaseVersion, /) -> bool: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + def __lt__(self, other: _BaseVersion, /) -> bool: ... + def __le__(self, other: _BaseVersion, /) -> bool: ... + def __ge__(self, other: _BaseVersion, /) -> bool: ... + def __gt__(self, other: _BaseVersion, /) -> bool: ... + def _compare(self, /, other: _BaseVersion[_CmpKeyT], method: Callable[[_CmpKeyT_co, _CmpKeyT], bool]) -> bool: ... + +class LegacyVersion(_BaseVersion[tuple[L[-1], tuple[str, ...]]]): + _version: Final[str] + def __init__(self, /, version: str) -> None: ... + @property + def public(self) -> str: ... + @property + def base_version(self) -> str: ... + @property + def local(self) -> None: ... + @property + def is_prerelease(self) -> L[False]: ... + @property + def is_postrelease(self) -> L[False]: ... + +class Version( + _BaseVersion[ + tuple[ + int, # epoch + tuple[int, ...], # release + tuple[str, int] | _InfinityType | _NegativeInfinityType, # pre + tuple[str, int] | _NegativeInfinityType, # post + tuple[str, int] | _InfinityType, # dev + tuple[tuple[int, L[""]] | tuple[_NegativeInfinityType, str], ...] | _NegativeInfinityType, # local + ], + ], +): + _regex: ClassVar[re.Pattern[str]] = ... + _version: Final[str] + + def __init__(self, /, version: str) -> None: ... + @property + def public(self) -> str: ... + @property + def base_version(self) -> str: ... + @property + def local(self) -> str | None: ... + @property + def is_prerelease(self) -> bool: ... + @property + def is_postrelease(self) -> bool: ... + +# +def parse(version: str) -> Version | LegacyVersion: ... diff --git a/numpy/core/_dtype.pyi b/numpy/core/_dtype.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/numpy/core/_dtype_ctypes.pyi b/numpy/core/_dtype_ctypes.pyi new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/numpy/core/overrides.pyi b/numpy/core/overrides.pyi new file mode 100644 index 000000000000..fab3512626f8 --- /dev/null +++ b/numpy/core/overrides.pyi @@ -0,0 +1,7 @@ +# NOTE: At runtime, this submodule dynamically re-exports any `numpy._core.overrides` +# member, and issues a `DeprecationWarning` when accessed. But since there is no +# `__dir__` or `__all__` present, these annotations would be unverifiable. Because +# this module is also deprecated in favor of `numpy._core`, and therefore not part of +# the public API, we omit the "re-exports", which in practice would require literal +# duplication of the stubs in order for the `@deprecated` decorator to be understood +# by type-checkers. diff --git a/numpy/fft/_helper.pyi b/numpy/fft/_helper.pyi index 5cb28db2239e..7673c1800a92 100644 --- a/numpy/fft/_helper.pyi +++ b/numpy/fft/_helper.pyi @@ -1,51 +1,38 @@ -from typing import Any, TypeVar, overload, Literal as L +from typing import Any, Final, TypeVar, overload +from typing import Literal as L -from numpy import generic, integer, floating, complexfloating -from numpy._typing import ( - NDArray, - ArrayLike, - _ShapeLike, - _ArrayLike, - _ArrayLikeFloat_co, - _ArrayLikeComplex_co, -) +from numpy import complexfloating, floating, generic, integer +from numpy._typing import ArrayLike, NDArray, _ArrayLike, _ArrayLikeComplex_co, _ArrayLikeFloat_co, _ShapeLike -__all__ = ["fftshift", "ifftshift", "fftfreq", "rfftfreq"] +__all__ = ["fftfreq", "fftshift", "ifftshift", "rfftfreq"] _SCT = TypeVar("_SCT", bound=generic) +### + +integer_types: Final[tuple[type[int], type[integer]]] = ... + +### + @overload -def fftshift(x: _ArrayLike[_SCT], axes: None | _ShapeLike = ...) -> NDArray[_SCT]: ... +def fftshift(x: _ArrayLike[_SCT], axes: _ShapeLike | None = None) -> NDArray[_SCT]: ... @overload -def fftshift(x: ArrayLike, axes: None | _ShapeLike = ...) -> NDArray[Any]: ... +def fftshift(x: ArrayLike, axes: _ShapeLike | None = None) -> NDArray[Any]: ... +# @overload -def ifftshift(x: _ArrayLike[_SCT], axes: None | _ShapeLike = ...) -> NDArray[_SCT]: ... +def ifftshift(x: _ArrayLike[_SCT], axes: _ShapeLike | None = None) -> NDArray[_SCT]: ... @overload -def ifftshift(x: ArrayLike, axes: None | _ShapeLike = ...) -> NDArray[Any]: ... +def ifftshift(x: ArrayLike, axes: _ShapeLike | None = None) -> NDArray[Any]: ... +# @overload -def fftfreq( - n: int | integer[Any], - d: _ArrayLikeFloat_co = ..., - device: None | L["cpu"] = ..., -) -> NDArray[floating[Any]]: ... +def fftfreq(n: int | integer, d: _ArrayLikeFloat_co = 1.0, device: L["cpu"] | None = None) -> NDArray[floating]: ... @overload -def fftfreq( - n: int | integer[Any], - d: _ArrayLikeComplex_co = ..., - device: None | L["cpu"] = ..., -) -> NDArray[complexfloating[Any, Any]]: ... +def fftfreq(n: int | integer, d: _ArrayLikeComplex_co = 1.0, device: L["cpu"] | None = None) -> NDArray[complexfloating]: ... +# @overload -def rfftfreq( - n: int | integer[Any], - d: _ArrayLikeFloat_co = ..., - device: None | L["cpu"] = ..., -) -> NDArray[floating[Any]]: ... +def rfftfreq(n: int | integer, d: _ArrayLikeFloat_co = 1.0, device: L["cpu"] | None = None) -> NDArray[floating]: ... @overload -def rfftfreq( - n: int | integer[Any], - d: _ArrayLikeComplex_co = ..., - device: None | L["cpu"] = ..., -) -> NDArray[complexfloating[Any, Any]]: ... +def rfftfreq(n: int | integer, d: _ArrayLikeComplex_co = 1.0, device: L["cpu"] | None = None) -> NDArray[complexfloating]: ... diff --git a/numpy/fft/helper.pyi b/numpy/fft/helper.pyi new file mode 100644 index 000000000000..887cbe7e27c9 --- /dev/null +++ b/numpy/fft/helper.pyi @@ -0,0 +1,22 @@ +from typing import Any +from typing import Literal as L + +from typing_extensions import deprecated + +import numpy as np +from numpy._typing import ArrayLike, NDArray, _ShapeLike + +from ._helper import integer_types as integer_types + +__all__ = ["fftfreq", "fftshift", "ifftshift", "rfftfreq"] + +### + +@deprecated("Please use `numpy.fft.fftshift` instead.") +def fftshift(x: ArrayLike, axes: _ShapeLike | None = None) -> NDArray[Any]: ... +@deprecated("Please use `numpy.fft.ifftshift` instead.") +def ifftshift(x: ArrayLike, axes: _ShapeLike | None = None) -> NDArray[Any]: ... +@deprecated("Please use `numpy.fft.fftfreq` instead.") +def fftfreq(n: int | np.integer, d: ArrayLike = 1.0, device: L["cpu"] | None = None) -> NDArray[Any]: ... +@deprecated("Please use `numpy.fft.rfftfreq` instead.") +def rfftfreq(n: int | np.integer, d: ArrayLike = 1.0, device: L["cpu"] | None = None) -> NDArray[Any]: ... diff --git a/numpy/fft/meson.build b/numpy/fft/meson.build index 751b5dc74d30..e18949af5e31 100644 --- a/numpy/fft/meson.build +++ b/numpy/fft/meson.build @@ -24,6 +24,7 @@ py.install_sources( '_helper.py', '_helper.pyi', 'helper.py', + 'helper.pyi', ], subdir: 'numpy/fft' ) diff --git a/numpy/lib/_shape_base_impl.pyi b/numpy/lib/_shape_base_impl.pyi index 5439c533edff..77e5d2de9cb9 100644 --- a/numpy/lib/_shape_base_impl.pyi +++ b/numpy/lib/_shape_base_impl.pyi @@ -10,20 +10,13 @@ from typing import ( type_check_only, ) +from typing_extensions import deprecated + import numpy as np -from numpy import ( - generic, - integer, - ufunc, - unsignedinteger, - signedinteger, - floating, - complexfloating, - object_, -) -from numpy._core.shape_base import vstack as row_stack +from numpy import _CastingKind, generic, integer, ufunc, unsignedinteger, signedinteger, floating, complexfloating, object_ from numpy._typing import ( ArrayLike, + DTypeLike, NDArray, _ShapeLike, _ArrayLike, @@ -72,6 +65,8 @@ class _SupportsArrayWrap(Protocol): @property def __array_wrap__(self) -> _ArrayWrap: ... +### + def take_along_axis( arr: _SCT | NDArray[_SCT], indices: NDArray[integer[Any]], @@ -119,6 +114,16 @@ def expand_dims( axis: _ShapeLike, ) -> NDArray[Any]: ... +# Deprecated in NumPy 2.0, 2023-08-18 +@deprecated("`row_stack` alias is deprecated. Use `np.vstack` directly.") +def row_stack( + tup: Sequence[ArrayLike], + *, + dtype: DTypeLike | None = None, + casting: _CastingKind = "same_kind", +) -> NDArray[Any]: ... + +# @overload def column_stack(tup: Sequence[_ArrayLike[_SCT]]) -> NDArray[_SCT]: ... @overload diff --git a/numpy/linalg/_linalg.pyi b/numpy/linalg/_linalg.pyi index 8ac75a47f5f8..9f646ec94037 100644 --- a/numpy/linalg/_linalg.pyi +++ b/numpy/linalg/_linalg.pyi @@ -16,7 +16,6 @@ from numpy import ( vecdot, # other - generic, floating, complexfloating, signedinteger, @@ -79,13 +78,13 @@ __all__ = [ "vecdot", ] -_T = TypeVar("_T") _ArrayType = TypeVar("_ArrayType", bound=NDArray[Any]) -_SCT2 = TypeVar("_SCT2", bound=generic, covariant=True) -_2Tuple: TypeAlias = tuple[_T, _T] _ModeKind: TypeAlias = L["reduced", "complete", "r", "raw"] +### + +fortran_int = np.intc class EigResult(NamedTuple): eigenvalues: NDArray[Any] diff --git a/numpy/linalg/_umath_linalg.pyi b/numpy/linalg/_umath_linalg.pyi new file mode 100644 index 000000000000..cd07acdb1f9e --- /dev/null +++ b/numpy/linalg/_umath_linalg.pyi @@ -0,0 +1,61 @@ +from typing import Final +from typing import Literal as L + +import numpy as np +from numpy._typing._ufunc import _GUFunc_Nin2_Nout1 + +__version__: Final[str] = ... +_ilp64: Final[bool] = ... + +### +# 1 -> 1 + +# (m,m) -> () +det: Final[np.ufunc] = ... +# (m,m) -> (m) +cholesky_lo: Final[np.ufunc] = ... +cholesky_up: Final[np.ufunc] = ... +eigvals: Final[np.ufunc] = ... +eigvalsh_lo: Final[np.ufunc] = ... +eigvalsh_up: Final[np.ufunc] = ... +# (m,m) -> (m,m) +inv: Final[np.ufunc] = ... +# (m,n) -> (p) +qr_r_raw: Final[np.ufunc] = ... +svd: Final[np.ufunc] = ... + +### +# 1 -> 2 + +# (m,m) -> (), () +slogdet: Final[np.ufunc] = ... +# (m,m) -> (m), (m,m) +eig: Final[np.ufunc] = ... +eigh_lo: Final[np.ufunc] = ... +eigh_up: Final[np.ufunc] = ... + +### +# 2 -> 1 + +# (m,n), (n) -> (m,m) +qr_complete: Final[_GUFunc_Nin2_Nout1[L["qr_complete"], L[2], None, L["(m,n),(n)->(m,m)"]]] = ... +# (m,n), (k) -> (m,k) +qr_reduced: Final[_GUFunc_Nin2_Nout1[L["qr_reduced"], L[2], None, L["(m,n),(k)->(m,k)"]]] = ... +# (m,m), (m,n) -> (m,n) +solve: Final[_GUFunc_Nin2_Nout1[L["solve"], L[4], None, L["(m,m),(m,n)->(m,n)"]]] = ... +# (m,m), (m) -> (m) +solve1: Final[_GUFunc_Nin2_Nout1[L["solve1"], L[4], None, L["(m,m),(m)->(m)"]]] = ... + +### +# 1 -> 3 + +# (m,n) -> (m,m), (p), (n,n) +svd_f: Final[np.ufunc] = ... +# (m,n) -> (m,p), (p), (p,n) +svd_s: Final[np.ufunc] = ... + +### +# 3 -> 4 + +# (m,n), (m,k), () -> (n,k), (k), (), (p) +lstsq: Final[np.ufunc] = ... diff --git a/numpy/linalg/lapack_lite.pyi b/numpy/linalg/lapack_lite.pyi new file mode 100644 index 000000000000..0f6bfa3a022b --- /dev/null +++ b/numpy/linalg/lapack_lite.pyi @@ -0,0 +1,141 @@ +from typing import Any, Final, TypedDict, type_check_only + +import numpy as np +from numpy._typing import NDArray + +from ._linalg import fortran_int + +### + +@type_check_only +class _GELSD(TypedDict): + m: int + n: int + nrhs: int + lda: int + ldb: int + rank: int + lwork: int + info: int + +@type_check_only +class _DGELSD(_GELSD): + dgelsd_: int + rcond: float + +@type_check_only +class _ZGELSD(_GELSD): + zgelsd_: int + +@type_check_only +class _GEQRF(TypedDict): + m: int + n: int + lda: int + lwork: int + info: int + +@type_check_only +class _DGEQRF(_GEQRF): + dgeqrf_: int + +@type_check_only +class _ZGEQRF(_GEQRF): + zgeqrf_: int + +@type_check_only +class _DORGQR(TypedDict): + dorgqr_: int + info: int + +@type_check_only +class _ZUNGQR(TypedDict): + zungqr_: int + info: int + +### + +_ilp64: Final[bool] = ... + +def dgelsd( + m: int, + n: int, + nrhs: int, + a: NDArray[np.float64], + lda: int, + b: NDArray[np.float64], + ldb: int, + s: NDArray[np.float64], + rcond: float, + rank: int, + work: NDArray[np.float64], + lwork: int, + iwork: NDArray[fortran_int], + info: int, +) -> _DGELSD: ... +def zgelsd( + m: int, + n: int, + nrhs: int, + a: NDArray[np.complex128], + lda: int, + b: NDArray[np.complex128], + ldb: int, + s: NDArray[np.float64], + rcond: float, + rank: int, + work: NDArray[np.complex128], + lwork: int, + rwork: NDArray[np.float64], + iwork: NDArray[fortran_int], + info: int, +) -> _ZGELSD: ... + +# +def dgeqrf( + m: int, + n: int, + a: NDArray[np.float64], # in/out, shape: (lda, n) + lda: int, + tau: NDArray[np.float64], # out, shape: (min(m, n),) + work: NDArray[np.float64], # out, shape: (max(1, lwork),) + lwork: int, + info: int, # out +) -> _DGEQRF: ... +def zgeqrf( + m: int, + n: int, + a: NDArray[np.complex128], # in/out, shape: (lda, n) + lda: int, + tau: NDArray[np.complex128], # out, shape: (min(m, n),) + work: NDArray[np.complex128], # out, shape: (max(1, lwork),) + lwork: int, + info: int, # out +) -> _ZGEQRF: ... + +# +def dorgqr( + m: int, # >=0 + n: int, # m >= n >= 0 + k: int, # n >= k >= 0 + a: NDArray[np.float64], # in/out, shape: (lda, n) + lda: int, # >= max(1, m) + tau: NDArray[np.float64], # in, shape: (k,) + work: NDArray[np.float64], # out, shape: (max(1, lwork),) + lwork: int, + info: int, # out +) -> _DORGQR: ... +def zungqr( + m: int, + n: int, + k: int, + a: NDArray[np.complex128], + lda: int, + tau: NDArray[np.complex128], + work: NDArray[np.complex128], + lwork: int, + info: int, +) -> _ZUNGQR: ... + +# +def xerbla(srname: object, info: int) -> None: ... diff --git a/numpy/linalg/linalg.pyi b/numpy/linalg/linalg.pyi new file mode 100644 index 000000000000..dbe9becfb8d5 --- /dev/null +++ b/numpy/linalg/linalg.pyi @@ -0,0 +1,69 @@ +from ._linalg import ( + LinAlgError, + cholesky, + cond, + cross, + det, + diagonal, + eig, + eigh, + eigvals, + eigvalsh, + inv, + lstsq, + matmul, + matrix_norm, + matrix_power, + matrix_rank, + matrix_transpose, + multi_dot, + norm, + outer, + pinv, + qr, + slogdet, + solve, + svd, + svdvals, + tensordot, + tensorinv, + tensorsolve, + trace, + vecdot, + vector_norm, +) + +__all__ = [ + "LinAlgError", + "cholesky", + "cond", + "cross", + "det", + "diagonal", + "eig", + "eigh", + "eigvals", + "eigvalsh", + "inv", + "lstsq", + "matmul", + "matrix_norm", + "matrix_power", + "matrix_rank", + "matrix_transpose", + "multi_dot", + "norm", + "outer", + "pinv", + "qr", + "slogdet", + "solve", + "svd", + "svdvals", + "tensordot", + "tensorinv", + "tensorsolve", + "trace", + "vecdot", + "vector_norm", +] diff --git a/numpy/linalg/meson.build b/numpy/linalg/meson.build index 740c9f56c6fa..e2f8136208d6 100644 --- a/numpy/linalg/meson.build +++ b/numpy/linalg/meson.build @@ -45,7 +45,10 @@ py.install_sources( '__init__.pyi', '_linalg.py', '_linalg.pyi', + '_umath_linalg.pyi', + 'lapack_lite.pyi', 'linalg.py', + 'linalg.pyi', ], subdir: 'numpy/linalg' ) diff --git a/numpy/matlib.pyi b/numpy/matlib.pyi index 67b753a87c32..cce0bf5b0541 100644 --- a/numpy/matlib.pyi +++ b/numpy/matlib.pyi @@ -394,7 +394,7 @@ from numpy import ( roots, rot90, round, - # row_stack, + row_stack, s_, save, savetxt, diff --git a/numpy/typing/tests/data/reveal/fromnumeric.pyi b/numpy/typing/tests/data/reveal/fromnumeric.pyi index 40bb578d0d46..366e34d8af99 100644 --- a/numpy/typing/tests/data/reveal/fromnumeric.pyi +++ b/numpy/typing/tests/data/reveal/fromnumeric.pyi @@ -102,11 +102,11 @@ assert_type(np.searchsorted(AR_f4[0], 0), np.intp) assert_type(np.searchsorted(AR_b[0], [0]), npt.NDArray[np.intp]) assert_type(np.searchsorted(AR_f4[0], [0]), npt.NDArray[np.intp]) -assert_type(np.resize(b, (5, 5)), np.ndarray[tuple[L[5], L[5]], np.dtype[np.bool]]) -assert_type(np.resize(f4, (5, 5)), np.ndarray[tuple[L[5], L[5]], np.dtype[np.float32]]) -assert_type(np.resize(f, (5, 5)), np.ndarray[tuple[L[5], L[5]], np.dtype[Any]]) -assert_type(np.resize(AR_b, (5, 5)), np.ndarray[tuple[L[5], L[5]], np.dtype[np.bool]]) -assert_type(np.resize(AR_f4, (5, 5)), np.ndarray[tuple[L[5], L[5]], np.dtype[np.float32]]) +assert_type(np.resize(b, (5, 5)), np.ndarray[tuple[int, int], np.dtype[np.bool]]) +assert_type(np.resize(f4, (5, 5)), np.ndarray[tuple[int, int], np.dtype[np.float32]]) +assert_type(np.resize(f, (5, 5)), np.ndarray[tuple[int, int], np.dtype[Any]]) +assert_type(np.resize(AR_b, (5, 5)), np.ndarray[tuple[int, int], np.dtype[np.bool]]) +assert_type(np.resize(AR_f4, (5, 5)), np.ndarray[tuple[int, int], np.dtype[np.float32]]) assert_type(np.squeeze(b), np.bool) assert_type(np.squeeze(f4), np.float32)