NumPy 源码解析(九十一)
.\numpy\numpy\_typing\_char_codes.py
from typing import Literal
_BoolCodes = Literal["?", "=?", "<?", ">?", "bool", "bool_"]
_UInt8Codes = Literal["uint8", "u1", "=u1", "<u1", ">u1"]
_UInt16Codes = Literal["uint16", "u2", "=u2", "<u2", ">u2"]
_UInt32Codes = Literal["uint32", "u4", "=u4", "<u4", ">u4"]
_UInt64Codes = Literal["uint64", "u8", "=u8", "<u8", ">u8"]
_Int8Codes = Literal["int8", "i1", "=i1", "<i1", ">i1"]
_Int16Codes = Literal["int16", "i2", "=i2", "<i2", ">i2"]
_Int32Codes = Literal["int32", "i4", "=i4", "<i4", ">i4"]
_Int64Codes = Literal["int64", "i8", "=i8", "<i8", ">i8"]
_Float16Codes = Literal["float16", "f2", "=f2", "<f2", ">f2"]
_Float32Codes = Literal["float32", "f4", "=f4", "<f4", ">f4"]
_Float64Codes = Literal["float64", "f8", "=f8", "<f8", ">f8"]
_Complex64Codes = Literal["complex64", "c8", "=c8", "<c8", ">c8"]
_Complex128Codes = Literal["complex128", "c16", "=c16", "<c16", ">c16"]
_ByteCodes = Literal["byte", "b", "=b", "<b", ">b"]
_ShortCodes = Literal["short", "h", "=h", "<h", ">h"]
_IntCCodes = Literal["intc", "i", "=i", "<i", ">i"]
_IntPCodes = Literal["intp", "int", "int_", "n", "=n", "<n", ">n"]
_LongCodes = Literal["long", "l", "=l", "<l", ">l"]
_IntCodes = _IntPCodes
_LongLongCodes = Literal["longlong", "q", "=q", "<q", ">q"]
_UByteCodes = Literal["ubyte", "B", "=B", "<B", ">B"]
_UShortCodes = Literal["ushort", "H", "=H", "<H", ">H"]
_UIntCCodes = Literal["uintc", "I", "=I", "<I", ">I"]
_UIntPCodes = Literal["uintp", "uint", "N", "=N", "<N", ">N"]
_ULongCodes = Literal["ulong", "L", "=L", "<L", ">L"]
_UIntCodes = _UIntPCodes
_ULongLongCodes = Literal["ulonglong", "Q", "=Q", "<Q", ">Q"]
_HalfCodes = Literal["half", "e", "=e", "<e", ">e"]
_SingleCodes = Literal["single", "f", "=f", "<f", ">f"]
_DoubleCodes = Literal["double", "float", "d", "=d", "<d", ">d"]
_LongDoubleCodes = Literal["longdouble", "g", "=g", "<g", ">g"]
_CSingleCodes = Literal["csingle", "F", "=F", "<F", ">F"]
_CDoubleCodes = Literal["cdouble", "complex", "D", "=D", "<D", ">D"]
_CLongDoubleCodes = Literal["clongdouble", "G", "=G", "<G", ">G"]
_StrCodes = Literal["str", "str_", "unicode", "U", "=U", "<U", ">U"]
_BytesCodes = Literal["bytes", "bytes_", "S", "=S", "<S", ">S"]
_VoidCodes = Literal["void", "V", "=V", "<V", ">V"]
_ObjectCodes = Literal["object", "object_", "O", "=O", "<O", ">O"]
_DT64Codes = Literal[
"datetime64", "=datetime64", "<datetime64", ">datetime64",
"datetime64[Y]", "=datetime64[Y]", "<datetime64[Y]", ">datetime64[Y]",
"datetime64[M]", "=datetime64[M]", "<datetime64[M]", ">datetime64[M]",
"datetime64[W]", "=datetime64[W]", "<datetime64[W]", ">datetime64[W]",
"datetime64[D]", "=datetime64[D]", "<datetime64[D]", ">datetime64[D]",
"datetime64[h]", "=datetime64[h]", "<datetime64[h]", ">datetime64[h]",
"datetime64[m]", "=datetime64[m]", "<datetime64[m]", ">datetime64[m]",
"datetime64[s]", "=datetime64[s]", "<datetime64[s]", ">datetime64[s]",
"datetime64[ms]", "=datetime64[ms]", "<datetime64[ms]", ">datetime64[ms]",
]
"datetime64[us]", "=datetime64[us]", "<datetime64[us]", ">datetime64[us]",
"datetime64[ns]", "=datetime64[ns]", "<datetime64[ns]", ">datetime64[ns]",
"datetime64[ps]", "=datetime64[ps]", "<datetime64[ps]", ">datetime64[ps]",
"datetime64[fs]", "=datetime64[fs]", "<datetime64[fs]", ">datetime64[fs]",
"datetime64[as]", "=datetime64[as]", "<datetime64[as]", ">datetime64[as]",
"M", "=M", "<M", ">M",
"M8", "=M8", "<M8", ">M8",
"M8[Y]", "=M8[Y]", "<M8[Y]", ">M8[Y]",
"M8[M]", "=M8[M]", "<M8[M]", ">M8[M]",
"M8[W]", "=M8[W]", "<M8[W]", ">M8[W]",
"M8[D]", "=M8[D]", "<M8[D]", ">M8[D]",
"M8[h]", "=M8[h]", "<M8[h]", ">M8[h]",
"M8[m]", "=M8[m]", "<M8[m]", ">M8[m]",
"M8[s]", "=M8[s]", "<M8[s]", ">M8[s]",
"M8[ms]", "=M8[ms]", "<M8[ms]", ">M8[ms]",
"M8[us]", "=M8[us]", "<M8[us]", ">M8[us]",
"M8[ns]", "=M8[ns]", "<M8[ns]", ">M8[ns]",
"M8[ps]", "=M8[ps]", "<M8[ps]", ">M8[ps]",
"M8[fs]", "=M8[fs]", "<M8[fs]", ">M8[fs]",
"M8[as]", "=M8[as]", "<M8[as]", ">M8[as]",
_TD64Codes = Literal[
"timedelta64", "=timedelta64", "<timedelta64", ">timedelta64",
"timedelta64[Y]", "=timedelta64[Y]", "<timedelta64[Y]", ">timedelta64[Y]",
"timedelta64[M]", "=timedelta64[M]", "<timedelta64[M]", ">timedelta64[M]",
"timedelta64[W]", "=timedelta64[W]", "<timedelta64[W]", ">timedelta64[W]",
"timedelta64[D]", "=timedelta64[D]", "<timedelta64[D]", ">timedelta64[D]",
"timedelta64[h]", "=timedelta64[h]", "<timedelta64[h]", ">timedelta64[h]",
"timedelta64[m]", "=timedelta64[m]", "<timedelta64[m]", ">timedelta64[m]",
"timedelta64[s]", "=timedelta64[s]", "<timedelta64[s]", ">timedelta64[s]",
"timedelta64[ms]", "=timedelta64[ms]", "<timedelta64[ms]", ">timedelta64[ms]",
"timedelta64[us]", "=timedelta64[us]", "<timedelta64[us]", ">timedelta64[us]",
"timedelta64[ns]", "=timedelta64[ns]", "<timedelta64[ns]", ">timedelta64[ns]",
"timedelta64[ps]", "=timedelta64[ps]", "<timedelta64[ps]", ">timedelta64[ps]",
"timedelta64[fs]", "=timedelta64[fs]", "<timedelta64[fs]", ">timedelta64[fs]",
"timedelta64[as]", "=timedelta64[as]", "<timedelta64[as]", ">timedelta64[as]",
"m", "=m", "<m", ">m",
"m8", "=m8", "<m8", ">m8",
"m8[Y]", "=m8[Y]", "<m8[Y]", ">m8[Y]",
"m8[M]", "=m8[M]", "<m8[M]", ">m8[M]",
"m8[W]", "=m8[W]", "<m8[W]", ">m8[W]",
"m8[D]", "=m8[D]", "<m8[D]", ">m8[D]",
"m8[h]", "=m8[h]", "<m8[h]", ">m8[h]",
"m8[m]", "=m8[m]", "<m8[m]", ">m8[m]",
"m8[s]", "=m8[s]", "<m8[s]", ">m8[s]",
"m8[ms]", "=m8[ms]", "<m8[ms]", ">m8[ms]",
"m8[us]", "=m8[us]", "<m8[us]", ">m8[us]",
"m8[ns]", "=m8[ns]", "<m8[ns]", ">m8[ns]",
"m8[ps]", "=m8[ps]", "<m8[ps]", ">m8[ps]",
"m8[fs]", "=m8[fs]", "<m8[fs]", ">m8[fs]",
"m8[as]", "=m8[as]", "<m8[as]", ">m8[as]",
]
.\numpy\numpy\_typing\_dtype_like.py
from collections.abc import Sequence
from typing import (
Any,
Sequence,
Union,
TypeVar,
Protocol,
TypedDict,
runtime_checkable,
)
import numpy as np
from ._shape import _ShapeLike
from ._char_codes import (
_BoolCodes,
_UInt8Codes,
_UInt16Codes,
_UInt32Codes,
_UInt64Codes,
_Int8Codes,
_Int16Codes,
_Int32Codes,
_Int64Codes,
_Float16Codes,
_Float32Codes,
_Float64Codes,
_Complex64Codes,
_Complex128Codes,
_ByteCodes,
_ShortCodes,
_IntCCodes,
_LongCodes,
_LongLongCodes,
_IntPCodes,
_IntCodes,
_UByteCodes,
_UShortCodes,
_UIntCCodes,
_ULongCodes,
_ULongLongCodes,
_UIntPCodes,
_UIntCodes,
_HalfCodes,
_SingleCodes,
_DoubleCodes,
_LongDoubleCodes,
_CSingleCodes,
_CDoubleCodes,
_CLongDoubleCodes,
_DT64Codes,
_TD64Codes,
_StrCodes,
_BytesCodes,
_VoidCodes,
_ObjectCodes,
)
_SCT = TypeVar("_SCT", bound=np.generic)
_DType_co = TypeVar("_DType_co", covariant=True, bound=np.dtype[Any])
_DTypeLikeNested = Any
class _DTypeDictBase(TypedDict):
names: Sequence[str]
formats: Sequence[_DTypeLikeNested]
class _DTypeDict(_DTypeDictBase, total=False):
offsets: Sequence[int]
titles: Sequence[Any]
itemsize: int
aligned: bool
@runtime_checkable
class _SupportsDType(Protocol[_DType_co]):
@property
def dtype(self) -> _DType_co: ...
_DTypeLike = Union[
np.dtype[_SCT],
type[_SCT],
_SupportsDType[np.dtype[_SCT]],
]
_VoidDTypeLike = Union[
tuple[_DTypeLikeNested, int],
tuple[_DTypeLikeNested, _ShapeLike],
list[Any],
_DTypeDict,
tuple[_DTypeLikeNested, _DTypeLikeNested],
]
DTypeLike = Union[
np.dtype[Any],
None,
type[Any],
_SupportsDType[np.dtype[Any]],
str,
_VoidDTypeLike,
]
_DTypeLikeBool = Union[
type[bool],
type[np.bool],
np.dtype[np.bool],
_SupportsDType[np.dtype[np.bool]],
_BoolCodes,
]
_DTypeLikeUInt = Union[
type[np.unsignedinteger],
np.dtype[np.unsignedinteger],
_SupportsDType[np.dtype[np.unsignedinteger]],
_UInt8Codes,
_UInt16Codes,
_UInt32Codes,
_UInt64Codes,
_UByteCodes,
_UShortCodes,
_UIntCCodes,
_LongCodes,
_ULongLongCodes,
_UIntPCodes,
_UIntCodes,
]
_DTypeLikeInt = Union[
type[int],
type[np.signedinteger],
np.dtype[np.signedinteger],
_SupportsDType[np.dtype[np.signedinteger]],
_Int8Codes,
_Int16Codes,
_Int32Codes,
_Int64Codes,
_ByteCodes,
_ShortCodes,
_IntCCodes,
_LongCodes,
_LongLongCodes,
_IntPCodes,
_IntCodes,
]
_DTypeLikeFloat = Union[
type[float],
type[np.floating],
np.dtype[np.floating],
_SupportsDType[np.dtype[np.floating]],
_Float16Codes,
_Float32Codes,
_Float64Codes,
_HalfCodes,
_SingleCodes,
_DoubleCodes,
_LongDoubleCodes,
]
_DTypeLikeComplex = Union[
type[complex],
type[np.complexfloating],
np.dtype[np.complexfloating],
_SupportsDType[np.dtype[np.complexfloating]],
_Complex64Codes,
_Complex128Codes,
_CSingleCodes,
_CDoubleCodes,
_CLongDoubleCodes,
]
_DTypeLikeDT64 = Union[
type[np.timedelta64],
np.dtype[np.timedelta64],
_SupportsDType[np.dtype[np.timedelta64]],
_TD64Codes,
]
_DTypeLikeTD64 = Union[
type[np.datetime64],
np.dtype[np.datetime64],
_SupportsDType[np.dtype[np.datetime64]],
_DT64Codes,
]
_DTypeLikeStr = Union[
type[str],
type[np.str_],
np.dtype[np.str_],
_SupportsDType[np.dtype[np.str_]],
_StrCodes,
]
_DTypeLikeBytes = Union[
type[bytes],
type[np.bytes_],
np.dtype[np.bytes_],
_SupportsDType[np.dtype[np.bytes_]],
_BytesCodes,
]
_DTypeLikeVoid = Union[
type[np.void],
np.dtype[np.void],
_SupportsDType[np.dtype[np.void]],
_VoidCodes,
_VoidDTypeLike,
]
_DTypeLikeObject = Union[
type,
np.dtype[np.object_],
_SupportsDType[np.dtype[np.object_]],
_ObjectCodes,
]
_DTypeLikeComplex_co = Union[
_DTypeLikeBool,
_DTypeLikeUInt,
_DTypeLikeInt,
_DTypeLikeFloat,
_DTypeLikeComplex,
]
.\numpy\numpy\_typing\_extended_precision.py
import numpy as np
from . import (
_80Bit,
_96Bit,
_128Bit,
_256Bit,
)
uint128 = np.unsignedinteger[_128Bit]
uint256 = np.unsignedinteger[_256Bit]
int128 = np.signedinteger[_128Bit]
int256 = np.signedinteger[_256Bit]
float80 = np.floating[_80Bit]
float96 = np.floating[_96Bit]
float128 = np.floating[_128Bit]
float256 = np.floating[_256Bit]
complex160 = np.complexfloating[_80Bit, _80Bit]
complex192 = np.complexfloating[_96Bit, _96Bit]
complex256 = np.complexfloating[_128Bit, _128Bit]
complex512 = np.complexfloating[_256Bit, _256Bit]
.\numpy\numpy\_typing\_nbit.py
from typing import Any
_NBitByte: Any
_NBitShort: Any
_NBitIntC: Any
_NBitIntP: Any
_NBitInt: Any
_NBitLong: Any
_NBitLongLong: Any
_NBitHalf: Any
_NBitSingle: Any
_NBitDouble: Any
_NBitLongDouble: Any
.\numpy\numpy\_typing\_nested_sequence.py
"""
A module containing the `_NestedSequence` protocol.
"""
from __future__ import annotations
from collections.abc import Iterator
from typing import (
Any,
TypeVar,
Protocol,
runtime_checkable,
)
__all__ = ["_NestedSequence"]
_T_co = TypeVar("_T_co", covariant=True)
@runtime_checkable
class _NestedSequence(Protocol[_T_co]):
"""
A protocol for representing nested sequences.
Warning
-------
`_NestedSequence` currently does not work in combination with typevars,
*e.g.* ``def func(a: _NestedSequnce[T]) -> T: ...``.
See Also
--------
collections.abc.Sequence
ABCs for read-only and mutable :term:`sequences`.
Examples
--------
.. code-block:: python
>>> from __future__ import annotations
>>> from typing import TYPE_CHECKING
>>> import numpy as np
>>> from numpy._typing import _NestedSequence
>>> def get_dtype(seq: _NestedSequence[float]) -> np.dtype[np.float64]:
... return np.asarray(seq).dtype
>>> a = get_dtype([1.0])
>>> b = get_dtype([[1.0]])
>>> c = get_dtype([[[1.0]]])
>>> d = get_dtype([[[[1.0]]]])
>>> if TYPE_CHECKING:
... reveal_locals()
... # note: Revealed local types are:
... # note: a: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
... # note: b: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
... # note: c: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
... # note: d: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
"""
def __len__(self, /) -> int:
"""Implement ``len(self)``."""
raise NotImplementedError
def __getitem__(self, index: int, /) -> _T_co | _NestedSequence[_T_co]:
"""Implement ``self[x]``."""
raise NotImplementedError
def __contains__(self, x: object, /) -> bool:
"""Implement ``x in self``."""
raise NotImplementedError
def __iter__(self, /) -> Iterator[_T_co | _NestedSequence[_T_co]]:
"""Implement ``iter(self)``."""
raise NotImplementedError
def __reversed__(self, /) -> Iterator[_T_co | _NestedSequence[_T_co]]:
"""Implement ``reversed(self)``."""
raise NotImplementedError
def count(self, value: Any, /) -> int:
"""Return the number of occurrences of `value`."""
raise NotImplementedError
def index(self, value: Any, /) -> int:
"""Return the first index of `value`."""
raise NotImplementedError
.\numpy\numpy\_typing\_scalars.py
from typing import Union, Any
import numpy as np
_CharLike_co = Union[str, bytes]
_BoolLike_co = Union[bool, np.bool]
_UIntLike_co = Union[_BoolLike_co, np.unsignedinteger[Any]]
_IntLike_co = Union[_BoolLike_co, int, np.integer[Any]]
_FloatLike_co = Union[_IntLike_co, float, np.floating[Any]]
_ComplexLike_co = Union[_FloatLike_co, complex, np.complexfloating[Any, Any]]
_TD64Like_co = Union[_IntLike_co, np.timedelta64]
_NumberLike_co = Union[int, float, complex, np.number[Any], np.bool]
_ScalarLike_co = Union[
int,
float,
complex,
str,
bytes,
np.generic,
]
_VoidLike_co = Union[tuple[Any, ...], np.void]
.\numpy\numpy\_typing\_shape.py
from collections.abc import Sequence
from typing import Union, SupportsIndex
_Shape = tuple[int, ...]
_ShapeLike = Union[SupportsIndex, Sequence[SupportsIndex]]
.\numpy\numpy\_typing\_ufunc.pyi
"""
A module with private type-check-only `numpy.ufunc` subclasses.
The signatures of the ufuncs are too varied to reasonably type
with a single class. So instead, `ufunc` has been expanded into
four private subclasses, one for each combination of
`~ufunc.nin` and `~ufunc.nout`.
"""
from typing import (
Any,
Generic,
overload,
TypeVar,
Literal,
SupportsIndex,
Protocol,
)
from numpy import ufunc, _CastingKind, _OrderKACF
from numpy.typing import NDArray
from ._shape import _ShapeLike
from ._scalars import _ScalarLike_co
from ._array_like import ArrayLike, _ArrayLikeBool_co, _ArrayLikeInt_co
from ._dtype_like import DTypeLike
_T = TypeVar("_T")
_2Tuple = tuple[_T, _T]
_3Tuple = tuple[_T, _T, _T]
_4Tuple = tuple[_T, _T, _T, _T]
_NTypes = TypeVar("_NTypes", bound=int)
_IDType = TypeVar("_IDType", bound=Any)
_NameType = TypeVar("_NameType", bound=str)
_Signature = TypeVar("_Signature", bound=str)
class _SupportsArrayUFunc(Protocol):
def __array_ufunc__(
self,
ufunc: ufunc,
method: Literal[
"__call__", "reduce", "reduceat", "accumulate", "outer", "at"
],
*inputs: Any,
**kwargs: Any,
) -> Any: ...
class _UFunc_Nin1_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
@property
def __name__(self) -> _NameType: ...
@property
def ntypes(self) -> _NTypes: ...
@property
def identity(self) -> _IDType: ...
@property
def nin(self) -> Literal[1]: ...
@property
def nout(self) -> Literal[1]: ...
@property
def nargs(self) -> Literal[2]: ...
@property
def signature(self) -> None: ...
@property
def reduce(self) -> None: ...
@property
def accumulate(self) -> None: ...
@property
def reduceat(self) -> None: ...
@property
def outer(self) -> None: ...
@overload
def __call__(
self,
__x1: _ScalarLike_co,
out: None = ...,
*,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _2Tuple[None | str] = ...,
) -> Any: ...
@overload
def __call__(
self,
__x1: ArrayLike,
out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
*,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _2Tuple[None | str] = ...,
) -> NDArray[Any]: ...
@overload
def __call__(
self,
__x1: _SupportsArrayUFunc,
out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
*,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _2Tuple[None | str] = ...,
) -> Any: ...
def at(
self,
a: _SupportsArrayUFunc,
indices: _ArrayLikeInt_co,
/,
) -> None: ...
class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):
@property
def __name__(self) -> _NameType: ...
@property
def ntypes(self) -> _NTypes: ...
@property
def identity(self) -> _IDType: ...
@property
def nin(self) -> Literal[2]: ...
@property
def nout(self) -> Literal[1]: ...
@property
def nargs(self) -> Literal[3]: ...
@property
def signature(self) -> None: ...
@overload
def __call__(
self,
__x1: _ScalarLike_co,
__x2: _ScalarLike_co,
out: None = ...,
*,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _3Tuple[None | str] = ...,
) -> Any: ...
@overload
def __call__(
self,
__x1: ArrayLike,
__x2: ArrayLike,
out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
*,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _3Tuple[None | str] = ...,
) -> NDArray[Any]: ...
def at(
self,
a: NDArray[Any],
indices: _ArrayLikeInt_co,
b: ArrayLike,
/,
) -> None: ...
def reduce(
self,
array: ArrayLike,
axis: None | _ShapeLike = ...,
dtype: DTypeLike = ...,
out: None | NDArray[Any] = ...,
keepdims: bool = ...,
initial: Any = ...,
where: _ArrayLikeBool_co = ...,
) -> Any: ...
def accumulate(
self,
array: ArrayLike,
axis: SupportsIndex = ...,
dtype: DTypeLike = ...,
out: None | NDArray[Any] = ...,
) -> NDArray[Any]: ...
def reduceat(
self,
array: ArrayLike,
indices: _ArrayLikeInt_co,
axis: SupportsIndex = ...,
dtype: DTypeLike = ...,
out: None | NDArray[Any] = ...,
) -> NDArray[Any]: ...
@overload
def outer(
self,
A: _ScalarLike_co,
B: _ScalarLike_co,
/, *,
out: None = ...,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _3Tuple[None | str] = ...,
) -> Any: ...
@overload
def outer(
self,
A: ArrayLike,
B: ArrayLike,
/, *,
out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _3Tuple[None | str] = ...,
) -> NDArray[Any]: ...
-> NDArray[Any]: ...
class _UFunc_Nin1_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]):
@property
def __name__(self) -> _NameType: ...
@property
def ntypes(self) -> _NTypes: ...
@property
def identity(self) -> _IDType: ...
@property
def nin(self) -> Literal[1]: ...
@property
def nout(self) -> Literal[2]: ...
@property
def nargs(self) -> Literal[3]: ...
@property
def signature(self) -> None: ...
@property
def at(self) -> None: ...
@property
def reduce(self) -> None: ...
@property
def accumulate(self) -> None: ...
@property
def reduceat(self) -> None: ...
@property
def outer(self) -> None: ...
@overload
def __call__(
self,
__x1: _ScalarLike_co,
__out1: None = ...,
__out2: None = ...,
*,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _3Tuple[None | str] = ...,
) -> _2Tuple[Any]: ...
@overload
def __call__(
self,
__x1: ArrayLike,
__out1: None | NDArray[Any] = ...,
__out2: None | NDArray[Any] = ...,
*,
out: _2Tuple[NDArray[Any]] = ...,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _3Tuple[None | str] = ...,
) -> _2Tuple[NDArray[Any]]: ...
@overload
def __call__(
self,
__x1: _SupportsArrayUFunc,
__out1: None | NDArray[Any] = ...,
__out2: None | NDArray[Any] = ...,
*,
out: _2Tuple[NDArray[Any]] = ...,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _3Tuple[None | str] = ...,
) -> _2Tuple[Any]: ...
class _UFunc_Nin2_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]):
@property
def __name__(self) -> _NameType: ...
@property
def ntypes(self) -> _NTypes: ...
@property
def identity(self) -> _IDType: ...
@property
def nin(self) -> Literal[2]: ...
@property
def nout(self) -> Literal[2]: ...
@property
def nargs(self) -> Literal[4]: ...
@property
def signature(self) -> None: ...
@property
def at(self) -> None: ...
@property
def reduce(self) -> None: ...
@property
def accumulate(self) -> None: ...
@property
def reduceat(self) -> None: ...
@property
def outer(self) -> None: ...
@overload
def __call__(
self,
__x1: _ScalarLike_co,
__x2: _ScalarLike_co,
__out1: None = ...,
__out2: None = ...,
*,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _4Tuple[None | str] = ...,
) -> _2Tuple[Any]: ...
@overload
def __call__(
self,
__x1: ArrayLike,
__x2: ArrayLike,
__out1: None | NDArray[Any] = ...,
__out2: None | NDArray[Any] = ...,
*,
out: _2Tuple[NDArray[Any]] = ...,
where: None | _ArrayLikeBool_co = ...,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _4Tuple[None | str] = ...,
) -> _2Tuple[NDArray[Any]]: ...
class _GUFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType, _Signature]):
@property
def __name__(self) -> _NameType: ...
@property
def ntypes(self) -> _NTypes: ...
@property
def identity(self) -> _IDType: ...
@property
def nin(self) -> Literal[2]: ...
@property
def nout(self) -> Literal[1]: ...
@property
def nargs(self) -> Literal[3]: ...
@property
def signature(self) -> _Signature: ...
@property
def reduce(self) -> None: ...
@property
def accumulate(self) -> None: ...
@property
def reduceat(self) -> None: ...
@property
def outer(self) -> None: ...
@property
def at(self) -> None: ...
@overload
def __call__(
self,
__x1: ArrayLike,
__x2: ArrayLike,
out: None = ...,
*,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _3Tuple[None | str] = ...,
axes: list[_2Tuple[SupportsIndex]] = ...,
) -> Any: ...
@overload
def __call__(
self,
__x1: ArrayLike,
__x2: ArrayLike,
out: NDArray[Any] | tuple[NDArray[Any]],
*,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _3Tuple[None | str] = ...,
axes: list[_2Tuple[SupportsIndex]] = ...,
) -> NDArray[Any]: ...
.\numpy\numpy\_typing\__init__.py
from __future__ import annotations
from .. import ufunc
from .._utils import set_module
from typing import TYPE_CHECKING, final
@final
@set_module("numpy.typing")
class NBitBase:
"""
用于静态类型检查期间表示 `numpy.number` 精度的类型。
仅用于静态类型检查,`NBitBase` 表示一个层级子类的基类。
每个后续的子类用于表示更低精度的层级,例如 `64Bit > 32Bit > 16Bit`。
.. versionadded:: 1.20
Examples
--------
下面是一个典型的用法示例:`NBitBase` 用于注释一个函数,该函数接受任意精度的浮点数和整数作为参数,
并返回最大精度的新浮点数(例如 `np.float16 + np.int64 -> np.float64`)。
"""
def __init_subclass__(cls) -> None:
allowed_names = {
"NBitBase", "_256Bit", "_128Bit", "_96Bit", "_80Bit",
"_64Bit", "_32Bit", "_16Bit", "_8Bit",
}
if cls.__name__ not in allowed_names:
raise TypeError('cannot inherit from final class "NBitBase"')
super().__init_subclass__()
class _256Bit(NBitBase):
pass
class _128Bit(_256Bit):
pass
class _96Bit(_128Bit):
pass
class _80Bit(_96Bit):
pass
class _64Bit(_80Bit):
pass
class _32Bit(_64Bit):
pass
class _16Bit(_32Bit):
pass
class _8Bit(_16Bit):
pass
from ._nested_sequence import (
_NestedSequence as _NestedSequence,
)
from ._nbit import (
_NBitByte as _NBitByte,
_NBitShort as _NBitShort,
_NBitIntC as _NBitIntC,
_NBitIntP as _NBitIntP,
_NBitInt as _NBitInt,
_NBitLong as _NBitLong,
_NBitLongLong as _NBitLongLong,
_NBitHalf as _NBitHalf,
)
_NBitSingle as _NBitSingle,
_NBitDouble as _NBitDouble,
_NBitLongDouble as _NBitLongDouble,
from ._char_codes import (
_BoolCodes as _BoolCodes,
_UInt8Codes as _UInt8Codes,
_UInt16Codes as _UInt16Codes,
_UInt32Codes as _UInt32Codes,
_UInt64Codes as _UInt64Codes,
_Int8Codes as _Int8Codes,
_Int16Codes as _Int16Codes,
_Int32Codes as _Int32Codes,
_Int64Codes as _Int64Codes,
_Float16Codes as _Float16Codes,
_Float32Codes as _Float32Codes,
_Float64Codes as _Float64Codes,
_Complex64Codes as _Complex64Codes,
_Complex128Codes as _Complex128Codes,
_ByteCodes as _ByteCodes,
_ShortCodes as _ShortCodes,
_IntCCodes as _IntCCodes,
_IntPCodes as _IntPCodes,
_IntCodes as _IntCodes,
_LongCodes as _LongCodes,
_LongLongCodes as _LongLongCodes,
_UByteCodes as _UByteCodes,
_UShortCodes as _UShortCodes,
_UIntCCodes as _UIntCCodes,
_UIntPCodes as _UIntPCodes,
_UIntCodes as _UIntCodes,
_ULongCodes as _ULongCodes,
_ULongLongCodes as _ULongLongCodes,
_HalfCodes as _HalfCodes,
_SingleCodes as _SingleCodes,
_DoubleCodes as _DoubleCodes,
_LongDoubleCodes as _LongDoubleCodes,
_CSingleCodes as _CSingleCodes,
_CDoubleCodes as _CDoubleCodes,
_CLongDoubleCodes as _CLongDoubleCodes,
_DT64Codes as _DT64Codes,
_TD64Codes as _TD64Codes,
_StrCodes as _StrCodes,
_BytesCodes as _BytesCodes,
_VoidCodes as _VoidCodes,
_ObjectCodes as _ObjectCodes,
)
from ._scalars import (
_CharLike_co as _CharLike_co,
_BoolLike_co as _BoolLike_co,
_UIntLike_co as _UIntLike_co,
_IntLike_co as _IntLike_co,
_FloatLike_co as _FloatLike_co,
_ComplexLike_co as _ComplexLike_co,
_TD64Like_co as _TD64Like_co,
_NumberLike_co as _NumberLike_co,
_ScalarLike_co as _ScalarLike_co,
_VoidLike_co as _VoidLike_co,
)
from ._shape import (
_Shape as _Shape,
_ShapeLike as _ShapeLike,
)
from ._dtype_like import (
DTypeLike as DTypeLike,
_DTypeLike as _DTypeLike,
_SupportsDType as _SupportsDType,
_VoidDTypeLike as _VoidDTypeLike,
_DTypeLikeBool as _DTypeLikeBool,
_DTypeLikeUInt as _DTypeLikeUInt,
_DTypeLikeInt as _DTypeLikeInt,
_DTypeLikeFloat as _DTypeLikeFloat,
_DTypeLikeComplex as _DTypeLikeComplex,
_DTypeLikeTD64 as _DTypeLikeTD64,
_DTypeLikeDT64 as _DTypeLikeDT64,
_DTypeLikeObject as _DTypeLikeObject,
_DTypeLikeVoid as _DTypeLikeVoid,
_DTypeLikeStr as _DTypeLikeStr,
_DTypeLikeBytes as _DTypeLikeBytes,
_DTypeLikeComplex_co as _DTypeLikeComplex_co,
)
from ._array_like import (
NDArray as NDArray,
ArrayLike as ArrayLike,
_ArrayLike as _ArrayLike,
_FiniteNestedSequence as _FiniteNestedSequence,
_SupportsArray as _SupportsArray,
_SupportsArrayFunc as _SupportsArrayFunc,
_ArrayLikeInt as _ArrayLikeInt,
_Array
_ArrayLikeComplex_co as _ArrayLikeComplex_co,
_ArrayLikeNumber_co as _ArrayLikeNumber_co,
_ArrayLikeTD64_co as _ArrayLikeTD64_co,
_ArrayLikeDT64_co as _ArrayLikeDT64_co,
_ArrayLikeObject_co as _ArrayLikeObject_co,
_ArrayLikeVoid_co as _ArrayLikeVoid_co,
_ArrayLikeStr_co as _ArrayLikeStr_co,
_ArrayLikeBytes_co as _ArrayLikeBytes_co,
_ArrayLikeUnknown as _ArrayLikeUnknown,
_UnknownType as _UnknownType,
_ArrayLikeComplex_co as _ArrayLikeComplex_co,
_ArrayLikeNumber_co as _ArrayLikeNumber_co,
_ArrayLikeTD64_co as _ArrayLikeTD64_co,
_ArrayLikeDT64_co as _ArrayLikeDT64_co,
_ArrayLikeObject_co as _ArrayLikeObject_co,
_ArrayLikeVoid_co as _ArrayLikeVoid_co,
_ArrayLikeStr_co as _ArrayLikeStr_co,
_ArrayLikeBytes_co as _ArrayLikeBytes_co,
_ArrayLikeUnknown as _ArrayLikeUnknown,
_UnknownType as _UnknownType,
if TYPE_CHECKING:
from ._ufunc import (
_UFunc_Nin1_Nout1 as _UFunc_Nin1_Nout1,
_UFunc_Nin2_Nout1 as _UFunc_Nin2_Nout1,
_UFunc_Nin1_Nout2 as _UFunc_Nin1_Nout2,
_UFunc_Nin2_Nout2 as _UFunc_Nin2_Nout2,
_GUFunc_Nin2_Nout1 as _GUFunc_Nin2_Nout1,
)
else:
_UFunc_Nin1_Nout1 = ufunc
_UFunc_Nin2_Nout1 = ufunc
_UFunc_Nin1_Nout2 = ufunc
_UFunc_Nin2_Nout2 = ufunc
_GUFunc_Nin2_Nout1 = ufunc
.\numpy\numpy\_utils\_convertions.py
"""
A set of methods retained from np.compat module that
are still used across codebase.
"""
__all__ = ["asunicode", "asbytes"]
def asunicode(s):
if isinstance(s, bytes):
return s.decode('latin1')
return str(s)
def asbytes(s):
if isinstance(s, bytes):
return s
return str(s).encode('latin1')
.\numpy\numpy\_utils\_inspect.py
"""
Subset of inspect module from upstream python
We use this instead of upstream because upstream inspect is slow to import, and
significantly contributes to numpy import times. Importing this copy has almost
no overhead.
"""
import types
__all__ = ['getargspec', 'formatargspec']
def ismethod(object):
"""Return true if the object is an instance method.
Instance method objects provide these attributes:
__doc__ documentation string
__name__ name with which this method was defined
im_class class object in which this method belongs
im_func function object containing implementation of method
im_self instance to which this method is bound, or None
"""
return isinstance(object, types.MethodType)
def isfunction(object):
"""Return true if the object is a user-defined function.
Function objects provide these attributes:
__doc__ documentation string
__name__ name with which this function was defined
func_code code object containing compiled function bytecode
func_defaults tuple of any default values for arguments
func_doc (same as __doc__)
func_globals global namespace in which this function was defined
func_name (same as __name__)
"""
return isinstance(object, types.FunctionType)
def iscode(object):
"""Return true if the object is a code object.
Code objects provide these attributes:
co_argcount number of arguments (not including * or ** args)
co_code string of raw compiled bytecode
co_consts tuple of constants used in the bytecode
co_filename name of file in which this code object was created
co_firstlineno number of first line in Python source code
co_flags bitmap: 1=optimized | 2=newlocals | 4=*arg | 8=**arg
co_lnotab encoded mapping of line numbers to bytecode indices
co_name name with which this code object was defined
co_names tuple of names of local variables
co_nlocals number of local variables
co_stacksize virtual machine stack space required
co_varnames tuple of names of arguments and local variables
"""
return isinstance(object, types.CodeType)
CO_OPTIMIZED, CO_NEWLOCALS, CO_VARARGS, CO_VARKEYWORDS = 1, 2, 4, 8
def getargs(co):
"""Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where 'args' is
a list of argument names (possibly containing nested lists), and
'varargs' and 'varkw' are the names of the * and ** arguments or None.
"""
if not iscode(co):
raise TypeError('arg is not a code object')
nargs = co.co_argcount
names = co.co_varnames
args = list(names[:nargs])
for i in range(nargs):
if args[i][:1] in ['', '.']:
raise TypeError("tuple function arguments are not supported")
varargs = None
if co.co_flags & CO_VARARGS:
varargs = co.co_varnames[nargs]
nargs = nargs + 1
varkw = None
if co.co_flags & CO_VARKEYWORDS:
varkw = co.co_varnames[nargs]
return args, varargs, varkw
def getargspec(func):
"""Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
"""
if ismethod(func):
func = func.__func__
if not isfunction(func):
raise TypeError('arg is not a Python function')
args, varargs, varkw = getargs(func.__code__)
return args, varargs, varkw, func.__defaults__
def getargvalues(frame):
"""Get information about arguments passed into a particular frame.
A tuple of four things is returned: (args, varargs, varkw, locals).
'args' is a list of the argument names (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dictionary of the given frame.
"""
args, varargs, varkw = getargs(frame.f_code)
return args, varargs, varkw, frame.f_locals
def joinseq(seq):
"""Join sequence elements into a string, handling single element case.
"""
if len(seq) == 1:
return '(' + seq[0] + ',)'
else:
return '(' + ', '.join(seq) + ')'
def strseq(object, convert, join=joinseq):
"""Recursively walk a sequence, stringifying each element.
"""
if type(object) in [list, tuple]:
return join([strseq(_o, convert, join) for _o in object])
else:
return convert(object)
def formatargspec(args, varargs=None, varkw=None, defaults=None,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
join=joinseq):
"""Format an argument spec from the 4 values returned by getargspec.
The first four arguments are (args, varargs, varkw, defaults). The
other four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional function to format the sequence of arguments.
"""
specs = []
if defaults:
firstdefault = len(args) - len(defaults)
for i in range(len(args)):
spec = strseq(args[i], formatarg, join)
if defaults and i >= firstdefault:
spec = spec + formatvalue(defaults[i - firstdefault])
specs.append(spec)
if varargs is not None:
specs.append(formatvarargs(varargs))
if varkw is not None:
specs.append(formatvarkw(varkw))
return '(' + ', '.join(specs) + ')'
def formatargvalues(args, varargs, varkw, locals,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
join=joinseq):
"""
根据从 getargvalues 返回的四个值格式化参数规范。
前四个参数是 (args, varargs, varkw, locals)。接下来四个参数是相应的可选格式化函数,
用于将名称和值转换为字符串。第九个参数是一个可选的函数,用于格式化参数序列。
"""
def convert(name, locals=locals,
formatarg=formatarg, formatvalue=formatvalue):
return formatarg(name) + formatvalue(locals[name])
specs = [strseq(arg, convert, join) for arg in args]
if varargs:
specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
if varkw:
specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
return '(' + ', '.join(specs) + ')'
.\numpy\numpy\_utils\_pep440.py
"""Utility to compare pep440 compatible version strings.
The LooseVersion and StrictVersion classes that distutils provides don't
work; they don't recognize anything like alpha/beta/rc/dev versions.
"""
import collections
import itertools
import re
__all__ = [
"parse", "Version", "LegacyVersion", "InvalidVersion", "VERSION_PATTERN",
]
class Infinity:
def __repr__(self):
return "Infinity"
def __hash__(self):
return hash(repr(self))
def __lt__(self, other):
return False
def __le__(self, other):
return False
def __eq__(self, other):
return isinstance(other, self.__class__)
def __ne__(self, other):
return not isinstance(other, self.__class__)
def __gt__(self, other):
return True
def __ge__(self, other):
return True
def __neg__(self):
return NegativeInfinity
Infinity = Infinity()
class NegativeInfinity:
def __repr__(self):
return "-Infinity"
def __hash__(self):
return hash(repr(self))
def __lt__(self, other):
return True
def __le__(self, other):
return True
def __eq__(self, other):
return isinstance(other, self.__class__)
def __ne__(self, other):
return not isinstance(other, self.__class__)
def __gt__(self, other):
return False
def __ge__(self, other):
return False
def __neg__(self):
return Infinity
NegativeInfinity = NegativeInfinity()
_Version = collections.namedtuple(
"_Version",
["epoch", "release", "dev", "pre", "post", "local"],
def parse(version):
"""
Parse the given version string and return either a :class:`Version` object
or a :class:`LegacyVersion` object depending on if the given version is
a valid PEP 440 version or a legacy version.
"""
try:
return Version(version)
except InvalidVersion:
return LegacyVersion(version)
class InvalidVersion(ValueError):
"""
An invalid version was found, users should refer to PEP 440.
"""
class _BaseVersion:
def __hash__(self):
return hash(self._key)
def __lt__(self, other):
return self._compare(other, lambda s, o: s < o)
def __le__(self, other):
return self._compare(other, lambda s, o: s <= o)
def __eq__(self, other):
return self._compare(other, lambda s, o: s == o)
def __ge__(self, other):
return self._compare(other, lambda s, o: s >= o)
def __gt__(self, other):
return self._compare(other, lambda s, o: s > o)
def __ne__(self, other):
return self._compare(other, lambda s, o: s != o)
def _compare(self, other, method):
if not isinstance(other, _BaseVersion):
return NotImplemented
return method(self._key, other._key)
class LegacyVersion(_BaseVersion):
def __init__(self, version):
self._version = str(version)
self._key = _legacy_cmpkey(self._version)
def __str__(self):
return self._version
def __repr__(self):
return "<LegacyVersion({0})>".format(repr(str(self)))
@property
def public(self):
return self._version
@property
def base_version(self):
return self._version
@property
def local(self):
return None
@property
def is_prerelease(self):
return False
@property
def is_postrelease(self):
return False
_legacy_version_component_re = re.compile(
r"(\d+ | [a-z]+ | \.| -)", re.VERBOSE,
)
_legacy_version_replacement_map = {
"pre": "c", "preview": "c", "-": "final-", "rc": "c", "dev": "@",
}
def _parse_version_parts(s):
for part in _legacy_version_component_re.split(s):
part = _legacy_version_replacement_map.get(part, part)
if not part or part == ".":
continue
if part[:1] in "0123456789":
yield part.zfill(8)
else:
yield "*" + part
yield "*final"
def _legacy_cmpkey(version):
epoch = -1
parts = []
for part in _parse_version_parts(version.lower()):
if part.startswith("*"):
if part < "*final":
while parts and parts[-1] == "*final-":
parts.pop()
while parts and parts[-1] == "00000000":
parts.pop()
parts.append(part)
parts = tuple(parts)
return epoch, parts
VERSION_PATTERN = r"""
v? # 可选的 'v' 前缀
(?:
(?:(?P<epoch>[0-9]+)!)? # epoch
(?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
(?P<pre> # pre-release
[-_\.]? # 可选的分隔符
(?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview)) # pre-release 类型
[-_\.]? # 可选的分隔符
(?P<pre_n>[0-9]+)? # 可选的 pre-release 版本号
)?
(?P<post> # post release
(?:-(?P<post_n1>[0-9]+)) # post-release 版本号1
| # 或者
(?:
[-_\.]? # 可选的分隔符
(?P<post_l>post|rev|r) # post-release 类型
[-_\.]? # 可选的分隔符
(?P<post_n2>[0-9]+)? # 可选的 post-release 版本号2
)
)?
(?P<dev> # dev release
[-_\.]? # 可选的分隔符
(?P<dev_l>dev) # dev-release 类型
[-_\.]? # 可选的分隔符
(?P<dev_n>[0-9]+)? # 可选的 dev-release 版本号
)?
)
(?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
"""
class Version(_BaseVersion):
_regex = re.compile(
r"^\s*" + VERSION_PATTERN + r"\s*$",
re.VERBOSE | re.IGNORECASE,
)
def __init__(self, version):
match = self._regex.search(version)
if not match:
raise InvalidVersion("Invalid version: '{0}'".format(version))
self._version = _Version(
epoch=int(match.group("epoch")) if match.group("epoch") else 0,
release=tuple(int(i) for i in match.group("release").split(".")),
pre=_parse_letter_version(
match.group("pre_l"),
match.group("pre_n"),
),
post=_parse_letter_version(
match.group("post_l"),
match.group("post_n1") or match.group("post_n2"),
),
dev=_parse_letter_version(
match.group("dev_l"),
match.group("dev_n"),
),
local=_parse_local_version(match.group("local")),
)
self._key = _cmpkey(
self._version.epoch,
self._version.release,
self._version.pre,
self._version.post,
self._version.dev,
self._version.local,
)
def __repr__(self):
return "<Version({0})>".format(repr(str(self)))
def __str__(self):
parts = []
if self._version.epoch != 0:
parts.append("{0}!".format(self._version.epoch))
parts.append(".".join(str(x) for x in self._version.release))
if self._version.pre is not None:
parts.append("".join(str(x) for x in self._version.pre))
if self._version.post is not None:
parts.append(".post{0}".format(self._version.post[1]))
if self._version.dev is not None:
parts.append(".dev{0}".format(self._version.dev[1]))
if self._version.local is not None:
parts.append(
"+{0}".format(".".join(str(x) for x in self._version.local))
)
return "".join(parts)
@property
def public(self):
return str(self).split("+", 1)[0]
@property
def base_version(self):
parts = []
if self._version.epoch != 0:
parts.append("{0}!".format(self._version.epoch))
parts.append(".".join(str(x) for x in self._version.release))
return "".join(parts)
@property
def local(self):
version_string = str(self)
if "+" in version_string:
return version_string.split("+", 1)[1]
@property
def is_prerelease(self):
return bool(self._version.dev or self._version.pre)
@property
def is_postrelease(self):
return bool(self._version.post)
def _parse_letter_version(letter, number):
if letter:
if number is None:
number = 0
letter = letter.lower()
if letter == "alpha":
letter = "a"
elif letter == "beta":
letter = "b"
elif letter in ["c", "pre", "preview"]:
letter = "rc"
elif letter in ["rev", "r"]:
letter = "post"
return letter, int(number)
if not letter and number:
letter = "post"
return letter, int(number)
_local_version_seperators = re.compile(r"[\._-]")
def _parse_local_version(local):
"""
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
"""
if local is not None:
return tuple(
part.lower() if not part.isdigit() else int(part)
for part in _local_version_seperators.split(local)
)
def _cmpkey(epoch, release, pre, post, dev, local):
release = tuple(
reversed(list(
itertools.dropwhile(
lambda x: x == 0,
reversed(release),
)
))
)
if pre is None and post is None and dev is not None:
pre = -Infinity
elif pre is None:
pre = Infinity
if post is None:
post = -Infinity
if dev is None:
dev = Infinity
if local is None:
local = -Infinity
else:
local = tuple(
(i, "") if isinstance(i, int) else (-Infinity, i)
for i in local
)
return epoch, release, pre, post, dev, local
.\numpy\numpy\_utils\__init__.py
"""
This is a module for defining private helpers which do not depend on the
rest of NumPy.
Everything in here must be self-contained so that it can be
imported anywhere else without creating circular imports.
If a utility requires the import of NumPy, it probably belongs
in ``numpy._core``.
"""
import functools
import warnings
from ._convertions import asunicode, asbytes
def set_module(module):
"""Private decorator for overriding __module__ on a function or class.
Example usage::
@set_module('numpy')
def example():
pass
assert example.__module__ == 'numpy'
"""
def decorator(func):
if module is not None:
func.__module__ = module
return func
return decorator
def _rename_parameter(old_names, new_names, dep_version=None):
"""
Generate decorator for backward-compatible keyword renaming.
Apply the decorator generated by `_rename_parameter` to functions with a
renamed parameter to maintain backward-compatibility.
After decoration, the function behaves as follows:
If only the new parameter is passed into the function, behave as usual.
If only the old parameter is passed into the function (as a keyword), raise
a DeprecationWarning if `dep_version` is provided, and behave as usual
otherwise.
If both old and new parameters are passed into the function, raise a
DeprecationWarning if `dep_version` is provided, and raise the appropriate
TypeError (function got multiple values for argument).
Parameters
----------
old_names : list of str
Old names of parameters
new_names : list of str
New names of parameters
dep_version : str, optional
Version of NumPy in which old parameter was deprecated in the format
'X.Y.Z'. If supplied, the deprecation message will indicate that
support for the old parameter will be removed in version 'X.Y+2.Z'
Notes
-----
Untested with functions that accept *args. Probably won't work as written.
"""
def decorator(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
for old_name, new_name in zip(old_names, new_names):
if old_name in kwargs:
if dep_version:
end_version = dep_version.split('.')
end_version[1] = str(int(end_version[1]) + 2)
end_version = '.'.join(end_version)
msg = (f"Use of keyword argument `{old_name}` is "
f"deprecated and replaced by `{new_name}`. "
f"Support for `{old_name}` will be removed "
f"in NumPy {end_version}.")
warnings.warn(msg, DeprecationWarning, stacklevel=2)
if new_name in kwargs:
msg = (f"{fun.__name__}() got multiple values for "
f"argument now known as `{new_name}`")
raise TypeError(msg)
kwargs[new_name] = kwargs.pop(old_name)
return fun(*args, **kwargs)
return wrapper
.\numpy\numpy\__init__.cython-30.pxd
from cpython.ref cimport Py_INCREF
from cpython.object cimport PyObject, PyTypeObject, PyObject_TypeCheck
cimport libc.stdio as stdio
cdef extern from *:
"""
/* Using NumPy API declarations from "numpy/__init__.cython-30.pxd" */
"""
cdef extern from "numpy/arrayobject.h":
ctypedef signed long npy_intp
ctypedef unsigned long npy_uintp
ctypedef unsigned char npy_bool
ctypedef signed char npy_byte
ctypedef signed short npy_short
ctypedef signed int npy_int
ctypedef signed long npy_long
ctypedef signed long long npy_longlong
ctypedef unsigned char npy_ubyte
ctypedef unsigned short npy_ushort
ctypedef unsigned int npy_uint
ctypedef unsigned long npy_ulong
ctypedef unsigned long long npy_ulonglong
ctypedef float npy_float
ctypedef double npy_double
ctypedef long double npy_longdouble
ctypedef signed char npy_int8
ctypedef signed short npy_int16
ctypedef signed int npy_int32
ctypedef signed long long npy_int64
ctypedef signed long long npy_int96
ctypedef signed long long npy_int128
ctypedef unsigned char npy_uint8
ctypedef unsigned short npy_uint16
ctypedef unsigned int npy_uint32
ctypedef unsigned long long npy_uint64
ctypedef unsigned long long npy_uint96
ctypedef unsigned long long npy_uint128
ctypedef float npy_float32
ctypedef double npy_float64
ctypedef long double npy_float80
ctypedef long double npy_float96
ctypedef long double npy_float128
ctypedef struct npy_cfloat:
pass
ctypedef struct npy_cdouble:
pass
ctypedef struct npy_clongdouble:
pass
ctypedef struct npy_complex64:
pass
ctypedef struct npy_complex128:
pass
ctypedef struct npy_complex160:
pass
ctypedef struct npy_complex192:
pass
ctypedef struct npy_complex256:
pass
ctypedef struct PyArray_Dims:
npy_intp *ptr
int len
cdef enum NPY_TYPES:
NPY_BOOL
NPY_BYTE
NPY_UBYTE
NPY_SHORT
NPY_USHORT
NPY_INT
NPY_UINT
NPY_LONG
NPY_ULONG
NPY_LONGLONG
NPY_ULONGLONG
NPY_FLOAT
NPY_DOUBLE
NPY_LONGDOUBLE
NPY_CFLOAT
NPY_CDOUBLE
NPY_CLONGDOUBLE
NPY_OBJECT
NPY_STRING
NPY_UNICODE
NPY_VOID
NPY_DATETIME
NPY_TIMEDELTA
NPY_NTYPES_LEGACY
NPY_NOTYPE
NPY_INT8
NPY_INT16
NPY_INT32
NPY_INT64
NPY_INT128
NPY_INT256
NPY_UINT8
NPY_UINT16
NPY_UINT32
NPY_UINT64
NPY_UINT128
NPY_UINT256
NPY_FLOAT16
NPY_FLOAT32
NPY_FLOAT64
NPY_FLOAT80
NPY_FLOAT96
NPY_FLOAT128
NPY_FLOAT256
NPY_COMPLEX32
NPY_COMPLEX64
NPY_COMPLEX128
NPY_COMPLEX160
NPY_COMPLEX192
NPY_COMPLEX256
NPY_COMPLEX512
NPY_INTP
NPY_DEFAULT_INT
ctypedef enum NPY_ORDER:
NPY_ANYORDER
NPY_CORDER
NPY_FORTRANORDER
NPY_KEEPORDER
ctypedef enum NPY_CASTING:
NPY_NO_CASTING
NPY_EQUIV_CASTING
NPY_SAFE_CASTING
NPY_SAME_KIND_CASTING
NPY_UNSAFE_CASTING
ctypedef enum NPY_CLIPMODE:
NPY_CLIP
NPY_WRAP
NPY_RAISE
ctypedef enum NPY_SCALARKIND:
NPY_NOSCALAR
NPY_BOOL_SCALAR
NPY_INTPOS_SCALAR
NPY_INTNEG_SCALAR
NPY_FLOAT_SCALAR
NPY_COMPLEX_SCALAR
NPY_OBJECT_SCALAR
ctypedef enum NPY_SORTKIND:
NPY_QUICKSORT
NPY_HEAPSORT
NPY_MERGESORT
ctypedef enum NPY_SEARCHSIDE:
NPY_SEARCHLEFT
NPY_SEARCHRIGHT
enum:
NPY_C_CONTIGUOUS
NPY_F_CONTIGUOUS
NPY_CONTIGUOUS
NPY_FORTRAN
NPY_OWNDATA
NPY_FORCECAST
NPY_ENSURECOPY
NPY_ENSUREARRAY
NPY_ELEMENTSTRIDES
NPY_ALIGNED
NPY_NOTSWAPPED
NPY_WRITEABLE
NPY_ARR_HAS_DESCR
NPY_BEHAVED
NPY_BEHAVED_NS
NPY_CARRAY
NPY_CARRAY_RO
NPY_FARRAY
NPY_FARRAY_RO
NPY_DEFAULT
NPY_IN_ARRAY
NPY_OUT_ARRAY
NPY_INOUT_ARRAY
NPY_IN_FARRAY
NPY_OUT_FARRAY
NPY_INOUT_FARRAY
NPY_UPDATE_ALL
enum:
NPY_ARRAY_C_CONTIGUOUS
NPY_ARRAY_F_CONTIGUOUS
NPY_ARRAY_OWNDATA
NPY_ARRAY_FORCECAST
NPY_ARRAY_ENSURECOPY
NPY_ARRAY_ENSUREARRAY
NPY_ARRAY_ELEMENTSTRIDES
NPY_ARRAY_ALIGNED
NPY_ARRAY_NOTSWAPPED
NPY_ARRAY_WRITEABLE
NPY_ARRAY_WRITEBACKIFCOPY
NPY_ARRAY_BEHAVED
NPY_ARRAY_BEHAVED_NS
NPY_ARRAY_CARRAY
NPY_ARRAY_CARRAY_RO
NPY_ARRAY_FARRAY
NPY_ARRAY_FARRAY_RO
NPY_ARRAY_DEFAULT
NPY_ARRAY_IN_ARRAY
NPY_ARRAY_OUT_ARRAY
NPY_ARRAY_INOUT_ARRAY
NPY_ARRAY_IN_FARRAY
NPY_ARRAY_OUT_FARRAY
NPY_ARRAY_INOUT_FARRAY
NPY_ARRAY_UPDATE_ALL
cdef enum:
NPY_MAXDIMS
NPY_RAVEL_AXIS
ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *)
ctypedef struct PyArray_ArrayDescr:
PyObject* shape
ctypedef struct PyArray_Descr:
pass
ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]:
cdef PyTypeObject* typeobj
cdef char kind
cdef char type
cdef char byteorder
cdef int type_num
@property
cdef inline npy_intp itemsize(self) noexcept nogil:
return PyDataType_ELSIZE(self)
@property
cdef inline npy_intp alignment(self) noexcept nogil:
return PyDataType_ALIGNMENT(self)
@property
cdef inline object fields(self):
return <object>PyDataType_FIELDS(self)
@property
cdef inline tuple names(self):
return <tuple>PyDataType_NAMES(self)
@property
cdef inline PyArray_ArrayDescr* subarray(self) noexcept nogil:
return PyDataType_SUBARRAY(self)
@property
cdef inline npy_uint64 flags(self) noexcept nogil:
"""The data types flags."""
return PyDataType_FLAGS(self)
ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]:
pass
ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]:
@property
cdef inline int numiter(self) noexcept nogil:
"""返回需要广播到相同形状的数组的数量。"""
return PyArray_MultiIter_NUMITER(self)
@property
cdef inline npy_intp size(self) noexcept nogil:
"""返回广播后的总大小。"""
return PyArray_MultiIter_SIZE(self)
@property
cdef inline npy_intp index(self) noexcept nogil:
"""返回当前广播结果的一维索引。"""
return PyArray_MultiIter_INDEX(self)
@property
cdef inline int nd(self) noexcept nogil:
"""返回广播结果的维数。"""
return PyArray_MultiIter_NDIM(self)
@property
cdef inline npy_intp* dimensions(self) noexcept nogil:
"""返回广播结果的形状。"""
return PyArray_MultiIter_DIMS(self)
@property
cdef inline void** iters(self) noexcept nogil:
"""返回一个包含迭代器对象的数组,这些迭代器用于一起广播的数组。
返回后,这些迭代器将被调整以进行广播。"""
return PyArray_MultiIter_ITERS(self)
ctypedef struct PyArrayObject:
pass
ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]:
cdef __cythonbufferdefaults__ = {"mode": "strided"}
@property
cdef inline PyObject* base(self) noexcept nogil:
"""Returns a borrowed reference to the object owning the data/memory.
"""
return PyArray_BASE(self)
@property
cdef inline dtype descr(self):
"""Returns an owned reference to the dtype of the array.
"""
return <dtype>PyArray_DESCR(self)
@property
cdef inline int ndim(self) noexcept nogil:
"""Returns the number of dimensions in the array.
"""
return PyArray_NDIM(self)
@property
cdef inline npy_intp *shape(self) noexcept nogil:
"""Returns a pointer to the dimensions/shape of the array.
The number of elements matches the number of dimensions of the array (ndim).
Can return NULL for 0-dimensional arrays.
"""
return PyArray_DIMS(self)
@property
cdef inline npy_intp *strides(self) noexcept nogil:
"""Returns a pointer to the strides of the array.
The number of elements matches the number of dimensions of the array (ndim).
"""
return PyArray_STRIDES(self)
@property
cdef inline npy_intp size(self) noexcept nogil:
"""Returns the total size (in number of elements) of the array.
"""
return PyArray_SIZE(self)
@property
cdef inline char* data(self) noexcept nogil:
"""The pointer to the data buffer as a char*.
This is provided for legacy reasons to avoid direct struct field access.
For new code that needs this access, you probably want to cast the result
of `PyArray_DATA()` instead, which returns a 'void*'.
"""
return PyArray_BYTES(self)
int _import_array() except -1
int __pyx_import_array "_import_array"() except -1
bint PyArray_CHKFLAGS(ndarray m, int flags) nogil
bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil
bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil
bint PyArray_ISCONTIGUOUS(ndarray m) nogil
bint PyArray_ISWRITEABLE(ndarray m) nogil
bint PyArray_ISALIGNED(ndarray m) nogil
int PyArray_NDIM(ndarray) nogil
bint PyArray_ISONESEGMENT(ndarray) nogil
bint PyArray_ISFORTRAN(ndarray) nogil
int PyArray_FORTRANIF(ndarray) nogil
void* PyArray_DATA(ndarray) nogil
char* PyArray_BYTES(ndarray) nogil
注释:
ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]:
cdef __cythonbufferdefaults__ = {"mode": "strided"}
@property
cdef inline PyObject* base(self) noexcept nogil:
"""返回一个借用引用,指向拥有数据/内存的对象。
"""
return PyArray_BASE(self)
@property
cdef inline dtype descr(self):
"""返回数组的 dtype 的拥有引用。
"""
return <dtype>PyArray_DESCR(self)
@property
cdef inline int ndim(self) noexcept nogil:
"""返回数组的维度数目。
"""
return PyArray_NDIM(self)
@property
cdef inline npy_intp *shape(self) noexcept nogil:
"""返回指向数组维度/形状的指针。
元素数目与数组的维度数目 (ndim) 相匹配。
对于0维数组可能返回NULL。
"""
return PyArray_DIMS(self)
@property
cdef inline npy_intp *strides(self) noexcept nogil:
"""返回指向数组步长的指针。
元素数目与数组的维度数目 (ndim) 相匹配。
"""
return PyArray_STRIDES(self)
@property
cdef inline npy_intp size(self) noexcept nogil:
"""返回数组的总大小(元素数目)。
"""
return PyArray_SIZE(self)
@property
cdef inline char* data(self) noexcept nogil:
"""指向数据缓冲区的 char* 指针。
出于遗留原因提供此方法,以避免直接访问结构字段。
对于需要此访问的新代码,建议使用 `PyArray_DATA()` 的结果进行转换,它返回 'void*'。
"""
return PyArray_BYTES(self)
int _import_array() except -1
int __pyx_import_array "_import_array"() except -1
bint PyArray_CHKFLAGS(ndarray m, int flags) nogil
bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil
bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil
bint PyArray_ISCONTIGUOUS(ndarray m) nogil
bint PyArray_ISWRITEABLE(ndarray m) nogil
bint PyArray_ISALIGNED(ndarray m) nogil
int PyArray_NDIM(ndarray) nogil
bint PyArray_ISONESEGMENT(ndarray) nogil
bint PyArray_ISFORTRAN(ndarray) nogil
int PyArray_FORTRANIF(ndarray) nogil
void* PyArray_DATA(ndarray) nogil
char* PyArray_BYTES(ndarray) nogil
npy_intp* PyArray_DIMS(ndarray) nogil
// 返回指向数组维度的指针,不会引发GIL
npy_intp* PyArray_STRIDES(ndarray) nogil
// 返回指向数组步幅的指针,不会引发GIL
npy_intp PyArray_DIM(ndarray, size_t) nogil
// 返回指定索引的数组维度大小,不会引发GIL
npy_intp PyArray_STRIDE(ndarray, size_t) nogil
// 返回指定索引的数组步幅大小,不会引发GIL
PyObject *PyArray_BASE(ndarray) nogil // returns borrowed reference!
// 返回数组的基础对象,借用引用,不会引发GIL
PyArray_Descr *PyArray_DESCR(ndarray) nogil // returns borrowed reference to dtype!
// 返回数组的描述符,借用引用,不会引发GIL
PyArray_Descr *PyArray_DTYPE(ndarray) nogil // returns borrowed reference to dtype! NP 1.7+ alias for descr.
// 返回数组的数据类型描述符,借用引用,不会引发GIL,NP 1.7+中是descr的别名
int PyArray_FLAGS(ndarray) nogil
// 返回数组的标志位,不会引发GIL
void PyArray_CLEARFLAGS(ndarray, int flags) nogil // Added in NumPy 1.7
// 清除数组的指定标志位,不会引发GIL,NumPy 1.7中新增
void PyArray_ENABLEFLAGS(ndarray, int flags) nogil // Added in NumPy 1.7
// 启用数组的指定标志位,不会引发GIL,NumPy 1.7中新增
npy_intp PyArray_ITEMSIZE(ndarray) nogil
// 返回数组元素的大小(字节数),不会引发GIL
int PyArray_TYPE(ndarray arr) nogil
// 返回数组的数据类型编号,不会引发GIL
object PyArray_GETITEM(ndarray arr, void *itemptr)
// 从数组中获取指定位置的元素,不会引发GIL
int PyArray_SETITEM(ndarray arr, void *itemptr, object obj) except -1
// 将对象设置到数组的指定位置,不会引发GIL,异常时返回-1
bint PyTypeNum_ISBOOL(int) nogil
// 检查指定的数据类型编号是否是布尔类型,不会引发GIL
bint PyTypeNum_ISUNSIGNED(int) nogil
// 检查指定的数据类型编号是否是无符号整数类型,不会引发GIL
bint PyTypeNum_ISSIGNED(int) nogil
// 检查指定的数据类型编号是否是有符号整数类型,不会引发GIL
bint PyTypeNum_ISINTEGER(int) nogil
// 检查指定的数据类型编号是否是整数类型,不会引发GIL
bint PyTypeNum_ISFLOAT(int) nogil
// 检查指定的数据类型编号是否是浮点数类型,不会引发GIL
bint PyTypeNum_ISNUMBER(int) nogil
// 检查指定的数据类型编号是否是数值类型,不会引发GIL
bint PyTypeNum_ISSTRING(int) nogil
// 检查指定的数据类型编号是否是字符串类型,不会引发GIL
bint PyTypeNum_ISCOMPLEX(int) nogil
// 检查指定的数据类型编号是否是复数类型,不会引发GIL
bint PyTypeNum_ISFLEXIBLE(int) nogil
// 检查指定的数据类型编号是否是灵活类型,不会引发GIL
bint PyTypeNum_ISUSERDEF(int) nogil
// 检查指定的数据类型编号是否是用户定义类型,不会引发GIL
bint PyTypeNum_ISEXTENDED(int) nogil
// 检查指定的数据类型编号是否是扩展类型,不会引发GIL
bint PyTypeNum_ISOBJECT(int) nogil
// 检查指定的数据类型编号是否是对象类型,不会引发GIL
npy_intp PyDataType_ELSIZE(dtype) nogil
// 返回数据类型描述符的元素大小(字节数),不会引发GIL
npy_intp PyDataType_ALIGNMENT(dtype) nogil
// 返回数据类型描述符的对齐方式,不会引发GIL
PyObject* PyDataType_METADATA(dtype) nogil
// 返回数据类型描述符的元数据对象,不会引发GIL
PyArray_ArrayDescr* PyDataType_SUBARRAY(dtype) nogil
// 返回数据类型描述符的子数组描述符,不会引发GIL
PyObject* PyDataType_NAMES(dtype) nogil
// 返回数据类型描述符的字段名称,不会引发GIL
PyObject* PyDataType_FIELDS(dtype) nogil
// 返回数据类型描述符的字段描述符,不会引发GIL
bint PyDataType_ISBOOL(dtype) nogil
// 检查指定的数据类型描述符是否是布尔类型,不会引发GIL
bint PyDataType_ISUNSIGNED(dtype) nogil
// 检查指定的数据类型描述符是否是无符号整数类型,不会引发GIL
bint PyDataType_ISSIGNED(dtype) nogil
// 检查指定的数据类型描述符是否是有符号整数类型,不会引发GIL
bint PyDataType_ISINTEGER(dtype) nogil
// 检查指定的数据类型描述符是否是整数类型,不会引发GIL
bint PyDataType_ISFLOAT(dtype) nogil
// 检查指定的数据类型描述符是否是浮点数类型,不会引发GIL
bint PyDataType_ISNUMBER(dtype) nogil
// 检查指定的数据类型描述符是否是数值类型,不会引发GIL
bint PyDataType_ISSTRING(dtype) nogil
// 检查指定的数据类型描述符是否是字符串类型,不会引发GIL
bint PyDataType_ISCOMPLEX(dtype) nogil
// 检查指定的数据类型描述符是否是复数类型,不会引发GIL
bint PyDataType_ISFLEXIBLE(dtype) nogil
// 检查指定的数据类型描述符是否是灵活类型,不会引发GIL
bint PyDataType_ISUSERDEF(dtype) nogil
// 检查指定的数据类型描述符是否是用户定义类型,不会引发GIL
bint PyDataType_ISEXTENDED(dtype) nogil
// 检查指定的数据类型描述符是否是扩展类型,不会引发GIL
bint PyDataType_ISOBJECT(dtype) nogil
// 检查指定的数据类型描述符是否是对象类型,不会引发GIL
bint PyDataType_HASFIELDS(dtype) nogil
// 检查指定的数据类型描述符是否有字段,不会引发GIL
bint PyDataType_HASSUBARRAY(dtype) nogil
// 检查指定的数据类型描述符是否有子数组,不会引发GIL
npy_uint64 PyDataType_FLAGS(dtype) nogil
// 返回数据类型描述符的标志位,不会引发GIL
bint PyArray_ISBOOL(ndarray) nogil
// 检查数组是否是布尔类型,不会引发GIL
bint PyArray_ISUNSIGNED(ndarray) nogil
// 检查数组是否是无符号整数类型,不会引发GIL
bint PyArray_ISSIGNED(ndarray) nogil
// 检查数组是否是有符号整数类型,不会引发GIL
bint PyArray_ISINTEGER(ndarray) nogil
// 检查数组是否是整数类型,不会引发GIL
bint PyArray_ISFLOAT(ndarray) nogil
// 检查数组是否是浮点数类型,不会引发GIL
bint PyArray_ISNUMBER(ndarray) nogil
// 检查数组是否是数值类型,不会引发GIL
bint PyArray
bint PyArray_IsNativeByteOrder(char) nogil
bint PyArray_ISNOTSWAPPED(ndarray) nogil
bint PyArray_ISBYTESWAPPED(ndarray) nogil
bint PyArray_FLAGSWAP(ndarray, int) nogil
bint PyArray_ISCARRAY(ndarray) nogil
bint PyArray_ISCARRAY_RO(ndarray) nogil
bint PyArray_ISFARRAY(ndarray) nogil
bint PyArray_ISFARRAY_RO(ndarray) nogil
bint PyArray_ISBEHAVED(ndarray) nogil
bint PyArray_ISBEHAVED_RO(ndarray) nogil
bint PyDataType_ISNOTSWAPPED(dtype) nogil
bint PyDataType_ISBYTESWAPPED(dtype) nogil
bint PyArray_DescrCheck(object)
bint PyArray_Check(object)
bint PyArray_CheckExact(object)
bint PyArray_IsZeroDim(object)
bint PyArray_CheckScalar(object)
bint PyArray_IsPythonNumber(object)
bint PyArray_IsPythonScalar(object)
bint PyArray_IsAnyScalar(object)
bint PyArray_CheckAnyScalar(object)
ndarray PyArray_GETCONTIGUOUS(ndarray)
bint PyArray_SAMESHAPE(ndarray, ndarray) nogil
npy_intp PyArray_SIZE(ndarray) nogil
npy_intp PyArray_NBYTES(ndarray) nogil
object PyArray_FROM_O(object)
object PyArray_FROM_OF(object m, int flags)
object PyArray_FROM_OT(object m, int type)
object PyArray_FROM_OTF(object m, int type, int flags)
object PyArray_FROMANY(object m, int type, int min, int max, int flags)
object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran)
object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran)
void PyArray_FILLWBYTE(ndarray, int val)
object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth)
unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2)
bint PyArray_EquivByteorders(int b1, int b2) nogil
object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum)
object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data)
object PyArray_ToScalar(void* data, ndarray arr)
void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil
void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil
void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil
void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil
object PyArray_Copy(ndarray)
object PyArray_FromObject(object op, int type, int min_depth, int max_depth)
object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth)
object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth)
object PyArray_Cast(ndarray mp, int type_num)
object PyArray_Take(ndarray ap, object items, int axis)
object PyArray_Put(ndarray ap, object items, object values)
void PyArray_ITER_RESET(flatiter it) nogil
void PyArray_ITER_NEXT(flatiter it) nogil
void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil
void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil
void* PyArray_ITER_DATA(flatiter it) nogil
bint PyArray_ITER_NOTDONE(flatiter it) nogil
void PyArray_MultiIter_RESET(broadcast multi) nogil
void PyArray_MultiIter_NEXT(broadcast multi) nogil
void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil
void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil
void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil
void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil
bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil
npy_intp PyArray_MultiIter_SIZE(broadcast multi) nogil
int PyArray_MultiIter_NDIM(broadcast multi) nogil
npy_intp PyArray_MultiIter_INDEX(broadcast multi) nogil
int PyArray_MultiIter_NUMITER(broadcast multi) nogil
npy_intp* PyArray_MultiIter_DIMS(broadcast multi) nogil
void** PyArray_MultiIter_ITERS(broadcast multi) nogil
int PyArray_INCREF (ndarray) except *
int PyArray_XDECREF (ndarray) except *
dtype PyArray_DescrFromType (int)
object PyArray_TypeObjectFromType (int)
char * PyArray_Zero (ndarray)
char * PyArray_One (ndarray)
int PyArray_CanCastSafely (int, int)
npy_bool PyArray_CanCastTo (dtype, dtype)
int PyArray_ObjectType (object, int) except 0
dtype PyArray_DescrFromObject (object, dtype)
dtype PyArray_DescrFromScalar (object)
dtype PyArray_DescrFromTypeObject (object)
npy_intp PyArray_Size (object)
object PyArray_EnsureArray (object)
object PyArray_EnsureAnyArray (object)
object PyArray_Return (ndarray)
object PyArray_Byteswap (ndarray, npy_bool)
object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER)
int PyArray_CopyInto (ndarray, ndarray) except -1
int PyArray_CopyAnyInto (ndarray, ndarray) except -1
int PyArray_CopyObject (ndarray, object) except -1
object PyArray_NewCopy (ndarray, NPY_ORDER)
object PyArray_ToList (ndarray)
object PyArray_ToString (ndarray, NPY_ORDER)
int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *) except -1
int PyArray_Dump (object, object, int) except -1
object PyArray_Dumps (object, int)
int PyArray_ValidType (int)
void PyArray_UpdateFlags (ndarray, int)
object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object)
dtype PyArray_DescrNewFromType (int)
double PyArray_GetPriority (object, double)
object PyArray_IterNew (object)
object PyArray_MultiIterNew (int, ...)
int PyArray_PyIntAsInt (object) except? -1
npy_intp PyArray_PyIntAsIntp (object)
int PyArray_Broadcast (broadcast) except -1
int PyArray_FillWithScalar (ndarray, object) except -1
npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *)
dtype PyArray_DescrNewByteorder (dtype, char)
object PyArray_IterAllButAxis (object, int *)
object PyArray_FromInterface (object)
object PyArray_FromStructInterface (object)
int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND)
npy_bool PyArray_CanCastScalar (type, type)
int PyArray_RemoveSmallest (broadcast) except -1
int PyArray_ElementStrides (object)
void PyArray_Item_INCREF (char *, dtype) except *
void PyArray_Item_XDECREF (char *, dtype) except *
object PyArray_Transpose (ndarray, PyArray_Dims *)
object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE)
object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE)
object PyArray_PutMask (ndarray, object, object)
object PyArray_Repeat (ndarray, object, int)
object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE)
int PyArray_Sort (ndarray, int, NPY_SORTKIND) except -1
object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER)
object PyArray_Squeeze (ndarray)
object PyArray_SwapAxes (ndarray, int, int)
object PyArray_Max (ndarray, int, ndarray)
object PyArray_Min (ndarray, int, ndarray)
object PyArray_Ptp (ndarray, int, ndarray)
object PyArray_Mean (ndarray, int, int, ndarray)
object PyArray_Trace (ndarray, int, int, int, int, ndarray)
object PyArray_Diagonal (ndarray, int, int, int)
object PyArray_Clip (ndarray, object, object, ndarray)
object PyArray_Nonzero (ndarray)
object PyArray_Std (ndarray, int, int, ndarray, int)
object PyArray_Sum (ndarray, int, int, ndarray)
object PyArray_CumSum (ndarray, int, int, ndarray)
object PyArray_Prod (ndarray, int, int, ndarray)
object PyArray_CumProd (ndarray, int, int, ndarray)
object PyArray_All (ndarray, int, ndarray)
object PyArray_Any (ndarray, int, ndarray)
object PyArray_Compress (ndarray, object, int, ndarray)
object PyArray_Flatten (ndarray, NPY_ORDER)
object PyArray_Ravel (ndarray, NPY_ORDER)
npy_intp PyArray_MultiplyList (npy_intp *, int)
int PyArray_MultiplyIntList (int *, int)
void * PyArray_GetPtr (ndarray, npy_intp*)
int PyArray_CompareLists (npy_intp *, npy_intp *, int)
int PyArray_IntpFromSequence (object, npy_intp *, int) except -1
object PyArray_Concatenate (object, int)
object PyArray_InnerProduct (object, object)
object PyArray_MatrixProduct (object, object)
object PyArray_Correlate (object, object, int)
unsigned char PyArray_EquivTypes (dtype, dtype)
object PyArray_Where (object, object, object)
object PyArray_Arange (double, double, double, int)
int PyArray_SortkindConverter (object, NPY_SORTKIND *) except 0
object PyArray_Round (ndarray, int, ndarray)
unsigned char PyArray_EquivTypenums (int, int)
int PyArray_RegisterDataType (dtype) except -1
int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *) except -1
int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND) except -1
void PyArray_InitArrFuncs (PyArray_ArrFuncs *)
object PyArray_IntTupleFromIntp (int, npy_intp *)
int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *) except 0
int PyArray_OutputConverter (object, ndarray*) except 0
object PyArray_BroadcastToShape (object, npy_intp *, int)
int PyArray_DescrAlignConverter (object, dtype*) except 0
int PyArray_DescrAlignConverter2 (object, dtype*) except 0
int PyArray_SearchsideConverter (object, void *) except 0
object PyArray_CheckAxis (ndarray, int *, int)
npy_intp PyArray_OverflowMultiplyList (npy_intp *, int)
int PyArray_SetBaseObject(ndarray, base) except -1
ctypedef npy_int8 int8_t
ctypedef npy_int16 int16_t
ctypedef npy_int32 int32_t
ctypedef npy_int64 int64_t
ctypedef npy_uint8 uint8_t
ctypedef npy_uint16 uint16_t
ctypedef npy_uint32 uint32_t
ctypedef npy_uint64 uint64_t
ctypedef npy_float32 float32_t
ctypedef npy_float64 float64_t
ctypedef float complex complex64_t
ctypedef double complex complex128_t
ctypedef npy_longlong longlong_t
ctypedef npy_ulonglong ulonglong_t
ctypedef npy_intp intp_t
ctypedef npy_uintp uintp_t
ctypedef npy_double float_t
ctypedef npy_double double_t
ctypedef npy_longdouble longdouble_t
ctypedef float complex cfloat_t
ctypedef double complex cdouble_t
ctypedef double complex complex_t
ctypedef long double complex clongdouble_t
cdef inline object PyArray_MultiIterNew1(a):
return PyArray_MultiIterNew(1, <void*>a)
cdef inline object PyArray_MultiIterNew2(a, b):
return PyArray_MultiIterNew(2, <void*>a, <void*>b)
cdef inline object PyArray_MultiIterNew3(a, b, c):
return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
cdef inline object PyArray_MultiIterNew4(a, b, c, d):
return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
cdef inline tuple PyDataType_SHAPE(dtype d):
if PyDataType_HASSUBARRAY(d):
return <tuple>d.subarray.shape
else:
return ()
cdef extern from "numpy/ndarrayobject.h":
PyTypeObject PyTimedeltaArrType_Type
PyTypeObject PyDatetimeArrType_Type
ctypedef int64_t npy_timedelta
ctypedef int64_t npy_datetime
cdef extern from "numpy/ndarraytypes.h":
ctypedef struct PyArray_DatetimeMetaData:
NPY_DATETIMEUNIT base
int64_t num
ctypedef struct npy_datetimestruct:
int64_t year
int32_t month, day, hour, min, sec, us, ps, as
cdef extern from "numpy/arrayscalars.h":
ctypedef class numpy.generic [object PyObject]:
pass
ctypedef class numpy.number [object PyObject]:
pass
ctypedef class numpy.integer [object PyObject]:
pass
ctypedef class numpy.signedinteger [object PyObject]:
pass
ctypedef class numpy.unsignedinteger [object PyObject]:
pass
ctypedef class numpy.inexact [object PyObject]:
pass
ctypedef class numpy.floating [object PyObject]:
pass
ctypedef class numpy.complexfloating [object PyObject]:
pass
ctypedef class numpy.flexible [object PyObject]:
pass
ctypedef class numpy.character [object PyObject]:
pass
ctypedef struct PyDatetimeScalarObject:
npy_datetime obval
PyArray_DatetimeMetaData obmeta
ctypedef struct PyTimedeltaScalarObject:
npy_timedelta obval
PyArray_DatetimeMetaData obmeta
ctypedef enum NPY_DATETIMEUNIT:
NPY_FR_Y
NPY_FR_M
NPY_FR_W
NPY_FR_D
NPY_FR_B
NPY_FR_h
NPY_FR_m
NPY_FR_s
NPY_FR_ms
NPY_FR_us
NPY_FR_ns
NPY_FR_ps
NPY_FR_fs
NPY_FR_as
NPY_FR_GENERIC
cdef extern from "numpy/arrayobject.h":
int get_datetime_iso_8601_strlen "NpyDatetime_GetDatetimeISO8601StrLen" (
int local, NPY_DATETIMEUNIT base)
int make_iso_8601_datetime "NpyDatetime_MakeISO8601Datetime" (
npy_datetimestruct *dts, char *outstr, npy_intp outlen,
int local, int utc, NPY_DATETIMEUNIT base, int tzoffset,
NPY_CASTING casting) except -1
int convert_pydatetime_to_datetimestruct "NpyDatetime_ConvertPyDateTimeToDatetimeStruct" (
PyObject *obj, npy_datetimestruct *out,
NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo) except -1
int convert_datetime64_to_datetimestruct "NpyDatetime_ConvertDatetime64ToDatetimeStruct" (
PyArray_DatetimeMetaData *meta, npy_datetime dt,
npy_datetimestruct *out) except -1
int convert_datetimestruct_to_datetime64 "NpyDatetime_ConvertDatetimeStructToDatetime64"(
PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts,
npy_datetime *out) except -1
cdef extern from "numpy/ufuncobject.h":
ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *)
ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]:
cdef:
int nin, nout, nargs
int identity
PyUFuncGenericFunction *functions
void **data
int ntypes
int check_return
char *name
char *types
char *doc
void *ptr
PyObject *obj
PyObject *userloops
cdef enum:
PyUFunc_Zero
PyUFunc_One
PyUFunc_None
UFUNC_FPE_DIVIDEBYZERO
UFUNC_FPE_OVERFLOW
UFUNC_FPE_UNDERFLOW
UFUNC_FPE_INVALID
object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *,
void **, char *, int, int, int, int, char *, char *, int)
int PyUFunc_RegisterLoopForType(ufunc, int,
PyUFuncGenericFunction, int *, void *) except -1
void PyUFunc_f_f_As_d_d \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_d_d \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_f_f \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_g_g \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_F_F_As_D_D \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_F_F \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_D_D \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_G_G \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_O_O \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_ff_f_As_dd_d \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_ff_f \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_dd_d \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_gg_g \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_FF_F_As_DD_D \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_DD_D \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_FF_F \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_GG_G \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_OO_O \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_O_O_method \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_OO_O_method \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_On_Om \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_clearfperr()
int PyUFunc_getfperr()
int PyUFunc_ReplaceLoopBySignature \
(ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *)
object PyUFunc_FromFuncAndDataAndSignature \
(PyUFuncGenericFunction *, void **, char *, int, int, int,
int, char *, char *, int, char *)
int _import_umath() except -1
cdef inline void set_array_base(ndarray arr, object base) except *:
Py_INCREF(base)
cdef inline object get_array_base(ndarray arr):
base = PyArray_BASE(arr)
if base is NULL:
return None
return <object>base
cdef inline int import_array() except -1:
try:
__pyx_import_array()
except Exception:
raise ImportError("numpy._core.multiarray failed to import")
cdef inline int import_umath() except -1:
try:
_import_umath()
except Exception:
raise ImportError("numpy._core.umath failed to import")
cdef inline int import_ufunc() except -1:
try:
_import_umath()
except Exception:
raise ImportError("numpy._core.umath failed to import")
cdef inline bint is_timedelta64_object(object obj) noexcept:
"""
Cython equivalent of `isinstance(obj, np.timedelta64)`
Parameters
----------
obj : object
Returns
-------
bool
"""
return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type)
cdef inline bint is_datetime64_object(object obj) noexcept:
"""
Cython equivalent of `isinstance(obj, np.datetime64)`
Parameters
----------
obj : object
Returns
-------
bool
"""
return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type)
cdef inline npy_datetime get_datetime64_value(object obj) noexcept nogil:
"""
returns the int64 value underlying scalar numpy datetime64 object
Note that to interpret this as a datetime, the corresponding unit is
also needed. That can be found using `get_datetime64_unit`.
"""
return (<PyDatetimeScalarObject*>obj).obval
cdef inline npy_timedelta get_timedelta64_value(object obj) noexcept nogil:
"""
returns the int64 value underlying scalar numpy timedelta64 object
"""
return (<PyTimedeltaScalarObject*>obj).obval
cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) noexcept nogil:
"""
returns the unit part of the dtype for a numpy datetime64 object.
"""
return <NPY_DATETIMEUNIT>(<PyDatetimeScalarObject*>obj).obmeta.base
ctypedef int (*NpyIter_IterNextFunc)(NpyIter* it) noexcept nogil
ctypedef void (*NpyIter_GetMultiIndexFunc)(NpyIter* it, npy_intp* outcoords) noexcept nogil
cdef extern from "numpy/arrayobject.h":
ctypedef struct NpyIter:
pass
cdef enum:
NPY_FAIL
NPY_SUCCEED
cdef enum:
NPY_ITER_C_INDEX
NPY_ITER_F_INDEX
NPY_ITER_MULTI_INDEX
NPY_ITER_EXTERNAL_LOOP
NPY_ITER_COMMON_DTYPE
NPY_ITER_REFS_OK
NPY_ITER_ZEROSIZE_OK
NPY_ITER_REDUCE_OK
NPY_ITER_RANGED
NPY_ITER_BUFFERED
NPY_ITER_GROWINNER
NPY_ITER_DELAY_BUFALLOC
NPY_ITER_DONT_NEGATE_STRIDES
NPY_ITER_COPY_IF_OVERLAP
NPY_ITER_READWRITE
NPY_ITER_READONLY
NPY_ITER_WRITEONLY
NPY_ITER_NBO
NPY_ITER_ALIGNED
NPY_ITER_CONTIG
NPY_ITER_COPY
NPY_ITER_UPDATEIFCOPY
NPY_ITER_ALLOCATE
NPY_ITER_NO_SUBTYPE
NPY_ITER_VIRTUAL
NPY_ITER_NO_BROADCAST
NPY_ITER_WRITEMASKED
NPY_ITER_ARRAYMASK
NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE
NpyIter* NpyIter_New(ndarray arr, npy_uint32 flags, NPY_ORDER order,
NPY_CASTING casting, dtype datatype) except NULL
NpyIter* NpyIter_MultiNew(npy_intp nop, PyArrayObject** op, npy_uint32 flags,
NPY_ORDER order, NPY_CASTING casting, npy_uint32*
op_flags, PyArray_Descr** op_dtypes) except NULL
// 创建一个新的 NpyIter 对象,并返回其指针
NpyIter* NpyIter_AdvancedNew(npy_intp nop, PyArrayObject** op,
npy_uint32 flags, NPY_ORDER order,
NPY_CASTING casting, npy_uint32* op_flags,
PyArray_Descr** op_dtypes, int oa_ndim,
int** op_axes, const npy_intp* itershape,
npy_intp buffersize) except NULL
// 复制给定的 NpyIter 对象,并返回其副本的指针
NpyIter* NpyIter_Copy(NpyIter* it) except NULL
// 从 NpyIter 对象中移除指定的轴
int NpyIter_RemoveAxis(NpyIter* it, int axis) except NPY_FAIL
// 从 NpyIter 对象中移除多重索引
int NpyIter_RemoveMultiIndex(NpyIter* it) except NPY_FAIL
// 启用 NpyIter 对象的外部循环模式
int NpyIter_EnableExternalLoop(NpyIter* it) except NPY_FAIL
// 释放 NpyIter 对象的内存资源
int NpyIter_Deallocate(NpyIter* it) except NPY_FAIL
// 重置 NpyIter 对象的迭代状态
int NpyIter_Reset(NpyIter* it, char** errmsg) except NPY_FAIL
// 重置 NpyIter 对象的迭代状态,限定于指定的迭代索引范围
int NpyIter_ResetToIterIndexRange(NpyIter* it, npy_intp istart,
npy_intp iend, char** errmsg) except NPY_FAIL
// 设置 NpyIter 对象的基础指针,用于重置迭代状态
int NpyIter_ResetBasePointers(NpyIter* it, char** baseptrs, char** errmsg) except NPY_FAIL
// 将 NpyIter 对象的迭代位置移动到指定的多重索引位置
int NpyIter_GotoMultiIndex(NpyIter* it, const npy_intp* multi_index) except NPY_FAIL
// 将 NpyIter 对象的迭代位置移动到指定的索引位置
int NpyIter_GotoIndex(NpyIter* it, npy_intp index) except NPY_FAIL
// 返回 NpyIter 对象的迭代尺寸
npy_intp NpyIter_GetIterSize(NpyIter* it) nogil
// 返回 NpyIter 对象的当前迭代索引
npy_intp NpyIter_GetIterIndex(NpyIter* it) nogil
// 返回 NpyIter 对象的迭代索引范围
void NpyIter_GetIterIndexRange(NpyIter* it, npy_intp* istart,
npy_intp* iend) nogil
// 将 NpyIter 对象的迭代位置移动到指定的迭代索引
int NpyIter_GotoIterIndex(NpyIter* it, npy_intp iterindex) except NPY_FAIL
// 检查 NpyIter 对象是否有延迟缓冲区分配
npy_bool NpyIter_HasDelayedBufAlloc(NpyIter* it) nogil
// 检查 NpyIter 对象是否使用外部循环模式
npy_bool NpyIter_HasExternalLoop(NpyIter* it) nogil
// 检查 NpyIter 对象是否有多重索引
npy_bool NpyIter_HasMultiIndex(NpyIter* it) nogil
// 检查 NpyIter 对象是否有索引
npy_bool NpyIter_HasIndex(NpyIter* it) nogil
// 检查 NpyIter 对象是否需要缓冲区
npy_bool NpyIter_RequiresBuffering(NpyIter* it) nogil
// 检查 NpyIter 对象是否已经缓冲
npy_bool NpyIter_IsBuffered(NpyIter* it) nogil
// 检查 NpyIter 对象是否在增长内部
npy_bool NpyIter_IsGrowInner(NpyIter* it) nogil
// 返回 NpyIter 对象的缓冲区大小
npy_intp NpyIter_GetBufferSize(NpyIter* it) nogil
// 返回 NpyIter 对象的维度数
int NpyIter_GetNDim(NpyIter* it) nogil
// 返回 NpyIter 对象的操作数数量
int NpyIter_GetNOp(NpyIter* it) nogil
// 返回 NpyIter 对象指定轴的步长数组
npy_intp* NpyIter_GetAxisStrideArray(NpyIter* it, int axis) except NULL
// 返回 NpyIter 对象的形状数组
int NpyIter_GetShape(NpyIter* it, npy_intp* outshape) nogil
// 返回 NpyIter 对象的数据类型数组
PyArray_Descr** NpyIter_GetDescrArray(NpyIter* it)
// 返回 NpyIter 对象的操作数数组
PyArrayObject** NpyIter_GetOperandArray(NpyIter* it)
// 返回 NpyIter 对象指定索引的迭代视图
ndarray NpyIter_GetIterView(NpyIter* it, npy_intp i)
// 将 NpyIter 对象的读取标志复制到输出数组
void NpyIter_GetReadFlags(NpyIter* it, char* outreadflags)
// 将 NpyIter 对象的写入标志复制到输出数组
void NpyIter_GetWriteFlags(NpyIter* it, char* outwriteflags)
// 创建与 NpyIter 对象兼容的步长数组
int NpyIter_CreateCompatibleStrides(NpyIter* it, npy_intp itemsize,
npy_intp* outstrides) except NPY_FAIL
// 检查指定操作数是否首次访问
npy_bool NpyIter_IsFirstVisit(NpyIter* it, int iop) nogil
// 返回用于迭代 NpyIter 对象的下一个函数指针
NpyIter_IterNextFunc* NpyIter_GetIterNext(NpyIter* it, char** errmsg) except NULL
// 返回用于获取 NpyIter 对象的多重索引的函数指针
NpyIter_GetMultiIndexFunc* NpyIter_GetGetMultiIndex(NpyIter* it,
char** errmsg) except NULL
char** NpyIter_GetDataPtrArray(NpyIter* it) nogil
char** NpyIter_GetInitialDataPtrArray(NpyIter* it) nogil
npy_intp* NpyIter_GetIndexPtr(NpyIter* it)
npy_intp* NpyIter_GetInnerStrideArray(NpyIter* it) nogil
npy_intp* NpyIter_GetInnerLoopSizePtr(NpyIter* it) nogil
void NpyIter_GetInnerFixedStrideArray(NpyIter* it, npy_intp* outstrides) nogil
npy_bool NpyIter_IterationNeedsAPI(NpyIter* it) nogil
void NpyIter_DebugPrint(NpyIter* it)
.\numpy\numpy\__init__.pxd
DEF _buffer_format_string_len = 255
cimport cpython.buffer as pybuf
from cpython.ref cimport Py_INCREF
from cpython.mem cimport PyObject_Malloc, PyObject_Free
from cpython.object cimport PyObject, PyTypeObject
from cpython.buffer cimport PyObject_GetBuffer
from cpython.type cimport type
cimport libc.stdio as stdio
cdef extern from *:
"""
/* Using NumPy API declarations from "numpy/__init__.pxd" */
"""
cdef extern from "Python.h":
ctypedef int Py_intptr_t
bint PyObject_TypeCheck(object obj, PyTypeObject* type)
cdef extern from "numpy/arrayobject.h":
ctypedef signed long npy_intp
ctypedef unsigned long npy_uintp
ctypedef unsigned char npy_bool
ctypedef signed char npy_byte
ctypedef signed short npy_short
ctypedef signed int npy_int
ctypedef signed long npy_long
ctypedef signed long long npy_longlong
ctypedef unsigned char npy_ubyte
ctypedef unsigned short npy_ushort
ctypedef unsigned int npy_uint
ctypedef unsigned long npy_ulong
ctypedef unsigned long long npy_ulonglong
ctypedef float npy_float
ctypedef double npy_double
ctypedef long double npy_longdouble
ctypedef signed char npy_int8
ctypedef signed short npy_int16
ctypedef signed int npy_int32
ctypedef signed long long npy_int64
ctypedef signed long long npy_int96
ctypedef signed long long npy_int128
ctypedef unsigned char npy_uint8
ctypedef unsigned short npy_uint16
ctypedef unsigned int npy_uint32
ctypedef unsigned long long npy_uint64
ctypedef unsigned long long npy_uint96
ctypedef unsigned long long npy_uint128
ctypedef float npy_float32
ctypedef double npy_float64
ctypedef long double npy_float80
ctypedef long double npy_float96
ctypedef long double npy_float128
ctypedef struct npy_cfloat:
pass
ctypedef struct npy_cdouble:
pass
ctypedef struct npy_clongdouble:
pass
ctypedef struct npy_complex64:
pass
ctypedef struct npy_complex128:
pass
ctypedef struct npy_complex160:
pass
ctypedef struct npy_complex192:
pass
ctypedef struct npy_complex256:
pass
ctypedef struct PyArray_Dims:
npy_intp *ptr
int len
cdef enum NPY_TYPES:
NPY_BOOL
NPY_BYTE
NPY_UBYTE
NPY_SHORT
NPY_USHORT
NPY_INT
NPY_UINT
NPY_LONG
NPY_ULONG
NPY_LONGLONG
NPY_ULONGLONG
NPY_FLOAT
NPY_DOUBLE
NPY_LONGDOUBLE
NPY_CFLOAT
NPY_CDOUBLE
NPY_CLONGDOUBLE
NPY_OBJECT
NPY_STRING
NPY_UNICODE
NPY_VOID
NPY_DATETIME
NPY_TIMEDELTA
NPY_NTYPES_LEGACY
NPY_NOTYPE
NPY_INT8
NPY_INT16
NPY_INT32
NPY_INT64
NPY_INT128
NPY_INT256
NPY_UINT8
NPY_UINT16
NPY_UINT32
NPY_UINT64
NPY_UINT128
NPY_UINT256
NPY_FLOAT16
NPY_FLOAT32
NPY_FLOAT64
NPY_FLOAT80
NPY_FLOAT96
NPY_FLOAT128
NPY_FLOAT256
NPY_COMPLEX32
NPY_COMPLEX64
NPY_COMPLEX128
NPY_COMPLEX160
NPY_COMPLEX192
NPY_COMPLEX256
NPY_COMPLEX512
NPY_INTP
NPY_DEFAULT_INT
ctypedef enum NPY_ORDER:
NPY_ANYORDER
NPY_CORDER
NPY_FORTRANORDER
NPY_KEEPORDER
ctypedef enum NPY_CASTING:
NPY_NO_CASTING
NPY_EQUIV_CASTING
NPY_SAFE_CASTING
NPY_SAME_KIND_CASTING
NPY_UNSAFE_CASTING
ctypedef enum NPY_CLIPMODE:
NPY_CLIP
NPY_WRAP
NPY_RAISE
ctypedef enum NPY_SCALARKIND:
NPY_NOSCALAR
NPY_BOOL_SCALAR
NPY_INTPOS_SCALAR
NPY_INTNEG_SCALAR
NPY_FLOAT_SCALAR
NPY_COMPLEX_SCALAR
NPY_OBJECT_SCALAR
ctypedef enum NPY_SORTKIND:
NPY_QUICKSORT
NPY_HEAPSORT
NPY_MERGESORT
ctypedef enum NPY_SEARCHSIDE:
NPY_SEARCHLEFT
NPY_SEARCHRIGHT
enum:
NPY_C_CONTIGUOUS
NPY_F_CONTIGUOUS
NPY_CONTIGUOUS
NPY_FORTRAN
NPY_OWNDATA
NPY_FORCECAST
NPY_ENSURECOPY
NPY_ENSUREARRAY
NPY_ELEMENTSTRIDES
NPY_ALIGNED
NPY_NOTSWAPPED
NPY_WRITEABLE
NPY_ARR_HAS_DESCR
NPY_BEHAVED
NPY_BEHAVED_NS
NPY_CARRAY
NPY_CARRAY_RO
NPY_FARRAY
NPY_FARRAY_RO
NPY_DEFAULT
NPY_IN_ARRAY
NPY_OUT_ARRAY
NPY_INOUT_ARRAY
NPY_IN_FARRAY
NPY_OUT_FARRAY
NPY_INOUT_FARRAY
NPY_UPDATE_ALL
enum:
NPY_ARRAY_C_CONTIGUOUS
NPY_ARRAY_F_CONTIGUOUS
NPY_ARRAY_OWNDATA
NPY_ARRAY_FORCECAST
NPY_ARRAY_ENSURECOPY
NPY_ARRAY_ENSUREARRAY
NPY_ARRAY_ELEMENTSTRIDES
NPY_ARRAY_ALIGNED
NPY_ARRAY_NOTSWAPPED
NPY_ARRAY_WRITEABLE
NPY_ARRAY_WRITEBACKIFCOPY
NPY_ARRAY_BEHAVED
NPY_ARRAY_BEHAVED_NS
NPY_ARRAY_CARRAY
NPY_ARRAY_CARRAY_RO
NPY_ARRAY_FARRAY
NPY_ARRAY_FARRAY_RO
NPY_ARRAY_DEFAULT
NPY_ARRAY_IN_ARRAY
NPY_ARRAY_OUT_ARRAY
NPY_ARRAY_INOUT_ARRAY
NPY_ARRAY_IN_FARRAY
NPY_ARRAY_OUT_FARRAY
NPY_ARRAY_INOUT_FARRAY
NPY_ARRAY_UPDATE_ALL
cdef enum:
NPY_MAXDIMS
NPY_RAVEL_AXIS
ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *)
ctypedef struct PyArray_ArrayDescr:
PyObject* shape
ctypedef struct PyArray_Descr:
pass
ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]:
cdef PyTypeObject* typeobj
cdef char kind
cdef char type
cdef char byteorder
cdef int type_num
ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]:
ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]:
cdef int numiter
cdef npy_intp size, index
cdef int nd
cdef npy_intp *dimensions
cdef void **iters
ctypedef struct PyArrayObject:
pass
ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]:
cdef __cythonbufferdefaults__ = {"mode": "strided"}
cdef:
char *data
int ndim "nd"
npy_intp *shape "dimensions"
npy_intp *strides
dtype descr
PyObject* base
int _import_array() except -1
int __pyx_import_array "_import_array"() except -1
bint PyArray_CHKFLAGS(ndarray m, int flags) nogil
bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil
bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil
bint PyArray_ISCONTIGUOUS(ndarray m) nogil
bint PyArray_ISWRITEABLE(ndarray m) nogil
bint PyArray_ISALIGNED(ndarray m) nogil
int PyArray_NDIM(ndarray) nogil
bint PyArray_ISONESEGMENT(ndarray) nogil
bint PyArray_ISFORTRAN(ndarray) nogil
int PyArray_FORTRANIF(ndarray) nogil
void* PyArray_DATA(ndarray) nogil
char* PyArray_BYTES(ndarray) nogil
npy_intp* PyArray_DIMS(ndarray) nogil
npy_intp* PyArray_STRIDES(ndarray) nogil
npy_intp PyArray_DIM(ndarray, size_t) nogil
npy_intp PyArray_STRIDE(ndarray, size_t) nogil
PyObject *PyArray_BASE(ndarray) nogil
PyArray_Descr *PyArray_DESCR(ndarray) nogil
PyArray_Descr *PyArray_DTYPE(ndarray) nogil
int PyArray_FLAGS(ndarray) nogil
void PyArray_CLEARFLAGS(ndarray, int flags) nogil
void PyArray_ENABLEFLAGS(ndarray, int flags) nogil
npy_intp PyArray_ITEMSIZE(ndarray) nogil
int PyArray_TYPE(ndarray arr) nogil
object PyArray_GETITEM(ndarray arr, void *itemptr)
int PyArray_SETITEM(ndarray arr, void *itemptr, object obj) except -1
bint PyTypeNum_ISBOOL(int) nogil
bint PyTypeNum_ISUNSIGNED(int) nogil
bint PyTypeNum_ISSIGNED(int) nogil
bint PyTypeNum_ISINTEGER(int) nogil
bint PyTypeNum_ISFLOAT(int) nogil
bint PyTypeNum_ISNUMBER(int) nogil
bint PyTypeNum_ISSTRING(int) nogil
bint PyTypeNum_ISCOMPLEX(int) nogil
bint PyTypeNum_ISFLEXIBLE(int) nogil
bint PyTypeNum_ISUSERDEF(int) nogil
bint PyTypeNum_ISEXTENDED(int) nogil
bint PyTypeNum_ISOBJECT(int) nogil
npy_intp PyDataType_ELSIZE(dtype) nogil
npy_intp PyDataType_ALIGNMENT(dtype) nogil
PyObject* PyDataType_METADATA(dtype) nogil
PyArray_ArrayDescr* PyDataType_SUBARRAY(dtype) nogil
PyObject* PyDataType_NAMES(dtype) nogil
PyObject* PyDataType_FIELDS(dtype) nogil
bint PyDataType_ISBOOL(dtype) nogil
bint PyDataType_ISUNSIGNED(dtype) nogil
bint PyDataType_ISSIGNED(dtype) nogil
bint PyDataType_ISINTEGER(dtype) nogil
bint PyDataType_ISFLOAT(dtype) nogil
bint PyDataType_ISNUMBER(dtype) nogil
bint PyDataType_ISSTRING(dtype) nogil
bint PyDataType_ISCOMPLEX(dtype) nogil
bint PyDataType_ISFLEXIBLE(dtype) nogil
bint PyDataType_ISUSERDEF(dtype) nogil
bint PyDataType_ISEXTENDED(dtype) nogil
bint PyDataType_ISOBJECT(dtype) nogil
bint PyDataType_HASFIELDS(dtype) nogil
bint PyDataType_HASSUBARRAY(dtype) nogil
npy_uint64 PyDataType_FLAGS(dtype) nogil
bint PyArray_ISBOOL(ndarray) nogil
bint PyArray_ISUNSIGNED(ndarray) nogil
bint PyArray_ISSIGNED(ndarray) nogil
bint PyArray_ISINTEGER(ndarray) nogil
bint PyArray_ISFLOAT(ndarray) nogil
bint PyArray_ISNUMBER(ndarray) nogil
bint PyArray_ISSTRING(ndarray) nogil
bint PyArray_ISCOMPLEX(ndarray) nogil
bint PyArray_ISFLEXIBLE(ndarray) nogil
bint PyArray_ISUSERDEF(ndarray) nogil
bint PyArray_ISEXTENDED(ndarray) nogil
bint PyArray_ISOBJECT(ndarray) nogil
bint PyArray_HASFIELDS(ndarray) nogil
bint PyArray_ISVARIABLE(ndarray) nogil
bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil
bint PyArray_ISNBO(char) nogil
bint PyArray_IsNativeByteOrder(char) nogil
bint PyArray_ISNOTSWAPPED(ndarray) nogil
bint PyArray_ISBYTESWAPPED(ndarray) nogil
bint PyArray_FLAGSWAP(ndarray, int) nogil
bint PyArray_ISCARRAY(ndarray) nogil
bint PyArray_ISCARRAY_RO(ndarray) nogil
bint PyArray_ISFARRAY(ndarray) nogil
bint PyArray_ISFARRAY_RO(ndarray) nogil
bint PyArray_ISBEHAVED(ndarray) nogil
bint PyArray_ISBEHAVED_RO(ndarray) nogil
bint PyDataType_ISNOTSWAPPED(dtype) nogil
bint PyDataType_ISBYTESWAPPED(dtype) nogil
bint PyArray_DescrCheck(object)
bint PyArray_Check(object)
bint PyArray_CheckExact(object)
bint PyArray_IsZeroDim(object)
bint PyArray_CheckScalar(object)
bint PyArray_IsPythonNumber(object)
bint PyArray_IsPythonScalar(object)
bint PyArray_IsAnyScalar(object)
bint PyArray_CheckAnyScalar(object)
ndarray PyArray_GETCONTIGUOUS(ndarray)
bint PyArray_SAMESHAPE(ndarray, ndarray) nogil
npy_intp PyArray_SIZE(ndarray) nogil
npy_intp PyArray_NBYTES(ndarray) nogil
object PyArray_FROM_O(object)
object PyArray_FROM_OF(object m, int flags)
object PyArray_FROM_OT(object m, int type)
object PyArray_FROM_OTF(object m, int type, int flags)
object PyArray_FROMANY(object m, int type, int min, int max, int flags)
object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran)
object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran)
void PyArray_FILLWBYTE(ndarray, int val)
object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth)
unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2)
bint PyArray_EquivByteorders(int b1, int b2) nogil
object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum)
object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data)
object PyArray_ToScalar(void* data, ndarray arr)
void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil
void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil
void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil
void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil
object PyArray_Copy(ndarray)
object PyArray_FromObject(object op, int type, int min_depth, int max_depth)
object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth)
object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth)
object PyArray_Cast(ndarray mp, int type_num)
object PyArray_Take(ndarray ap, object items, int axis)
object PyArray_Put(ndarray ap, object items, object values)
void PyArray_ITER_RESET(flatiter it) nogil
void PyArray_ITER_NEXT(flatiter it) nogil
void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil
void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil
void* PyArray_ITER_DATA(flatiter it) nogil
bint PyArray_ITER_NOTDONE(flatiter it) nogil
void PyArray_MultiIter_RESET(broadcast multi) nogil
void PyArray_MultiIter_NEXT(broadcast multi) nogil
void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil
void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil
void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil
void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil
bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil
npy_intp PyArray_MultiIter_SIZE(broadcast multi) nogil
int PyArray_MultiIter_NDIM(broadcast multi) nogil
npy_intp PyArray_MultiIter_INDEX(broadcast multi) nogil
npy_intp* PyArray_MultiIter_DIMS(broadcast multi) nogil
void** PyArray_MultiIter_ITERS(broadcast multi) nogil
int PyArray_INCREF(ndarray) except *
int PyArray_XDECREF(ndarray) except *
dtype PyArray_DescrFromType(int)
object PyArray_TypeObjectFromType(int)
char * PyArray_Zero(ndarray)
char * PyArray_One(ndarray)
int PyArray_CanCastSafely(int, int)
npy_bool PyArray_CanCastTo(dtype, dtype)
int PyArray_ObjectType(object, int) except 0
dtype PyArray_DescrFromObject(object, dtype)
dtype PyArray_DescrFromScalar(object)
dtype PyArray_DescrFromTypeObject(object)
npy_intp PyArray_Size(object)
void PyArray_ScalarAsCtype(object, void *)
double PyArray_GetPriority(object, double)
object PyArray_IterNew(object)
object PyArray_MultiIterNew(int, ...)
int PyArray_PyIntAsInt(object) except? -1
npy_intp PyArray_PyIntAsIntp(object)
int PyArray_Broadcast(broadcast) except -1
int PyArray_FillWithScalar(ndarray, object) except -1
npy_bool PyArray_CheckStrides(int, int, npy_intp, npy_intp, npy_intp *, npy_intp *)
dtype PyArray_DescrNewByteorder (dtype, char)
object PyArray_IterAllButAxis (object, int *)
object PyArray_FromInterface (object)
object PyArray_FromStructInterface (object)
int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND)
npy_bool PyArray_CanCastScalar (type, type)
int PyArray_RemoveSmallest (broadcast) except -1
int PyArray_ElementStrides (object)
void PyArray_Item_INCREF (char *, dtype) except *
void PyArray_Item_XDECREF (char *, dtype) except *
object PyArray_Transpose (ndarray, PyArray_Dims *)
object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE)
object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE)
object PyArray_PutMask (ndarray, object, object)
object PyArray_Repeat (ndarray, object, int)
object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE)
int PyArray_Sort (ndarray, int, NPY_SORTKIND) except -1
object PyArray_ArgSort (ndarray, int, NPY_SORTKIND)
object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *)
object PyArray_ArgMax (ndarray, int, ndarray)
object PyArray_ArgMin (ndarray, int, ndarray)
object PyArray_Reshape (ndarray, object)
object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER)
object PyArray_Squeeze (ndarray)
object PyArray_SwapAxes (ndarray, int, int)
object PyArray_Max (ndarray, int, ndarray)
object PyArray_Min (ndarray, int, ndarray)
object PyArray_Ptp (ndarray, int, ndarray)
object PyArray_Mean (ndarray, int, int, ndarray)
object PyArray_Trace (ndarray, int, int, int, int, ndarray)
object PyArray_Diagonal (ndarray, int, int, int)
object PyArray_Clip (ndarray, object, object, ndarray)
object PyArray_Conjugate (ndarray, ndarray)
object PyArray_Nonzero (ndarray)
object PyArray_Std (ndarray, int, int, ndarray, int)
object PyArray_Sum (ndarray, int, int, ndarray)
object PyArray_CumSum (ndarray, int, int, ndarray)
object PyArray_Prod (ndarray, int, int, ndarray)
object PyArray_CumProd (ndarray, int, int, ndarray)
object PyArray_All (ndarray, int, ndarray)
object PyArray_Any (ndarray, int, ndarray)
object PyArray_Compress (ndarray, object, int, ndarray)
object PyArray_Flatten (ndarray, NPY_ORDER)
object PyArray_Ravel (ndarray, NPY_ORDER)
npy_intp PyArray_MultiplyList (npy_intp *, int)
int PyArray_MultiplyIntList (int *, int)
void * PyArray_GetPtr (ndarray, npy_intp*)
int PyArray_CompareLists (npy_intp *, npy_intp *, int)
int PyArray_Free (object, void *)
int PyArray_IntpFromSequence (object, npy_intp *, int) except -1
object PyArray_Concatenate (object, int)
object PyArray_InnerProduct (object, object)
object PyArray_MatrixProduct (object, object)
object PyArray_Correlate (object, object, int)
int PyArray_IntpConverter (object, PyArray_Dims *) except 0
int PyArray_AxisConverter (object, int *) except 0
int PyArray_BoolConverter (object, npy_bool *) except 0
int PyArray_ByteorderConverter (object, char *) except 0
int PyArray_OrderConverter (object, NPY_ORDER *) except 0
unsigned char PyArray_EquivTypes (dtype, dtype)
object PyArray_Where (object, object, object)
object PyArray_Arange (double, double, double, int)
int PyArray_SortkindConverter (object, NPY_SORTKIND *) except 0
object PyArray_LexSort (object, int)
object PyArray_Round (ndarray, int, ndarray)
unsigned char PyArray_EquivTypenums (int, int)
int PyArray_RegisterDataType (dtype) except -1
int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *) except -1
int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND) except -1
object PyArray_IntTupleFromIntp (int, npy_intp *)
ctypedef npy_int8 int8_t
ctypedef npy_int16 int16_t
ctypedef npy_int32 int32_t
ctypedef npy_int64 int64_t
ctypedef npy_uint8 uint8_t
ctypedef npy_uint16 uint16_t
ctypedef npy_uint32 uint32_t
ctypedef npy_uint64 uint64_t
ctypedef npy_float32 float32_t
ctypedef npy_float64 float64_t
ctypedef float complex complex64_t
ctypedef double complex complex128_t
ctypedef npy_longlong longlong_t
ctypedef npy_ulonglong ulonglong_t
ctypedef npy_intp intp_t
ctypedef npy_uintp uintp_t
ctypedef npy_double float_t
ctypedef npy_double double_t
ctypedef npy_longdouble longdouble_t
ctypedef float complex cfloat_t
ctypedef double complex cdouble_t
ctypedef double complex complex_t
ctypedef long double complex clongdouble_t
cdef inline object PyArray_MultiIterNew1(a):
return PyArray_MultiIterNew(1, <void*>a)
cdef inline object PyArray_MultiIterNew2(a, b):
return PyArray_MultiIterNew(2, <void*>a, <void*>b)
cdef inline object PyArray_MultiIterNew3(a, b, c):
return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
cdef inline object PyArray_MultiIterNew4(a, b, c, d):
return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
cdef inline tuple PyDataType_SHAPE(dtype d):
if PyDataType_HASSUBARRAY(d):
return <tuple>d.subarray.shape
else:
return ()
cdef extern from "numpy/ndarrayobject.h":
PyTypeObject PyTimedeltaArrType_Type
PyTypeObject PyDatetimeArrType_Type
ctypedef int64_t npy_timedelta
ctypedef int64_t npy_datetime
cdef extern from "numpy/ndarraytypes.h":
ctypedef struct PyArray_DatetimeMetaData:
NPY_DATETIMEUNIT base
int64_t num
ctypedef struct npy_datetimestruct:
int64_t year
int32_t month, day, hour, min, sec, us, ps, as
cdef extern from "numpy/arrayscalars.h":
ctypedef class numpy.generic [object PyObject]:
pass
ctypedef class numpy.number [object PyObject]:
pass
ctypedef class numpy.integer [object PyObject]:
pass
ctypedef class numpy.signedinteger [object PyObject]:
pass
ctypedef class numpy.unsignedinteger [object PyObject]:
pass
ctypedef class numpy.inexact [object PyObject]:
pass
ctypedef class numpy.floating [object PyObject]:
pass
ctypedef class numpy.complexfloating [object PyObject]:
pass
ctypedef class numpy.flexible [object PyObject]:
pass
ctypedef class numpy.character [object PyObject]:
pass
ctypedef struct PyDatetimeScalarObject:
npy_datetime obval
PyArray_DatetimeMetaData obmeta
ctypedef struct PyTimedeltaScalarObject:
npy_timedelta obval
PyArray_DatetimeMetaData obmeta
ctypedef enum NPY_DATETIMEUNIT:
NPY_FR_Y
NPY_FR_M
NPY_FR_W
NPY_FR_D
NPY_FR_B
NPY_FR_h
NPY_FR_m
NPY_FR_s
NPY_FR_ms
NPY_FR_us
NPY_FR_ns
NPY_FR_ps
NPY_FR_fs
NPY_FR_as
NPY_FR_GENERIC
cdef extern from "numpy/arrayobject.h":
int get_datetime_iso_8601_strlen "NpyDatetime_GetDatetimeISO8601StrLen" (
int local, NPY_DATETIMEUNIT base)
int make_iso_8601_datetime "NpyDatetime_MakeISO8601Datetime" (
npy_datetimestruct *dts, char *outstr, npy_intp outlen,
int local, int utc, NPY_DATETIMEUNIT base, int tzoffset,
NPY_CASTING casting) except -1
int convert_pydatetime_to_datetimestruct "NpyDatetime_ConvertPyDateTimeToDatetimeStruct" (
PyObject *obj, npy_datetimestruct *out,
NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo) except -1
int convert_datetime64_to_datetimestruct "NpyDatetime_ConvertDatetime64ToDatetimeStruct" (
PyArray_DatetimeMetaData *meta, npy_datetime dt,
npy_datetimestruct *out) except -1
int convert_datetimestruct_to_datetime64 "NpyDatetime_ConvertDatetimeStructToDatetime64"(
PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts,
npy_datetime *out) except -1
cdef extern from "numpy/ufuncobject.h":
ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *)
ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]:
cdef:
int nin, nout, nargs
int identity
PyUFuncGenericFunction *functions
void **data
int ntypes
int check_return
char *name
char *types
char *doc
void *ptr
PyObject *obj
PyObject *userloops
cdef enum:
PyUFunc_Zero
PyUFunc_One
PyUFunc_None
UFUNC_FPE_DIVIDEBYZERO
UFUNC_FPE_OVERFLOW
UFUNC_FPE_UNDERFLOW
UFUNC_FPE_INVALID
object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *,
void **, char *, int, int, int, int, char *, char *, int)
int PyUFunc_RegisterLoopForType(ufunc, int,
PyUFuncGenericFunction, int *, void *) except -1
void PyUFunc_f_f_As_d_d \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_d_d \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_f_f \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_g_g \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_F_F_As_D_D \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_F_F \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_D_D \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_G_G \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_O_O \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_ff_f_As_dd_d \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_ff_f \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_dd_d \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_gg_g \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_FF_F_As_DD_D \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_DD_D \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_FF_F \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_GG_G \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_OO_O \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_O_O_method \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_OO_O_method \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_On_Om \
(char **, npy_intp *, npy_intp *, void *)
void PyUFunc_clearfperr()
int PyUFunc_getfperr()
int PyUFunc_ReplaceLoopBySignature \
(ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *)
object PyUFunc_FromFuncAndDataAndSignature \
(PyUFuncGenericFunction *, void **, char *, int, int, int,
int, char *, char *, int, char *)
int _import_umath() except -1
cdef inline void set_array_base(ndarray arr, object base):
Py_INCREF(base)
PyArray_SetBaseObject(arr, base)
cdef inline object get_array_base(ndarray arr):
base = PyArray_BASE(arr)
if base is NULL:
return None
return <object>base
cdef inline int import_array() except -1:
try:
__pyx_import_array()
except Exception:
raise ImportError("numpy._core.multiarray failed to import")
cdef inline int import_umath() except -1:
try:
_import_umath()
except Exception:
raise ImportError("numpy._core.umath failed to import")
cdef inline int import_ufunc() except -1:
try:
_import_umath()
except Exception:
raise ImportError("numpy._core.umath failed to import")
cdef inline bint is_timedelta64_object(object obj):
"""
Cython 的等价函数,用于检查 obj 是否为 np.timedelta64 类型的实例
Parameters
----------
obj : object
Returns
-------
bool
"""
return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type)
cdef inline bint is_datetime64_object(object obj):
"""
Cython 的等价函数,用于检查 obj 是否为 np.datetime64 类型的实例
Parameters
----------
obj : object
Returns
-------
bool
"""
return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type)
cdef inline npy_datetime get_datetime64_value(object obj) nogil:
"""
返回标量 numpy datetime64 对象下层的 int64 值
注意,要解释为 datetime,还需要对应的单位,可以使用 get_datetime64_unit 获取单位信息。
"""
return (<PyDatetimeScalarObject*>obj).obval
cdef inline npy_timedelta get_timedelta64_value(object obj) nogil:
"""
返回标量 numpy timedelta64 对象下层的 int64 值
"""
return (<PyTimedeltaScalarObject*>obj).obval
cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil:
"""
返回 numpy datetime64 对象的 dtype 中的单位部分信息
"""
return <NPY_DATETIMEUNIT>(<PyDatetimeScalarObject*>obj).obmeta.base
ctypedef int (*NpyIter_IterNextFunc)(NpyIter* it) noexcept nogil
ctypedef void (*NpyIter_GetMultiIndexFunc)(NpyIter* it, npy_intp* outcoords) noexcept nogil
cdef extern from "numpy/arrayobject.h":
ctypedef struct NpyIter:
pass
cdef enum:
NPY_FAIL
NPY_SUCCEED
NPY_ITER_C_INDEX
NPY_ITER_F_INDEX
NPY_ITER_MULTI_INDEX
NPY_ITER_EXTERNAL_LOOP
NPY_ITER_COMMON_DTYPE
NPY_ITER_REFS_OK
NPY_ITER_ZEROSIZE_OK
NPY_ITER_REDUCE_OK
NPY_ITER_RANGED
NPY_ITER_BUFFERED
NPY_ITER_GROWINNER
NPY_ITER_DELAY_BUFALLOC
NPY_ITER_DONT_NEGATE_STRIDES
NPY_ITER_COPY_IF_OVERLAP
NPY_ITER_READWRITE
NPY_ITER_READONLY
NPY_ITER_WRITEONLY
NPY_ITER_NBO
NPY_ITER_ALIGNED
NPY_ITER_CONTIG
NPY_ITER_COPY
NPY_ITER_UPDATEIFCOPY
NPY_ITER_ALLOCATE
NPY_ITER_NO_SUBTYPE
NPY_ITER_VIRTUAL
NPY_ITER_NO_BROADCAST
NPY_ITER_WRITEMASKED
NPY_ITER_ARRAYMASK
NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE
NpyIter* NpyIter_New(ndarray arr, npy_uint32 flags, NPY_ORDER order,
NPY_CASTING casting, dtype datatype) except NULL
NpyIter* NpyIter_MultiNew(npy_intp nop, PyArrayObject** op, npy_uint32 flags,
NPY_ORDER order, NPY_CASTING casting, npy_uint32*
op_flags, PyArray_Descr** op_dtypes) except NULL
// 创建一个新的 NpyIter 对象,具有高级配置选项
NpyIter* NpyIter_AdvancedNew(npy_intp nop, // 操作数的数量
PyArrayObject** op, // 操作数对象的指针数组
npy_uint32 flags, // 迭代器的标志
NPY_ORDER order, // 迭代的顺序
NPY_CASTING casting, // 类型转换方式
npy_uint32* op_flags, // 操作数的标志数组
PyArray_Descr** op_dtypes, // 操作数的数据类型数组
int oa_ndim, // 操作数轴的数量
int** op_axes, // 操作数轴的数组的指针
const npy_intp* itershape, // 迭代器的形状
npy_intp buffersize) // 缓冲区的大小
except NULL
// 复制一个现有的 NpyIter 对象,返回新的对象
NpyIter* NpyIter_Copy(NpyIter* it) except NULL
// 移除指定轴上的迭代
int NpyIter_RemoveAxis(NpyIter* it, int axis) except NPY_FAIL
// 移除多索引迭代
int NpyIter_RemoveMultiIndex(NpyIter* it) except NPY_FAIL
// 启用外部循环模式
int NpyIter_EnableExternalLoop(NpyIter* it) except NPY_FAIL
// 释放 NpyIter 对象的内存
int NpyIter_Deallocate(NpyIter* it) except NPY_FAIL
// 重置迭代器状态
int NpyIter_Reset(NpyIter* it, char** errmsg) except NPY_FAIL
// 重置到指定迭代索引范围
int NpyIter_ResetToIterIndexRange(NpyIter* it, npy_intp istart, npy_intp iend, char** errmsg) except NPY_FAIL
// 重置基础指针数组
int NpyIter_ResetBasePointers(NpyIter* it, char** baseptrs, char** errmsg) except NPY_FAIL
// 跳转到指定多索引位置
int NpyIter_GotoMultiIndex(NpyIter* it, const npy_intp* multi_index) except NPY_FAIL
// 跳转到指定索引位置
int NpyIter_GotoIndex(NpyIter* it, npy_intp index) except NPY_FAIL
// 获取迭代器的总大小
npy_intp NpyIter_GetIterSize(NpyIter* it) nogil
// 获取当前迭代的索引
npy_intp NpyIter_GetIterIndex(NpyIter* it) nogil
// 获取迭代索引范围
void NpyIter_GetIterIndexRange(NpyIter* it, npy_intp* istart, npy_intp* iend) nogil
// 跳转到指定迭代索引
int NpyIter_GotoIterIndex(NpyIter* it, npy_intp iterindex) except NPY_FAIL
// 判断是否需要延迟缓冲区分配
npy_bool NpyIter_HasDelayedBufAlloc(NpyIter* it) nogil
// 判断是否启用外部循环
npy_bool NpyIter_HasExternalLoop(NpyIter* it) nogil
// 判断是否具有多索引
npy_bool NpyIter_HasMultiIndex(NpyIter* it) nogil
// 判断是否具有索引
npy_bool NpyIter_HasIndex(NpyIter* it) nogil
// 判断是否需要缓冲区
npy_bool NpyIter_RequiresBuffering(NpyIter* it) nogil
// 判断是否已缓冲
npy_bool NpyIter_IsBuffered(NpyIter* it) nogil
// 判断是否为增长内部迭代
npy_bool NpyIter_IsGrowInner(NpyIter* it) nogil
// 获取缓冲区大小
npy_intp NpyIter_GetBufferSize(NpyIter* it) nogil
// 获取迭代器的维度数
int NpyIter_GetNDim(NpyIter* it) nogil
// 获取操作数的数量
int NpyIter_GetNOp(NpyIter* it) nogil
// 获取指定轴的步幅数组
npy_intp* NpyIter_GetAxisStrideArray(NpyIter* it, int axis) except NULL
// 获取迭代器的形状
int NpyIter_GetShape(NpyIter* it, npy_intp* outshape) nogil
// 获取操作数的数据类型数组
PyArray_Descr** NpyIter_GetDescrArray(NpyIter* it)
// 获取操作数对象的指针数组
PyArrayObject** NpyIter_GetOperandArray(NpyIter* it)
// 获取指定迭代索引的迭代视图
ndarray NpyIter_GetIterView(NpyIter* it, npy_intp i)
// 获取读取标志
void NpyIter_GetReadFlags(NpyIter* it, char* outreadflags)
// 获取写入标志
void NpyIter_GetWriteFlags(NpyIter* it, char* outwriteflags)
// 创建兼容步幅数组
int NpyIter_CreateCompatibleStrides(NpyIter* it, npy_intp itemsize, npy_intp* outstrides) except NPY_FAIL
// 判断是否是第一次访问指定操作数
npy_bool NpyIter_IsFirstVisit(NpyIter* it, int iop) nogil
// 获取迭代器的下一个迭代函数
NpyIter_IterNextFunc* NpyIter_GetIterNext(NpyIter* it, char** errmsg) except NULL
// 获取获取多索引的函数
NpyIter_GetMultiIndexFunc* NpyIter_GetGetMultiIndex(NpyIter* it, char** errmsg) except NULL
char** NpyIter_GetDataPtrArray(NpyIter* it) nogil
char** NpyIter_GetInitialDataPtrArray(NpyIter* it) nogil
npy_intp* NpyIter_GetIndexPtr(NpyIter* it)
npy_intp* NpyIter_GetInnerStrideArray(NpyIter* it) nogil
npy_intp* NpyIter_GetInnerLoopSizePtr(NpyIter* it) nogil
void NpyIter_GetInnerFixedStrideArray(NpyIter* it, npy_intp* outstrides) nogil
npy_bool NpyIter_IterationNeedsAPI(NpyIter* it) nogil
void NpyIter_DebugPrint(NpyIter* it)