comment here

This commit is contained in:
ton
2023-03-18 20:03:34 +07:00
commit 4553a0a589
14513 changed files with 2685043 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
Copyright (c) 2005-2022, NumPy Developers.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the NumPy Developers nor the names of any
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The NumPy repository and source distributions bundle several libraries that are
compatibly licensed. We list these here.
Name: lapack-lite
Files: numpy/linalg/lapack_lite/*
License: BSD-3-Clause
For details, see numpy/linalg/lapack_lite/LICENSE.txt
Name: tempita
Files: tools/npy_tempita/*
License: MIT
For details, see tools/npy_tempita/license.txt
Name: dragon4
Files: numpy/core/src/multiarray/dragon4.c
License: MIT
For license text, see numpy/core/src/multiarray/dragon4.c
Name: libdivide
Files: numpy/core/include/numpy/libdivide/*
License: Zlib
For license text, see numpy/core/include/numpy/libdivide/LICENSE.txt

View File

@@ -0,0 +1,115 @@
# This file is generated by numpy's setup.py
# It contains system_info results at the time of building this package.
__all__ = ["get_info","show"]
import os
import sys
extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs')
if sys.platform == 'win32' and os.path.isdir(extra_dll_dir):
os.add_dll_directory(extra_dll_dir)
blas_info={'libraries': ['cblas', 'blas', 'cblas', 'blas'], 'library_dirs': ['/home/ton/.julia/dev/ImageUtils/.CondaPkg/env/lib'], 'include_dirs': ['/home/ton/.julia/dev/ImageUtils/.CondaPkg/env/include'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None)]}
blas_opt_info={'define_macros': [('NO_ATLAS_INFO', 1), ('HAVE_CBLAS', None)], 'libraries': ['cblas', 'blas', 'cblas', 'blas'], 'library_dirs': ['/home/ton/.julia/dev/ImageUtils/.CondaPkg/env/lib'], 'include_dirs': ['/home/ton/.julia/dev/ImageUtils/.CondaPkg/env/include'], 'language': 'c'}
lapack_info={'libraries': ['lapack', 'blas', 'lapack', 'blas'], 'library_dirs': ['/home/ton/.julia/dev/ImageUtils/.CondaPkg/env/lib'], 'language': 'f77'}
lapack_opt_info={'libraries': ['lapack', 'blas', 'lapack', 'blas', 'cblas', 'blas', 'cblas', 'blas'], 'library_dirs': ['/home/ton/.julia/dev/ImageUtils/.CondaPkg/env/lib'], 'language': 'c', 'define_macros': [('NO_ATLAS_INFO', 1), ('HAVE_CBLAS', None)], 'include_dirs': ['/home/ton/.julia/dev/ImageUtils/.CondaPkg/env/include']}
def get_info(name):
g = globals()
return g.get(name, g.get(name + "_info", {}))
def show():
"""
Show libraries in the system on which NumPy was built.
Print information about various resources (libraries, library
directories, include directories, etc.) in the system on which
NumPy was built.
See Also
--------
get_include : Returns the directory containing NumPy C
header files.
Notes
-----
1. Classes specifying the information to be printed are defined
in the `numpy.distutils.system_info` module.
Information may include:
* ``language``: language used to write the libraries (mostly
C or f77)
* ``libraries``: names of libraries found in the system
* ``library_dirs``: directories containing the libraries
* ``include_dirs``: directories containing library header files
* ``src_dirs``: directories containing library source files
* ``define_macros``: preprocessor macros used by
``distutils.setup``
* ``baseline``: minimum CPU features required
* ``found``: dispatched features supported in the system
* ``not found``: dispatched features that are not supported
in the system
2. NumPy BLAS/LAPACK Installation Notes
Installing a numpy wheel (``pip install numpy`` or force it
via ``pip install numpy --only-binary :numpy: numpy``) includes
an OpenBLAS implementation of the BLAS and LAPACK linear algebra
APIs. In this case, ``library_dirs`` reports the original build
time configuration as compiled with gcc/gfortran; at run time
the OpenBLAS library is in
``site-packages/numpy.libs/`` (linux), or
``site-packages/numpy/.dylibs/`` (macOS), or
``site-packages/numpy/.libs/`` (windows).
Installing numpy from source
(``pip install numpy --no-binary numpy``) searches for BLAS and
LAPACK dynamic link libraries at build time as influenced by
environment variables NPY_BLAS_LIBS, NPY_CBLAS_LIBS, and
NPY_LAPACK_LIBS; or NPY_BLAS_ORDER and NPY_LAPACK_ORDER;
or the optional file ``~/.numpy-site.cfg``.
NumPy remembers those locations and expects to load the same
libraries at run-time.
In NumPy 1.21+ on macOS, 'accelerate' (Apple's Accelerate BLAS
library) is in the default build-time search order after
'openblas'.
Examples
--------
>>> import numpy as np
>>> np.show_config()
blas_opt_info:
language = c
define_macros = [('HAVE_CBLAS', None)]
libraries = ['openblas', 'openblas']
library_dirs = ['/usr/local/lib']
"""
from numpy.core._multiarray_umath import (
__cpu_features__, __cpu_baseline__, __cpu_dispatch__
)
for name,info_dict in globals().items():
if name[0] == "_" or type(info_dict) is not type({}): continue
print(name + ":")
if not info_dict:
print(" NOT AVAILABLE")
for k,v in info_dict.items():
v = str(v)
if k == "sources" and len(v) > 200:
v = v[:60] + " ...\n... " + v[-60:]
print(" %s = %s" % (k,v))
features_found, features_not_found = [], []
for feature in __cpu_dispatch__:
if __cpu_features__[feature]:
features_found.append(feature)
else:
features_not_found.append(feature)
print("Supported SIMD extensions in this NumPy install:")
print(" baseline = %s" % (','.join(__cpu_baseline__)))
print(" found = %s" % (','.join(features_found)))
print(" not found = %s" % (','.join(features_not_found)))

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,439 @@
"""
NumPy
=====
Provides
1. An array object of arbitrary homogeneous items
2. Fast mathematical operations over arrays
3. Linear Algebra, Fourier Transforms, Random Number Generation
How to use the documentation
----------------------------
Documentation is available in two forms: docstrings provided
with the code, and a loose standing reference guide, available from
`the NumPy homepage <https://numpy.org>`_.
We recommend exploring the docstrings using
`IPython <https://ipython.org>`_, an advanced Python shell with
TAB-completion and introspection capabilities. See below for further
instructions.
The docstring examples assume that `numpy` has been imported as ``np``::
>>> import numpy as np
Code snippets are indicated by three greater-than signs::
>>> x = 42
>>> x = x + 1
Use the built-in ``help`` function to view a function's docstring::
>>> help(np.sort)
... # doctest: +SKIP
For some objects, ``np.info(obj)`` may provide additional help. This is
particularly true if you see the line "Help on ufunc object:" at the top
of the help() page. Ufuncs are implemented in C, not Python, for speed.
The native Python help() does not know how to view their help, but our
np.info() function does.
To search for documents containing a keyword, do::
>>> np.lookfor('keyword')
... # doctest: +SKIP
General-purpose documents like a glossary and help on the basic concepts
of numpy are available under the ``doc`` sub-module::
>>> from numpy import doc
>>> help(doc)
... # doctest: +SKIP
Available subpackages
---------------------
lib
Basic functions used by several sub-packages.
random
Core Random Tools
linalg
Core Linear Algebra Tools
fft
Core FFT routines
polynomial
Polynomial tools
testing
NumPy testing tools
distutils
Enhancements to distutils with support for
Fortran compilers support and more.
Utilities
---------
test
Run numpy unittests
show_config
Show numpy build configuration
dual
Overwrite certain functions with high-performance SciPy tools.
Note: `numpy.dual` is deprecated. Use the functions from NumPy or Scipy
directly instead of importing them from `numpy.dual`.
matlib
Make everything matrices.
__version__
NumPy version string
Viewing documentation using IPython
-----------------------------------
Start IPython and import `numpy` usually under the alias ``np``: `import
numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste
examples into the shell. To see which functions are available in `numpy`,
type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
down the list. To view the docstring for a function, use
``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view
the source code).
Copies vs. in-place operation
-----------------------------
Most of the functions in `numpy` return a copy of the array argument
(e.g., `np.sort`). In-place versions of these functions are often
available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
Exceptions to this rule are documented.
"""
import sys
import warnings
from ._globals import (
ModuleDeprecationWarning, VisibleDeprecationWarning,
_NoValue, _CopyMode
)
# We first need to detect if we're being called as part of the numpy setup
# procedure itself in a reliable manner.
try:
__NUMPY_SETUP__
except NameError:
__NUMPY_SETUP__ = False
if __NUMPY_SETUP__:
sys.stderr.write('Running from numpy source directory.\n')
else:
try:
from numpy.__config__ import show as show_config
except ImportError as e:
msg = """Error importing numpy: you should not try to import numpy from
its source directory; please exit the numpy source tree, and relaunch
your python interpreter from there."""
raise ImportError(msg) from e
__all__ = ['ModuleDeprecationWarning',
'VisibleDeprecationWarning']
# mapping of {name: (value, deprecation_msg)}
__deprecated_attrs__ = {}
# Allow distributors to run custom init code
from . import _distributor_init
from . import core
from .core import *
from . import compat
from . import lib
# NOTE: to be revisited following future namespace cleanup.
# See gh-14454 and gh-15672 for discussion.
from .lib import *
from . import linalg
from . import fft
from . import polynomial
from . import random
from . import ctypeslib
from . import ma
from . import matrixlib as _mat
from .matrixlib import *
# Deprecations introduced in NumPy 1.20.0, 2020-06-06
import builtins as _builtins
_msg = (
"module 'numpy' has no attribute '{n}'.\n"
"`np.{n}` was a deprecated alias for the builtin `{n}`. "
"To avoid this error in existing code, use `{n}` by itself. "
"Doing this will not modify any behavior and is safe. {extended_msg}\n"
"The aliases was originally deprecated in NumPy 1.20; for more "
"details and guidance see the original release note at:\n"
" https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
_specific_msg = (
"If you specifically wanted the numpy scalar type, use `np.{}` here.")
_int_extended_msg = (
"When replacing `np.{}`, you may wish to use e.g. `np.int64` "
"or `np.int32` to specify the precision. If you wish to review "
"your current use, check the release note link for "
"additional information.")
_type_info = [
("object", ""), # The NumPy scalar only exists by name.
("bool", _specific_msg.format("bool_")),
("float", _specific_msg.format("float64")),
("complex", _specific_msg.format("complex128")),
("str", _specific_msg.format("str_")),
("int", _int_extended_msg.format("int"))]
__former_attrs__ = {
n: _msg.format(n=n, extended_msg=extended_msg)
for n, extended_msg in _type_info
}
# Future warning introduced in NumPy 1.24.0, 2022-11-17
_msg = (
"`np.{n}` is a deprecated alias for `{an}`. (Deprecated NumPy 1.24)")
# Some of these are awkward (since `np.str` may be preferable in the long
# term), but overall the names ending in 0 seem undesireable
_type_info = [
("bool8", bool_, "np.bool_"),
("int0", intp, "np.intp"),
("uint0", uintp, "np.uintp"),
("str0", str_, "np.str_"),
("bytes0", bytes_, "np.bytes_"),
("void0", void, "np.void"),
("object0", object_,
"`np.object0` is a deprecated alias for `np.object_`. "
"`object` can be used instead. (Deprecated NumPy 1.24)")]
# Some of these could be defined right away, but most were aliases to
# the Python objects and only removed in NumPy 1.24. Defining them should
# probably wait for NumPy 1.26 or 2.0.
# When defined, these should possibly not be added to `__all__` to avoid
# import with `from numpy import *`.
__future_scalars__ = {"bool", "long", "ulong", "str", "bytes", "object"}
__deprecated_attrs__.update({
n: (alias, _msg.format(n=n, an=an)) for n, alias, an in _type_info})
del _msg, _type_info
from .core import round, abs, max, min
# now that numpy modules are imported, can initialize limits
core.getlimits._register_known_types()
__all__.extend(['__version__', 'show_config'])
__all__.extend(core.__all__)
__all__.extend(_mat.__all__)
__all__.extend(lib.__all__)
__all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
# Remove one of the two occurrences of `issubdtype`, which is exposed as
# both `numpy.core.issubdtype` and `numpy.lib.issubdtype`.
__all__.remove('issubdtype')
# These are exported by np.core, but are replaced by the builtins below
# remove them to ensure that we don't end up with `np.long == np.int_`,
# which would be a breaking change.
del long, unicode
__all__.remove('long')
__all__.remove('unicode')
# Remove things that are in the numpy.lib but not in the numpy namespace
# Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace)
# that prevents adding more things to the main namespace by accident.
# The list below will grow until the `from .lib import *` fixme above is
# taken care of
__all__.remove('Arrayterator')
del Arrayterator
# These names were removed in NumPy 1.20. For at least one release,
# attempts to access these names in the numpy namespace will trigger
# a warning, and calling the function will raise an exception.
_financial_names = ['fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt',
'ppmt', 'pv', 'rate']
__expired_functions__ = {
name: (f'In accordance with NEP 32, the function {name} was removed '
'from NumPy version 1.20. A replacement for this function '
'is available in the numpy_financial library: '
'https://pypi.org/project/numpy-financial')
for name in _financial_names}
# Filter out Cython harmless warnings
warnings.filterwarnings("ignore", message="numpy.dtype size changed")
warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
# oldnumeric and numarray were removed in 1.9. In case some packages import
# but do not use them, we define them here for backward compatibility.
oldnumeric = 'removed'
numarray = 'removed'
def __getattr__(attr):
# Warn for expired attributes, and return a dummy function
# that always raises an exception.
import warnings
try:
msg = __expired_functions__[attr]
except KeyError:
pass
else:
warnings.warn(msg, DeprecationWarning, stacklevel=2)
def _expired(*args, **kwds):
raise RuntimeError(msg)
return _expired
# Emit warnings for deprecated attributes
try:
val, msg = __deprecated_attrs__[attr]
except KeyError:
pass
else:
warnings.warn(msg, DeprecationWarning, stacklevel=2)
return val
if attr in __future_scalars__:
# And future warnings for those that will change, but also give
# the AttributeError
warnings.warn(
f"In the future `np.{attr}` will be defined as the "
"corresponding NumPy scalar.", FutureWarning, stacklevel=2)
if attr in __former_attrs__:
raise AttributeError(__former_attrs__[attr])
# Importing Tester requires importing all of UnitTest which is not a
# cheap import Since it is mainly used in test suits, we lazy import it
# here to save on the order of 10 ms of import time for most users
#
# The previous way Tester was imported also had a side effect of adding
# the full `numpy.testing` namespace
if attr == 'testing':
import numpy.testing as testing
return testing
elif attr == 'Tester':
from .testing import Tester
return Tester
raise AttributeError("module {!r} has no attribute "
"{!r}".format(__name__, attr))
def __dir__():
public_symbols = globals().keys() | {'Tester', 'testing'}
public_symbols -= {
"core", "matrixlib",
}
return list(public_symbols)
# Pytest testing
from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
del PytestTester
def _sanity_check():
"""
Quick sanity checks for common bugs caused by environment.
There are some cases e.g. with wrong BLAS ABI that cause wrong
results under specific runtime conditions that are not necessarily
achieved during test suite runs, and it is useful to catch those early.
See https://github.com/numpy/numpy/issues/8577 and other
similar bug reports.
"""
try:
x = ones(2, dtype=float32)
if not abs(x.dot(x) - float32(2.0)) < 1e-5:
raise AssertionError()
except AssertionError:
msg = ("The current Numpy installation ({!r}) fails to "
"pass simple sanity checks. This can be caused for example "
"by incorrect BLAS library being linked in, or by mixing "
"package managers (pip, conda, apt, ...). Search closed "
"numpy issues for similar problems.")
raise RuntimeError(msg.format(__file__)) from None
_sanity_check()
del _sanity_check
def _mac_os_check():
"""
Quick Sanity check for Mac OS look for accelerate build bugs.
Testing numpy polyfit calls init_dgelsd(LAPACK)
"""
try:
c = array([3., 2., 1.])
x = linspace(0, 2, 5)
y = polyval(c, x)
_ = polyfit(x, y, 2, cov=True)
except ValueError:
pass
if sys.platform == "darwin":
with warnings.catch_warnings(record=True) as w:
_mac_os_check()
# Throw runtime error, if the test failed Check for warning and error_message
error_message = ""
if len(w) > 0:
error_message = "{}: {}".format(w[-1].category.__name__, str(w[-1].message))
msg = (
"Polyfit sanity test emitted a warning, most likely due "
"to using a buggy Accelerate backend."
"\nIf you compiled yourself, more information is available at:"
"\nhttps://numpy.org/doc/stable/user/building.html#accelerated-blas-lapack-libraries"
"\nOtherwise report this to the vendor "
"that provided NumPy.\n{}\n".format(error_message))
raise RuntimeError(msg)
del _mac_os_check
# We usually use madvise hugepages support, but on some old kernels it
# is slow and thus better avoided.
# Specifically kernel version 4.6 had a bug fix which probably fixed this:
# https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
import os
use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
if sys.platform == "linux" and use_hugepage is None:
# If there is an issue with parsing the kernel version,
# set use_hugepages to 0. Usage of LooseVersion will handle
# the kernel version parsing better, but avoided since it
# will increase the import time. See: #16679 for related discussion.
try:
use_hugepage = 1
kernel_version = os.uname().release.split(".")[:2]
kernel_version = tuple(int(v) for v in kernel_version)
if kernel_version < (4, 6):
use_hugepage = 0
except ValueError:
use_hugepages = 0
elif use_hugepage is None:
# This is not Linux, so it should not matter, just enable anyway
use_hugepage = 1
else:
use_hugepage = int(use_hugepage)
# Note that this will currently only make a difference on Linux
core.multiarray._set_madvise_hugepage(use_hugepage)
# Give a warning if NumPy is reloaded or imported on a sub-interpreter
# We do this from python, since the C-module may not be reloaded and
# it is tidier organized.
core.multiarray._multiarray_umath._reload_guard()
core._set_promotion_state(os.environ.get("NPY_PROMOTION_STATE", "legacy"))
# Tell PyInstaller where to find hook-numpy.py
def _pyinstaller_hooks_dir():
from pathlib import Path
return [str(Path(__file__).with_name("_pyinstaller").resolve())]
# Remove symbols imported for internal use
del os
# get the version using versioneer
from .version import __version__, git_revision as __git_version__
# Remove symbols imported for internal use
del sys, warnings

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,10 @@
""" Distributor init file
Distributors: you can add custom code here to support particular distributions
of numpy.
For example, this is a good place to put any checks for hardware requirements.
The numpy standard source distribution will not put code in this file, so you
can safely replace this file with your own version.
"""

View File

@@ -0,0 +1,125 @@
"""
Module defining global singleton classes.
This module raises a RuntimeError if an attempt to reload it is made. In that
way the identities of the classes defined here are fixed and will remain so
even if numpy itself is reloaded. In particular, a function like the following
will still work correctly after numpy is reloaded::
def foo(arg=np._NoValue):
if arg is np._NoValue:
...
That was not the case when the singleton classes were defined in the numpy
``__init__.py`` file. See gh-7844 for a discussion of the reload problem that
motivated this module.
"""
import enum
__ALL__ = [
'ModuleDeprecationWarning', 'VisibleDeprecationWarning',
'_NoValue', '_CopyMode'
]
# Disallow reloading this module so as to preserve the identities of the
# classes defined here.
if '_is_loaded' in globals():
raise RuntimeError('Reloading numpy._globals is not allowed')
_is_loaded = True
class ModuleDeprecationWarning(DeprecationWarning):
"""Module deprecation warning.
The nose tester turns ordinary Deprecation warnings into test failures.
That makes it hard to deprecate whole modules, because they get
imported by default. So this is a special Deprecation warning that the
nose tester will let pass without making tests fail.
"""
ModuleDeprecationWarning.__module__ = 'numpy'
class VisibleDeprecationWarning(UserWarning):
"""Visible deprecation warning.
By default, python will not show deprecation warnings, so this class
can be used when a very visible warning is helpful, for example because
the usage is most likely a user bug.
"""
VisibleDeprecationWarning.__module__ = 'numpy'
class _NoValueType:
"""Special keyword value.
The instance of this class may be used as the default value assigned to a
keyword if no other obvious default (e.g., `None`) is suitable,
Common reasons for using this keyword are:
- A new keyword is added to a function, and that function forwards its
inputs to another function or method which can be defined outside of
NumPy. For example, ``np.std(x)`` calls ``x.std``, so when a ``keepdims``
keyword was added that could only be forwarded if the user explicitly
specified ``keepdims``; downstream array libraries may not have added
the same keyword, so adding ``x.std(..., keepdims=keepdims)``
unconditionally could have broken previously working code.
- A keyword is being deprecated, and a deprecation warning must only be
emitted when the keyword is used.
"""
__instance = None
def __new__(cls):
# ensure that only one instance exists
if not cls.__instance:
cls.__instance = super().__new__(cls)
return cls.__instance
def __repr__(self):
return "<no value>"
_NoValue = _NoValueType()
class _CopyMode(enum.Enum):
"""
An enumeration for the copy modes supported
by numpy.copy() and numpy.array(). The following three modes are supported,
- ALWAYS: This means that a deep copy of the input
array will always be taken.
- IF_NEEDED: This means that a deep copy of the input
array will be taken only if necessary.
- NEVER: This means that the deep copy will never be taken.
If a copy cannot be avoided then a `ValueError` will be
raised.
Note that the buffer-protocol could in theory do copies. NumPy currently
assumes an object exporting the buffer protocol will never do this.
"""
ALWAYS = True
IF_NEEDED = False
NEVER = 2
def __bool__(self):
# For backwards compatibility
if self == _CopyMode.ALWAYS:
return True
if self == _CopyMode.IF_NEEDED:
return False
raise ValueError(f"{self} is neither True nor False.")
_CopyMode.__module__ = 'numpy'

View File

@@ -0,0 +1,40 @@
"""This hook should collect all binary files and any hidden modules that numpy
needs.
Our (some-what inadequate) docs for writing PyInstaller hooks are kept here:
https://pyinstaller.readthedocs.io/en/stable/hooks.html
"""
from PyInstaller.compat import is_conda, is_pure_conda
from PyInstaller.utils.hooks import collect_dynamic_libs, is_module_satisfies
# Collect all DLLs inside numpy's installation folder, dump them into built
# app's root.
binaries = collect_dynamic_libs("numpy", ".")
# If using Conda without any non-conda virtual environment manager:
if is_pure_conda:
# Assume running the NumPy from Conda-forge and collect it's DLLs from the
# communal Conda bin directory. DLLs from NumPy's dependencies must also be
# collected to capture MKL, OpenBlas, OpenMP, etc.
from PyInstaller.utils.hooks import conda_support
datas = conda_support.collect_dynamic_libs("numpy", dependencies=True)
# Submodules PyInstaller cannot detect (probably because they are only imported
# by extension modules, which PyInstaller cannot read).
hiddenimports = ['numpy.core._dtype_ctypes']
if is_conda:
hiddenimports.append("six")
# Remove testing and building code and packages that are referenced throughout
# NumPy but are not really dependencies.
excludedimports = [
"scipy",
"pytest",
"nose",
"f2py",
"setuptools",
"numpy.f2py",
"distutils",
"numpy.distutils",
]

View File

@@ -0,0 +1,32 @@
"""A crude *bit of everything* smoke test to verify PyInstaller compatibility.
PyInstaller typically goes wrong by forgetting to package modules, extension
modules or shared libraries. This script should aim to touch as many of those
as possible in an attempt to trip a ModuleNotFoundError or a DLL load failure
due to an uncollected resource. Missing resources are unlikely to lead to
arithmetic errors so there's generally no need to verify any calculation's
output - merely that it made it to the end OK. This script should not
explicitly import any of numpy's submodules as that gives PyInstaller undue
hints that those submodules exist and should be collected (accessing implicitly
loaded submodules is OK).
"""
import numpy as np
a = np.arange(1., 10.).reshape((3, 3)) % 5
np.linalg.det(a)
a @ a
a @ a.T
np.linalg.inv(a)
np.sin(np.exp(a))
np.linalg.svd(a)
np.linalg.eigh(a)
np.unique(np.random.randint(0, 10, 100))
np.sort(np.random.uniform(0, 10, 100))
np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
np.ma.masked_array(np.arange(10), np.random.rand(10) < .5).sum()
np.polynomial.Legendre([7, 8, 9]).roots()
print("I made it!")

View File

@@ -0,0 +1,35 @@
import subprocess
from pathlib import Path
import pytest
# PyInstaller has been very unproactive about replacing 'imp' with 'importlib'.
@pytest.mark.filterwarnings('ignore::DeprecationWarning')
# It also leaks io.BytesIO()s.
@pytest.mark.filterwarnings('ignore::ResourceWarning')
@pytest.mark.parametrize("mode", ["--onedir", "--onefile"])
@pytest.mark.slow
def test_pyinstaller(mode, tmp_path):
"""Compile and run pyinstaller-smoke.py using PyInstaller."""
pyinstaller_cli = pytest.importorskip("PyInstaller.__main__").run
source = Path(__file__).with_name("pyinstaller-smoke.py").resolve()
args = [
# Place all generated files in ``tmp_path``.
'--workpath', str(tmp_path / "build"),
'--distpath', str(tmp_path / "dist"),
'--specpath', str(tmp_path),
mode,
str(source),
]
pyinstaller_cli(args)
if mode == "--onefile":
exe = tmp_path / "dist" / source.stem
else:
exe = tmp_path / "dist" / source.stem / source.stem
p = subprocess.run([str(exe)], check=True, stdout=subprocess.PIPE)
assert p.stdout.strip() == b"I made it!"

View File

@@ -0,0 +1,206 @@
"""
Pytest test running.
This module implements the ``test()`` function for NumPy modules. The usual
boiler plate for doing that is to put the following in the module
``__init__.py`` file::
from numpy._pytesttester import PytestTester
test = PytestTester(__name__)
del PytestTester
Warnings filtering and other runtime settings should be dealt with in the
``pytest.ini`` file in the numpy repo root. The behavior of the test depends on
whether or not that file is found as follows:
* ``pytest.ini`` is present (develop mode)
All warnings except those explicitly filtered out are raised as error.
* ``pytest.ini`` is absent (release mode)
DeprecationWarnings and PendingDeprecationWarnings are ignored, other
warnings are passed through.
In practice, tests run from the numpy repo are run in develop mode. That
includes the standard ``python runtests.py`` invocation.
This module is imported by every numpy subpackage, so lies at the top level to
simplify circular import issues. For the same reason, it contains no numpy
imports at module scope, instead importing numpy within function calls.
"""
import sys
import os
__all__ = ['PytestTester']
def _show_numpy_info():
import numpy as np
print("NumPy version %s" % np.__version__)
relaxed_strides = np.ones((10, 1), order="C").flags.f_contiguous
print("NumPy relaxed strides checking option:", relaxed_strides)
info = np.lib.utils._opt_info()
print("NumPy CPU features: ", (info if info else 'nothing enabled'))
class PytestTester:
"""
Pytest test runner.
A test function is typically added to a package's __init__.py like so::
from numpy._pytesttester import PytestTester
test = PytestTester(__name__).test
del PytestTester
Calling this test function finds and runs all tests associated with the
module and all its sub-modules.
Attributes
----------
module_name : str
Full path to the package to test.
Parameters
----------
module_name : module name
The name of the module to test.
Notes
-----
Unlike the previous ``nose``-based implementation, this class is not
publicly exposed as it performs some ``numpy``-specific warning
suppression.
"""
def __init__(self, module_name):
self.module_name = module_name
def __call__(self, label='fast', verbose=1, extra_argv=None,
doctests=False, coverage=False, durations=-1, tests=None):
"""
Run tests for module using pytest.
Parameters
----------
label : {'fast', 'full'}, optional
Identifies the tests to run. When set to 'fast', tests decorated
with `pytest.mark.slow` are skipped, when 'full', the slow marker
is ignored.
verbose : int, optional
Verbosity value for test outputs, in the range 1-3. Default is 1.
extra_argv : list, optional
List with any extra arguments to pass to pytests.
doctests : bool, optional
.. note:: Not supported
coverage : bool, optional
If True, report coverage of NumPy code. Default is False.
Requires installation of (pip) pytest-cov.
durations : int, optional
If < 0, do nothing, If 0, report time of all tests, if > 0,
report the time of the slowest `timer` tests. Default is -1.
tests : test or list of tests
Tests to be executed with pytest '--pyargs'
Returns
-------
result : bool
Return True on success, false otherwise.
Notes
-----
Each NumPy module exposes `test` in its namespace to run all tests for
it. For example, to run all tests for numpy.lib:
>>> np.lib.test() #doctest: +SKIP
Examples
--------
>>> result = np.lib.test() #doctest: +SKIP
...
1023 passed, 2 skipped, 6 deselected, 1 xfailed in 10.39 seconds
>>> result
True
"""
import pytest
import warnings
module = sys.modules[self.module_name]
module_path = os.path.abspath(module.__path__[0])
# setup the pytest arguments
pytest_args = ["-l"]
# offset verbosity. The "-q" cancels a "-v".
pytest_args += ["-q"]
with warnings.catch_warnings():
warnings.simplefilter("always")
# Filter out distutils cpu warnings (could be localized to
# distutils tests). ASV has problems with top level import,
# so fetch module for suppression here.
from numpy.distutils import cpuinfo
with warnings.catch_warnings(record=True):
# Ignore the warning from importing the array_api submodule. This
# warning is done on import, so it would break pytest collection,
# but importing it early here prevents the warning from being
# issued when it imported again.
import numpy.array_api
# Filter out annoying import messages. Want these in both develop and
# release mode.
pytest_args += [
"-W ignore:Not importing directory",
"-W ignore:numpy.dtype size changed",
"-W ignore:numpy.ufunc size changed",
"-W ignore::UserWarning:cpuinfo",
]
# When testing matrices, ignore their PendingDeprecationWarnings
pytest_args += [
"-W ignore:the matrix subclass is not",
"-W ignore:Importing from numpy.matlib is",
]
if doctests:
pytest_args += ["--doctest-modules"]
if extra_argv:
pytest_args += list(extra_argv)
if verbose > 1:
pytest_args += ["-" + "v"*(verbose - 1)]
if coverage:
pytest_args += ["--cov=" + module_path]
if label == "fast":
# not importing at the top level to avoid circular import of module
from numpy.testing import IS_PYPY
if IS_PYPY:
pytest_args += ["-m", "not slow and not slow_pypy"]
else:
pytest_args += ["-m", "not slow"]
elif label != "full":
pytest_args += ["-m", label]
if durations >= 0:
pytest_args += ["--durations=%s" % durations]
if tests is None:
tests = [self.module_name]
pytest_args += ["--pyargs"] + list(tests)
# run tests.
_show_numpy_info()
try:
code = pytest.main(pytest_args)
except SystemExit as exc:
code = exc.code
return code == 0

View File

@@ -0,0 +1,18 @@
from collections.abc import Iterable
from typing import Literal as L
__all__: list[str]
class PytestTester:
module_name: str
def __init__(self, module_name: str) -> None: ...
def __call__(
self,
label: L["fast", "full"] = ...,
verbose: int = ...,
extra_argv: None | Iterable[str] = ...,
doctests: L[False] = ...,
coverage: bool = ...,
durations: int = ...,
tests: None | Iterable[str] = ...,
) -> bool: ...

View File

@@ -0,0 +1,225 @@
"""Private counterpart of ``numpy.typing``."""
from __future__ import annotations
from numpy import ufunc
from numpy.core.overrides import set_module
from typing import TYPE_CHECKING, final
@final # Disallow the creation of arbitrary `NBitBase` subclasses
@set_module("numpy.typing")
class NBitBase:
"""
A type representing `numpy.number` precision during static type checking.
Used exclusively for the purpose static type checking, `NBitBase`
represents the base of a hierarchical set of subclasses.
Each subsequent subclass is herein used for representing a lower level
of precision, *e.g.* ``64Bit > 32Bit > 16Bit``.
.. versionadded:: 1.20
Examples
--------
Below is a typical usage example: `NBitBase` is herein used for annotating
a function that takes a float and integer of arbitrary precision
as arguments and returns a new float of whichever precision is largest
(*e.g.* ``np.float16 + np.int64 -> np.float64``).
.. code-block:: python
>>> from __future__ import annotations
>>> from typing import TypeVar, TYPE_CHECKING
>>> import numpy as np
>>> import numpy.typing as npt
>>> T1 = TypeVar("T1", bound=npt.NBitBase)
>>> T2 = TypeVar("T2", bound=npt.NBitBase)
>>> def add(a: np.floating[T1], b: np.integer[T2]) -> np.floating[T1 | T2]:
... return a + b
>>> a = np.float16()
>>> b = np.int64()
>>> out = add(a, b)
>>> if TYPE_CHECKING:
... reveal_locals()
... # note: Revealed local types are:
... # note: a: numpy.floating[numpy.typing._16Bit*]
... # note: b: numpy.signedinteger[numpy.typing._64Bit*]
... # note: out: numpy.floating[numpy.typing._64Bit*]
"""
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__()
# Silence errors about subclassing a `@final`-decorated class
class _256Bit(NBitBase): # type: ignore[misc]
pass
class _128Bit(_256Bit): # type: ignore[misc]
pass
class _96Bit(_128Bit): # type: ignore[misc]
pass
class _80Bit(_96Bit): # type: ignore[misc]
pass
class _64Bit(_80Bit): # type: ignore[misc]
pass
class _32Bit(_64Bit): # type: ignore[misc]
pass
class _16Bit(_32Bit): # type: ignore[misc]
pass
class _8Bit(_16Bit): # type: ignore[misc]
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,
_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,
_LongLongCodes as _LongLongCodes,
_UByteCodes as _UByteCodes,
_UShortCodes as _UShortCodes,
_UIntCCodes as _UIntCCodes,
_UIntPCodes as _UIntPCodes,
_UIntCodes as _UIntCodes,
_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 (
ArrayLike as ArrayLike,
_ArrayLike as _ArrayLike,
_FiniteNestedSequence as _FiniteNestedSequence,
_SupportsArray as _SupportsArray,
_SupportsArrayFunc as _SupportsArrayFunc,
_ArrayLikeInt as _ArrayLikeInt,
_ArrayLikeBool_co as _ArrayLikeBool_co,
_ArrayLikeUInt_co as _ArrayLikeUInt_co,
_ArrayLikeInt_co as _ArrayLikeInt_co,
_ArrayLikeFloat_co as _ArrayLikeFloat_co,
_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,
)
from ._generic_alias import (
NDArray as NDArray,
_DType as _DType,
_GenericAlias as _GenericAlias,
)
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:
# Declare the (type-check-only) ufunc subclasses as ufunc aliases during
# runtime; this helps autocompletion tools such as Jedi (numpy/numpy#19834)
_UFunc_Nin1_Nout1 = ufunc
_UFunc_Nin2_Nout1 = ufunc
_UFunc_Nin1_Nout2 = ufunc
_UFunc_Nin2_Nout2 = ufunc
_GUFunc_Nin2_Nout1 = ufunc

View File

@@ -0,0 +1,152 @@
"""A module for creating docstrings for sphinx ``data`` domains."""
import re
import textwrap
from ._generic_alias import NDArray
_docstrings_list = []
def add_newdoc(name: str, value: str, doc: str) -> None:
"""Append ``_docstrings_list`` with a docstring for `name`.
Parameters
----------
name : str
The name of the object.
value : str
A string-representation of the object.
doc : str
The docstring of the object.
"""
_docstrings_list.append((name, value, doc))
def _parse_docstrings() -> str:
"""Convert all docstrings in ``_docstrings_list`` into a single
sphinx-legible text block.
"""
type_list_ret = []
for name, value, doc in _docstrings_list:
s = textwrap.dedent(doc).replace("\n", "\n ")
# Replace sections by rubrics
lines = s.split("\n")
new_lines = []
indent = ""
for line in lines:
m = re.match(r'^(\s+)[-=]+\s*$', line)
if m and new_lines:
prev = textwrap.dedent(new_lines.pop())
if prev == "Examples":
indent = ""
new_lines.append(f'{m.group(1)}.. rubric:: {prev}')
else:
indent = 4 * " "
new_lines.append(f'{m.group(1)}.. admonition:: {prev}')
new_lines.append("")
else:
new_lines.append(f"{indent}{line}")
s = "\n".join(new_lines)
s_block = f""".. data:: {name}\n :value: {value}\n {s}"""
type_list_ret.append(s_block)
return "\n".join(type_list_ret)
add_newdoc('ArrayLike', 'typing.Union[...]',
"""
A `~typing.Union` representing objects that can be coerced
into an `~numpy.ndarray`.
Among others this includes the likes of:
* Scalars.
* (Nested) sequences.
* Objects implementing the `~class.__array__` protocol.
.. versionadded:: 1.20
See Also
--------
:term:`array_like`:
Any scalar or sequence that can be interpreted as an ndarray.
Examples
--------
.. code-block:: python
>>> import numpy as np
>>> import numpy.typing as npt
>>> def as_array(a: npt.ArrayLike) -> np.ndarray:
... return np.array(a)
""")
add_newdoc('DTypeLike', 'typing.Union[...]',
"""
A `~typing.Union` representing objects that can be coerced
into a `~numpy.dtype`.
Among others this includes the likes of:
* :class:`type` objects.
* Character codes or the names of :class:`type` objects.
* Objects with the ``.dtype`` attribute.
.. versionadded:: 1.20
See Also
--------
:ref:`Specifying and constructing data types <arrays.dtypes.constructing>`
A comprehensive overview of all objects that can be coerced
into data types.
Examples
--------
.. code-block:: python
>>> import numpy as np
>>> import numpy.typing as npt
>>> def as_dtype(d: npt.DTypeLike) -> np.dtype:
... return np.dtype(d)
""")
add_newdoc('NDArray', repr(NDArray),
"""
A :term:`generic <generic type>` version of
`np.ndarray[Any, np.dtype[+ScalarType]] <numpy.ndarray>`.
Can be used during runtime for typing arrays with a given dtype
and unspecified shape.
.. versionadded:: 1.21
Examples
--------
.. code-block:: python
>>> import numpy as np
>>> import numpy.typing as npt
>>> print(npt.NDArray)
numpy.ndarray[typing.Any, numpy.dtype[+ScalarType]]
>>> print(npt.NDArray[np.float64])
numpy.ndarray[typing.Any, numpy.dtype[numpy.float64]]
>>> NDArrayInt = npt.NDArray[np.int_]
>>> a: NDArrayInt = np.arange(10)
>>> def func(a: npt.ArrayLike) -> npt.NDArray[Any]:
... return np.array(a)
""")
_docstrings = _parse_docstrings()

View File

@@ -0,0 +1,165 @@
from __future__ import annotations
# NOTE: Import `Sequence` from `typing` as we it is needed for a type-alias,
# not an annotation
import sys
from collections.abc import Collection, Callable
from typing import Any, Sequence, Protocol, Union, TypeVar, runtime_checkable
from numpy import (
ndarray,
dtype,
generic,
bool_,
unsignedinteger,
integer,
floating,
complexfloating,
number,
timedelta64,
datetime64,
object_,
void,
str_,
bytes_,
)
from ._nested_sequence import _NestedSequence
_T = TypeVar("_T")
_ScalarType = TypeVar("_ScalarType", bound=generic)
_DType = TypeVar("_DType", bound="dtype[Any]")
_DType_co = TypeVar("_DType_co", covariant=True, bound="dtype[Any]")
# The `_SupportsArray` protocol only cares about the default dtype
# (i.e. `dtype=None` or no `dtype` parameter at all) of the to-be returned
# array.
# Concrete implementations of the protocol are responsible for adding
# any and all remaining overloads
@runtime_checkable
class _SupportsArray(Protocol[_DType_co]):
def __array__(self) -> ndarray[Any, _DType_co]: ...
@runtime_checkable
class _SupportsArrayFunc(Protocol):
"""A protocol class representing `~class.__array_function__`."""
def __array_function__(
self,
func: Callable[..., Any],
types: Collection[type[Any]],
args: tuple[Any, ...],
kwargs: dict[str, Any],
) -> object: ...
# TODO: Wait until mypy supports recursive objects in combination with typevars
_FiniteNestedSequence = Union[
_T,
Sequence[_T],
Sequence[Sequence[_T]],
Sequence[Sequence[Sequence[_T]]],
Sequence[Sequence[Sequence[Sequence[_T]]]],
]
# A subset of `npt.ArrayLike` that can be parametrized w.r.t. `np.generic`
_ArrayLike = Union[
_SupportsArray["dtype[_ScalarType]"],
_NestedSequence[_SupportsArray["dtype[_ScalarType]"]],
]
# A union representing array-like objects; consists of two typevars:
# One representing types that can be parametrized w.r.t. `np.dtype`
# and another one for the rest
_DualArrayLike = Union[
_SupportsArray[_DType],
_NestedSequence[_SupportsArray[_DType]],
_T,
_NestedSequence[_T],
]
# TODO: support buffer protocols once
#
# https://bugs.python.org/issue27501
#
# is resolved. See also the mypy issue:
#
# https://github.com/python/typing/issues/593
if sys.version_info[:2] < (3, 9):
ArrayLike = _DualArrayLike[
dtype,
Union[bool, int, float, complex, str, bytes],
]
else:
ArrayLike = _DualArrayLike[
dtype[Any],
Union[bool, int, float, complex, str, bytes],
]
# `ArrayLike<X>_co`: array-like objects that can be coerced into `X`
# given the casting rules `same_kind`
_ArrayLikeBool_co = _DualArrayLike[
"dtype[bool_]",
bool,
]
_ArrayLikeUInt_co = _DualArrayLike[
"dtype[Union[bool_, unsignedinteger[Any]]]",
bool,
]
_ArrayLikeInt_co = _DualArrayLike[
"dtype[Union[bool_, integer[Any]]]",
Union[bool, int],
]
_ArrayLikeFloat_co = _DualArrayLike[
"dtype[Union[bool_, integer[Any], floating[Any]]]",
Union[bool, int, float],
]
_ArrayLikeComplex_co = _DualArrayLike[
"dtype[Union[bool_, integer[Any], floating[Any], complexfloating[Any, Any]]]",
Union[bool, int, float, complex],
]
_ArrayLikeNumber_co = _DualArrayLike[
"dtype[Union[bool_, number[Any]]]",
Union[bool, int, float, complex],
]
_ArrayLikeTD64_co = _DualArrayLike[
"dtype[Union[bool_, integer[Any], timedelta64]]",
Union[bool, int],
]
_ArrayLikeDT64_co = Union[
_SupportsArray["dtype[datetime64]"],
_NestedSequence[_SupportsArray["dtype[datetime64]"]],
]
_ArrayLikeObject_co = Union[
_SupportsArray["dtype[object_]"],
_NestedSequence[_SupportsArray["dtype[object_]"]],
]
_ArrayLikeVoid_co = Union[
_SupportsArray["dtype[void]"],
_NestedSequence[_SupportsArray["dtype[void]"]],
]
_ArrayLikeStr_co = _DualArrayLike[
"dtype[str_]",
str,
]
_ArrayLikeBytes_co = _DualArrayLike[
"dtype[bytes_]",
bytes,
]
_ArrayLikeInt = _DualArrayLike[
"dtype[integer[Any]]",
int,
]
# Extra ArrayLike type so that pyright can deal with NDArray[Any]
# Used as the first overload, should only match NDArray[Any],
# not any actual types.
# https://github.com/numpy/numpy/pull/22193
class _UnknownType:
...
_ArrayLikeUnknown = _DualArrayLike[
"dtype[_UnknownType]",
_UnknownType,
]

View File

@@ -0,0 +1,338 @@
"""
A module with various ``typing.Protocol`` subclasses that implement
the ``__call__`` magic method.
See the `Mypy documentation`_ on protocols for more details.
.. _`Mypy documentation`: https://mypy.readthedocs.io/en/stable/protocols.html#callback-protocols
"""
from __future__ import annotations
from typing import (
TypeVar,
overload,
Any,
NoReturn,
Protocol,
)
from numpy import (
ndarray,
dtype,
generic,
bool_,
timedelta64,
number,
integer,
unsignedinteger,
signedinteger,
int8,
int_,
floating,
float64,
complexfloating,
complex128,
)
from ._nbit import _NBitInt, _NBitDouble
from ._scalars import (
_BoolLike_co,
_IntLike_co,
_FloatLike_co,
_NumberLike_co,
)
from . import NBitBase
from ._generic_alias import NDArray
from ._nested_sequence import _NestedSequence
_T1 = TypeVar("_T1")
_T2 = TypeVar("_T2")
_T1_contra = TypeVar("_T1_contra", contravariant=True)
_T2_contra = TypeVar("_T2_contra", contravariant=True)
_2Tuple = tuple[_T1, _T1]
_NBit1 = TypeVar("_NBit1", bound=NBitBase)
_NBit2 = TypeVar("_NBit2", bound=NBitBase)
_IntType = TypeVar("_IntType", bound=integer)
_FloatType = TypeVar("_FloatType", bound=floating)
_NumberType = TypeVar("_NumberType", bound=number)
_NumberType_co = TypeVar("_NumberType_co", covariant=True, bound=number)
_GenericType_co = TypeVar("_GenericType_co", covariant=True, bound=generic)
class _BoolOp(Protocol[_GenericType_co]):
@overload
def __call__(self, other: _BoolLike_co, /) -> _GenericType_co: ...
@overload # platform dependent
def __call__(self, other: int, /) -> int_: ...
@overload
def __call__(self, other: float, /) -> float64: ...
@overload
def __call__(self, other: complex, /) -> complex128: ...
@overload
def __call__(self, other: _NumberType, /) -> _NumberType: ...
class _BoolBitOp(Protocol[_GenericType_co]):
@overload
def __call__(self, other: _BoolLike_co, /) -> _GenericType_co: ...
@overload # platform dependent
def __call__(self, other: int, /) -> int_: ...
@overload
def __call__(self, other: _IntType, /) -> _IntType: ...
class _BoolSub(Protocol):
# Note that `other: bool_` is absent here
@overload
def __call__(self, other: bool, /) -> NoReturn: ...
@overload # platform dependent
def __call__(self, other: int, /) -> int_: ...
@overload
def __call__(self, other: float, /) -> float64: ...
@overload
def __call__(self, other: complex, /) -> complex128: ...
@overload
def __call__(self, other: _NumberType, /) -> _NumberType: ...
class _BoolTrueDiv(Protocol):
@overload
def __call__(self, other: float | _IntLike_co, /) -> float64: ...
@overload
def __call__(self, other: complex, /) -> complex128: ...
@overload
def __call__(self, other: _NumberType, /) -> _NumberType: ...
class _BoolMod(Protocol):
@overload
def __call__(self, other: _BoolLike_co, /) -> int8: ...
@overload # platform dependent
def __call__(self, other: int, /) -> int_: ...
@overload
def __call__(self, other: float, /) -> float64: ...
@overload
def __call__(self, other: _IntType, /) -> _IntType: ...
@overload
def __call__(self, other: _FloatType, /) -> _FloatType: ...
class _BoolDivMod(Protocol):
@overload
def __call__(self, other: _BoolLike_co, /) -> _2Tuple[int8]: ...
@overload # platform dependent
def __call__(self, other: int, /) -> _2Tuple[int_]: ...
@overload
def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
@overload
def __call__(self, other: _IntType, /) -> _2Tuple[_IntType]: ...
@overload
def __call__(self, other: _FloatType, /) -> _2Tuple[_FloatType]: ...
class _TD64Div(Protocol[_NumberType_co]):
@overload
def __call__(self, other: timedelta64, /) -> _NumberType_co: ...
@overload
def __call__(self, other: _BoolLike_co, /) -> NoReturn: ...
@overload
def __call__(self, other: _FloatLike_co, /) -> timedelta64: ...
class _IntTrueDiv(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> floating[_NBit1]: ...
@overload
def __call__(self, other: int, /) -> floating[_NBit1 | _NBitInt]: ...
@overload
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, other: complex, /,
) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
@overload
def __call__(self, other: integer[_NBit2], /) -> floating[_NBit1 | _NBit2]: ...
class _UnsignedIntOp(Protocol[_NBit1]):
# NOTE: `uint64 + signedinteger -> float64`
@overload
def __call__(self, other: bool, /) -> unsignedinteger[_NBit1]: ...
@overload
def __call__(
self, other: int | signedinteger[Any], /
) -> Any: ...
@overload
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, other: complex, /,
) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, other: unsignedinteger[_NBit2], /
) -> unsignedinteger[_NBit1 | _NBit2]: ...
class _UnsignedIntBitOp(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> unsignedinteger[_NBit1]: ...
@overload
def __call__(self, other: int, /) -> signedinteger[Any]: ...
@overload
def __call__(self, other: signedinteger[Any], /) -> signedinteger[Any]: ...
@overload
def __call__(
self, other: unsignedinteger[_NBit2], /
) -> unsignedinteger[_NBit1 | _NBit2]: ...
class _UnsignedIntMod(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> unsignedinteger[_NBit1]: ...
@overload
def __call__(
self, other: int | signedinteger[Any], /
) -> Any: ...
@overload
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, other: unsignedinteger[_NBit2], /
) -> unsignedinteger[_NBit1 | _NBit2]: ...
class _UnsignedIntDivMod(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> _2Tuple[signedinteger[_NBit1]]: ...
@overload
def __call__(
self, other: int | signedinteger[Any], /
) -> _2Tuple[Any]: ...
@overload
def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
@overload
def __call__(
self, other: unsignedinteger[_NBit2], /
) -> _2Tuple[unsignedinteger[_NBit1 | _NBit2]]: ...
class _SignedIntOp(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> signedinteger[_NBit1]: ...
@overload
def __call__(self, other: int, /) -> signedinteger[_NBit1 | _NBitInt]: ...
@overload
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, other: complex, /,
) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, other: signedinteger[_NBit2], /,
) -> signedinteger[_NBit1 | _NBit2]: ...
class _SignedIntBitOp(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> signedinteger[_NBit1]: ...
@overload
def __call__(self, other: int, /) -> signedinteger[_NBit1 | _NBitInt]: ...
@overload
def __call__(
self, other: signedinteger[_NBit2], /,
) -> signedinteger[_NBit1 | _NBit2]: ...
class _SignedIntMod(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> signedinteger[_NBit1]: ...
@overload
def __call__(self, other: int, /) -> signedinteger[_NBit1 | _NBitInt]: ...
@overload
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, other: signedinteger[_NBit2], /,
) -> signedinteger[_NBit1 | _NBit2]: ...
class _SignedIntDivMod(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> _2Tuple[signedinteger[_NBit1]]: ...
@overload
def __call__(self, other: int, /) -> _2Tuple[signedinteger[_NBit1 | _NBitInt]]: ...
@overload
def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
@overload
def __call__(
self, other: signedinteger[_NBit2], /,
) -> _2Tuple[signedinteger[_NBit1 | _NBit2]]: ...
class _FloatOp(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> floating[_NBit1]: ...
@overload
def __call__(self, other: int, /) -> floating[_NBit1 | _NBitInt]: ...
@overload
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, other: complex, /,
) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, other: integer[_NBit2] | floating[_NBit2], /
) -> floating[_NBit1 | _NBit2]: ...
class _FloatMod(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> floating[_NBit1]: ...
@overload
def __call__(self, other: int, /) -> floating[_NBit1 | _NBitInt]: ...
@overload
def __call__(self, other: float, /) -> floating[_NBit1 | _NBitDouble]: ...
@overload
def __call__(
self, other: integer[_NBit2] | floating[_NBit2], /
) -> floating[_NBit1 | _NBit2]: ...
class _FloatDivMod(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> _2Tuple[floating[_NBit1]]: ...
@overload
def __call__(self, other: int, /) -> _2Tuple[floating[_NBit1 | _NBitInt]]: ...
@overload
def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1 | _NBitDouble]]: ...
@overload
def __call__(
self, other: integer[_NBit2] | floating[_NBit2], /
) -> _2Tuple[floating[_NBit1 | _NBit2]]: ...
class _ComplexOp(Protocol[_NBit1]):
@overload
def __call__(self, other: bool, /) -> complexfloating[_NBit1, _NBit1]: ...
@overload
def __call__(self, other: int, /) -> complexfloating[_NBit1 | _NBitInt, _NBit1 | _NBitInt]: ...
@overload
def __call__(
self, other: complex, /,
) -> complexfloating[_NBit1 | _NBitDouble, _NBit1 | _NBitDouble]: ...
@overload
def __call__(
self,
other: (
integer[_NBit2]
| floating[_NBit2]
| complexfloating[_NBit2, _NBit2]
), /,
) -> complexfloating[_NBit1 | _NBit2, _NBit1 | _NBit2]: ...
class _NumberOp(Protocol):
def __call__(self, other: _NumberLike_co, /) -> Any: ...
class _SupportsLT(Protocol):
def __lt__(self, other: Any, /) -> object: ...
class _SupportsGT(Protocol):
def __gt__(self, other: Any, /) -> object: ...
class _ComparisonOp(Protocol[_T1_contra, _T2_contra]):
@overload
def __call__(self, other: _T1_contra, /) -> bool_: ...
@overload
def __call__(self, other: _T2_contra, /) -> NDArray[bool_]: ...
@overload
def __call__(
self,
other: _SupportsLT | _SupportsGT | _NestedSequence[_SupportsLT | _SupportsGT],
/,
) -> Any: ...

View File

@@ -0,0 +1,111 @@
from typing import Literal
_BoolCodes = Literal["?", "=?", "<?", ">?", "bool", "bool_", "bool8"]
_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", "int0", "p", "=p", "<p", ">p"]
_IntCodes = Literal["long", "int", "int_", "l", "=l", "<l", ">l"]
_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", "uint0", "P", "=P", "<P", ">P"]
_UIntCodes = Literal["ulong", "uint", "L", "=L", "<L", ">L"]
_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", "float_", "d", "=d", "<d", ">d"]
_LongDoubleCodes = Literal["longdouble", "longfloat", "g", "=g", "<g", ">g"]
_CSingleCodes = Literal["csingle", "singlecomplex", "F", "=F", "<F", ">F"]
_CDoubleCodes = Literal["cdouble", "complex", "complex_", "cfloat", "D", "=D", "<D", ">D"]
_CLongDoubleCodes = Literal["clongdouble", "clongfloat", "longcomplex", "G", "=G", "<G", ">G"]
_StrCodes = Literal["str", "str_", "str0", "unicode", "unicode_", "U", "=U", "<U", ">U"]
_BytesCodes = Literal["bytes", "bytes_", "bytes0", "S", "=S", "<S", ">S"]
_VoidCodes = Literal["void", "void0", "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]",
]

View File

@@ -0,0 +1,249 @@
from typing import (
Any,
List,
Sequence,
Tuple,
Union,
Type,
TypeVar,
Protocol,
TypedDict,
runtime_checkable,
)
import numpy as np
from ._shape import _ShapeLike
from ._generic_alias import _DType as DType
from ._char_codes import (
_BoolCodes,
_UInt8Codes,
_UInt16Codes,
_UInt32Codes,
_UInt64Codes,
_Int8Codes,
_Int16Codes,
_Int32Codes,
_Int64Codes,
_Float16Codes,
_Float32Codes,
_Float64Codes,
_Complex64Codes,
_Complex128Codes,
_ByteCodes,
_ShortCodes,
_IntCCodes,
_IntPCodes,
_IntCodes,
_LongLongCodes,
_UByteCodes,
_UShortCodes,
_UIntCCodes,
_UIntPCodes,
_UIntCodes,
_ULongLongCodes,
_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=DType[Any])
_DTypeLikeNested = Any # TODO: wait for support for recursive types
# Mandatory keys
class _DTypeDictBase(TypedDict):
names: Sequence[str]
formats: Sequence[_DTypeLikeNested]
# Mandatory + optional keys
class _DTypeDict(_DTypeDictBase, total=False):
# Only `str` elements are usable as indexing aliases,
# but `titles` can in principle accept any object
offsets: Sequence[int]
titles: Sequence[Any]
itemsize: int
aligned: bool
# A protocol for anything with the dtype attribute
@runtime_checkable
class _SupportsDType(Protocol[_DType_co]):
@property
def dtype(self) -> _DType_co: ...
# A subset of `npt.DTypeLike` that can be parametrized w.r.t. `np.generic`
_DTypeLike = Union[
"np.dtype[_SCT]",
Type[_SCT],
_SupportsDType["np.dtype[_SCT]"],
]
# Would create a dtype[np.void]
_VoidDTypeLike = Union[
# (flexible_dtype, itemsize)
Tuple[_DTypeLikeNested, int],
# (fixed_dtype, shape)
Tuple[_DTypeLikeNested, _ShapeLike],
# [(field_name, field_dtype, field_shape), ...]
#
# The type here is quite broad because NumPy accepts quite a wide
# range of inputs inside the list; see the tests for some
# examples.
List[Any],
# {'names': ..., 'formats': ..., 'offsets': ..., 'titles': ...,
# 'itemsize': ...}
_DTypeDict,
# (base_dtype, new_dtype)
Tuple[_DTypeLikeNested, _DTypeLikeNested],
]
# Anything that can be coerced into numpy.dtype.
# Reference: https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html
DTypeLike = Union[
DType[Any],
# default data type (float64)
None,
# array-scalar types and generic types
Type[Any], # NOTE: We're stuck with `Type[Any]` due to object dtypes
# anything with a dtype attribute
_SupportsDType[DType[Any]],
# character codes, type strings or comma-separated fields, e.g., 'float64'
str,
_VoidDTypeLike,
]
# NOTE: while it is possible to provide the dtype as a dict of
# dtype-like objects (e.g. `{'field1': ..., 'field2': ..., ...}`),
# this syntax is officially discourged and
# therefore not included in the Union defining `DTypeLike`.
#
# See https://github.com/numpy/numpy/issues/16891 for more details.
# Aliases for commonly used dtype-like objects.
# Note that the precision of `np.number` subclasses is ignored herein.
_DTypeLikeBool = Union[
Type[bool],
Type[np.bool_],
DType[np.bool_],
_SupportsDType[DType[np.bool_]],
_BoolCodes,
]
_DTypeLikeUInt = Union[
Type[np.unsignedinteger],
DType[np.unsignedinteger],
_SupportsDType[DType[np.unsignedinteger]],
_UInt8Codes,
_UInt16Codes,
_UInt32Codes,
_UInt64Codes,
_UByteCodes,
_UShortCodes,
_UIntCCodes,
_UIntPCodes,
_UIntCodes,
_ULongLongCodes,
]
_DTypeLikeInt = Union[
Type[int],
Type[np.signedinteger],
DType[np.signedinteger],
_SupportsDType[DType[np.signedinteger]],
_Int8Codes,
_Int16Codes,
_Int32Codes,
_Int64Codes,
_ByteCodes,
_ShortCodes,
_IntCCodes,
_IntPCodes,
_IntCodes,
_LongLongCodes,
]
_DTypeLikeFloat = Union[
Type[float],
Type[np.floating],
DType[np.floating],
_SupportsDType[DType[np.floating]],
_Float16Codes,
_Float32Codes,
_Float64Codes,
_HalfCodes,
_SingleCodes,
_DoubleCodes,
_LongDoubleCodes,
]
_DTypeLikeComplex = Union[
Type[complex],
Type[np.complexfloating],
DType[np.complexfloating],
_SupportsDType[DType[np.complexfloating]],
_Complex64Codes,
_Complex128Codes,
_CSingleCodes,
_CDoubleCodes,
_CLongDoubleCodes,
]
_DTypeLikeDT64 = Union[
Type[np.timedelta64],
DType[np.timedelta64],
_SupportsDType[DType[np.timedelta64]],
_TD64Codes,
]
_DTypeLikeTD64 = Union[
Type[np.datetime64],
DType[np.datetime64],
_SupportsDType[DType[np.datetime64]],
_DT64Codes,
]
_DTypeLikeStr = Union[
Type[str],
Type[np.str_],
DType[np.str_],
_SupportsDType[DType[np.str_]],
_StrCodes,
]
_DTypeLikeBytes = Union[
Type[bytes],
Type[np.bytes_],
DType[np.bytes_],
_SupportsDType[DType[np.bytes_]],
_BytesCodes,
]
_DTypeLikeVoid = Union[
Type[np.void],
DType[np.void],
_SupportsDType[DType[np.void]],
_VoidCodes,
_VoidDTypeLike,
]
_DTypeLikeObject = Union[
type,
DType[np.object_],
_SupportsDType[DType[np.object_]],
_ObjectCodes,
]
_DTypeLikeComplex_co = Union[
_DTypeLikeBool,
_DTypeLikeUInt,
_DTypeLikeInt,
_DTypeLikeFloat,
_DTypeLikeComplex,
]

View File

@@ -0,0 +1,43 @@
"""A module with platform-specific extended precision
`numpy.number` subclasses.
The subclasses are defined here (instead of ``__init__.pyi``) such
that they can be imported conditionally via the numpy's mypy plugin.
"""
from typing import TYPE_CHECKING
import numpy as np
from . import (
_80Bit,
_96Bit,
_128Bit,
_256Bit,
)
if TYPE_CHECKING:
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]
else:
uint128 = Any
uint256 = Any
int128 = Any
int256 = Any
float80 = Any
float96 = Any
float128 = Any
float256 = Any
complex160 = Any
complex192 = Any
complex256 = Any
complex512 = Any

View File

@@ -0,0 +1,245 @@
from __future__ import annotations
import sys
import types
from collections.abc import Generator, Iterable, Iterator
from typing import (
Any,
ClassVar,
NoReturn,
TypeVar,
TYPE_CHECKING,
)
import numpy as np
__all__ = ["_GenericAlias", "NDArray"]
_T = TypeVar("_T", bound="_GenericAlias")
def _to_str(obj: object) -> str:
"""Helper function for `_GenericAlias.__repr__`."""
if obj is Ellipsis:
return '...'
elif isinstance(obj, type) and not isinstance(obj, _GENERIC_ALIAS_TYPE):
if obj.__module__ == 'builtins':
return obj.__qualname__
else:
return f'{obj.__module__}.{obj.__qualname__}'
else:
return repr(obj)
def _parse_parameters(args: Iterable[Any]) -> Generator[TypeVar, None, None]:
"""Search for all typevars and typevar-containing objects in `args`.
Helper function for `_GenericAlias.__init__`.
"""
for i in args:
if hasattr(i, "__parameters__"):
yield from i.__parameters__
elif isinstance(i, TypeVar):
yield i
def _reconstruct_alias(alias: _T, parameters: Iterator[TypeVar]) -> _T:
"""Recursively replace all typevars with those from `parameters`.
Helper function for `_GenericAlias.__getitem__`.
"""
args = []
for i in alias.__args__:
if isinstance(i, TypeVar):
value: Any = next(parameters)
elif isinstance(i, _GenericAlias):
value = _reconstruct_alias(i, parameters)
elif hasattr(i, "__parameters__"):
prm_tup = tuple(next(parameters) for _ in i.__parameters__)
value = i[prm_tup]
else:
value = i
args.append(value)
cls = type(alias)
return cls(alias.__origin__, tuple(args), alias.__unpacked__)
class _GenericAlias:
"""A python-based backport of the `types.GenericAlias` class.
E.g. for ``t = list[int]``, ``t.__origin__`` is ``list`` and
``t.__args__`` is ``(int,)``.
See Also
--------
:pep:`585`
The PEP responsible for introducing `types.GenericAlias`.
"""
__slots__ = (
"__weakref__",
"_origin",
"_args",
"_parameters",
"_hash",
"_starred",
)
@property
def __origin__(self) -> type:
return super().__getattribute__("_origin")
@property
def __args__(self) -> tuple[object, ...]:
return super().__getattribute__("_args")
@property
def __parameters__(self) -> tuple[TypeVar, ...]:
"""Type variables in the ``GenericAlias``."""
return super().__getattribute__("_parameters")
@property
def __unpacked__(self) -> bool:
return super().__getattribute__("_starred")
@property
def __typing_unpacked_tuple_args__(self) -> tuple[object, ...] | None:
# NOTE: This should return `__args__` if `__origin__` is a tuple,
# which should never be the case with how `_GenericAlias` is used
# within numpy
return None
def __init__(
self,
origin: type,
args: object | tuple[object, ...],
starred: bool = False,
) -> None:
self._origin = origin
self._args = args if isinstance(args, tuple) else (args,)
self._parameters = tuple(_parse_parameters(self.__args__))
self._starred = starred
@property
def __call__(self) -> type[Any]:
return self.__origin__
def __reduce__(self: _T) -> tuple[
type[_T],
tuple[type[Any], tuple[object, ...], bool],
]:
cls = type(self)
return cls, (self.__origin__, self.__args__, self.__unpacked__)
def __mro_entries__(self, bases: Iterable[object]) -> tuple[type[Any]]:
return (self.__origin__,)
def __dir__(self) -> list[str]:
"""Implement ``dir(self)``."""
cls = type(self)
dir_origin = set(dir(self.__origin__))
return sorted(cls._ATTR_EXCEPTIONS | dir_origin)
def __hash__(self) -> int:
"""Return ``hash(self)``."""
# Attempt to use the cached hash
try:
return super().__getattribute__("_hash")
except AttributeError:
self._hash: int = (
hash(self.__origin__) ^
hash(self.__args__) ^
hash(self.__unpacked__)
)
return super().__getattribute__("_hash")
def __instancecheck__(self, obj: object) -> NoReturn:
"""Check if an `obj` is an instance."""
raise TypeError("isinstance() argument 2 cannot be a "
"parameterized generic")
def __subclasscheck__(self, cls: type) -> NoReturn:
"""Check if a `cls` is a subclass."""
raise TypeError("issubclass() argument 2 cannot be a "
"parameterized generic")
def __repr__(self) -> str:
"""Return ``repr(self)``."""
args = ", ".join(_to_str(i) for i in self.__args__)
origin = _to_str(self.__origin__)
prefix = "*" if self.__unpacked__ else ""
return f"{prefix}{origin}[{args}]"
def __getitem__(self: _T, key: object | tuple[object, ...]) -> _T:
"""Return ``self[key]``."""
key_tup = key if isinstance(key, tuple) else (key,)
if len(self.__parameters__) == 0:
raise TypeError(f"There are no type variables left in {self}")
elif len(key_tup) > len(self.__parameters__):
raise TypeError(f"Too many arguments for {self}")
elif len(key_tup) < len(self.__parameters__):
raise TypeError(f"Too few arguments for {self}")
key_iter = iter(key_tup)
return _reconstruct_alias(self, key_iter)
def __eq__(self, value: object) -> bool:
"""Return ``self == value``."""
if not isinstance(value, _GENERIC_ALIAS_TYPE):
return NotImplemented
return (
self.__origin__ == value.__origin__ and
self.__args__ == value.__args__ and
self.__unpacked__ == getattr(
value, "__unpacked__", self.__unpacked__
)
)
def __iter__(self: _T) -> Generator[_T, None, None]:
"""Return ``iter(self)``."""
cls = type(self)
yield cls(self.__origin__, self.__args__, True)
_ATTR_EXCEPTIONS: ClassVar[frozenset[str]] = frozenset({
"__origin__",
"__args__",
"__parameters__",
"__mro_entries__",
"__reduce__",
"__reduce_ex__",
"__copy__",
"__deepcopy__",
"__unpacked__",
"__typing_unpacked_tuple_args__",
"__class__",
})
def __getattribute__(self, name: str) -> Any:
"""Return ``getattr(self, name)``."""
# Pull the attribute from `__origin__` unless its
# name is in `_ATTR_EXCEPTIONS`
cls = type(self)
if name in cls._ATTR_EXCEPTIONS:
return super().__getattribute__(name)
return getattr(self.__origin__, name)
# See `_GenericAlias.__eq__`
if sys.version_info >= (3, 9):
_GENERIC_ALIAS_TYPE = (_GenericAlias, types.GenericAlias)
else:
_GENERIC_ALIAS_TYPE = (_GenericAlias,)
ScalarType = TypeVar("ScalarType", bound=np.generic, covariant=True)
if TYPE_CHECKING or sys.version_info >= (3, 9):
_DType = np.dtype[ScalarType]
NDArray = np.ndarray[Any, np.dtype[ScalarType]]
else:
_DType = _GenericAlias(np.dtype, (ScalarType,))
NDArray = _GenericAlias(np.ndarray, (Any, _DType))

View File

@@ -0,0 +1,16 @@
"""A module with the precisions of platform-specific `~numpy.number`s."""
from typing import Any
# To-be replaced with a `npt.NBitBase` subclass by numpy's mypy plugin
_NBitByte = Any
_NBitShort = Any
_NBitIntC = Any
_NBitIntP = Any
_NBitInt = Any
_NBitLongLong = Any
_NBitHalf = Any
_NBitSingle = Any
_NBitDouble = Any
_NBitLongDouble = Any

View File

@@ -0,0 +1,92 @@
"""A module containing the `_NestedSequence` protocol."""
from __future__ import annotations
from typing import (
Any,
Iterator,
overload,
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
@overload
def __getitem__(self, index: int, /) -> _T_co | _NestedSequence[_T_co]: ...
@overload
def __getitem__(self, index: slice, /) -> _NestedSequence[_T_co]: ...
def __getitem__(self, index, /):
"""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

View File

@@ -0,0 +1,30 @@
from typing import Union, Tuple, Any
import numpy as np
# NOTE: `_StrLike_co` and `_BytesLike_co` are pointless, as `np.str_` and
# `np.bytes_` are already subclasses of their builtin counterpart
_CharLike_co = Union[str, bytes]
# The 6 `<X>Like_co` type-aliases below represent all scalars that can be
# coerced into `<X>` (with the casting rule `same_kind`)
_BoolLike_co = Union[bool, np.bool_]
_UIntLike_co = Union[_BoolLike_co, np.unsignedinteger]
_IntLike_co = Union[_BoolLike_co, int, np.integer]
_FloatLike_co = Union[_IntLike_co, float, np.floating]
_ComplexLike_co = Union[_FloatLike_co, complex, np.complexfloating]
_TD64Like_co = Union[_IntLike_co, np.timedelta64]
_NumberLike_co = Union[int, float, complex, np.number, np.bool_]
_ScalarLike_co = Union[
int,
float,
complex,
str,
bytes,
np.generic,
]
# `_VoidLike_co` is technically not a scalar, but it's close enough
_VoidLike_co = Union[Tuple[Any, ...], np.void]

View File

@@ -0,0 +1,6 @@
from typing import Sequence, Tuple, Union, SupportsIndex
_Shape = Tuple[int, ...]
# Anything that can be coerced to a shape tuple
_ShapeLike = Union[SupportsIndex, Sequence[SupportsIndex]]

View File

@@ -0,0 +1,445 @@
"""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)
class _SupportsArrayUFunc(Protocol):
def __array_ufunc__(
self,
ufunc: ufunc,
method: Literal["__call__", "reduce", "reduceat", "accumulate", "outer", "inner"],
*inputs: Any,
**kwargs: Any,
) -> Any: ...
# NOTE: In reality `extobj` should be a length of list 3 containing an
# int, an int, and a callable, but there's no way to properly express
# non-homogenous lists.
# Use `Any` over `Union` to avoid issues related to lists invariance.
# NOTE: `reduce`, `accumulate`, `reduceat` and `outer` raise a ValueError for
# ufuncs that don't accept two input arguments and return one output argument.
# In such cases the respective methods are simply typed as `None`.
# NOTE: Similarly, `at` won't be defined for ufuncs that return
# multiple outputs; in such cases `at` is typed as `None`
# NOTE: If 2 output types are returned then `out` must be a
# 2-tuple of arrays. Otherwise `None` or a plain array are also acceptable
class _UFunc_Nin1_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc]
@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] = ...,
extobj: list[Any] = ...,
) -> 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] = ...,
extobj: list[Any] = ...,
) -> 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] = ...,
extobj: list[Any] = ...,
) -> Any: ...
def at(
self,
a: _SupportsArrayUFunc,
indices: _ArrayLikeInt_co,
/,
) -> None: ...
class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc]
@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] = ...,
extobj: list[Any] = ...,
) -> 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] = ...,
extobj: list[Any] = ...,
) -> 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]: ...
# Expand `**kwargs` into explicit keyword-only arguments
@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] = ...,
extobj: list[Any] = ...,
) -> Any: ...
@overload
def outer( # type: ignore[misc]
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] = ...,
extobj: list[Any] = ...,
) -> NDArray[Any]: ...
class _UFunc_Nin1_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc]
@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] = ...,
extobj: list[Any] = ...,
) -> _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] = ...,
extobj: list[Any] = ...,
) -> _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] = ...,
extobj: list[Any] = ...,
) -> _2Tuple[Any]: ...
class _UFunc_Nin2_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc]
@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] = ...,
extobj: list[Any] = ...,
) -> _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] = ...,
extobj: list[Any] = ...,
) -> _2Tuple[NDArray[Any]]: ...
class _GUFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]): # type: ignore[misc]
@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]: ...
# NOTE: In practice the only gufunc in the main namespace is `matmul`,
# so we can use its signature here
@property
def signature(self) -> Literal["(n?,k),(k,m?)->(n?,m?)"]: ...
@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: ...
# Scalar for 1D array-likes; ndarray otherwise
@overload
def __call__(
self,
__x1: ArrayLike,
__x2: ArrayLike,
out: None = ...,
*,
casting: _CastingKind = ...,
order: _OrderKACF = ...,
dtype: DTypeLike = ...,
subok: bool = ...,
signature: str | _3Tuple[None | str] = ...,
extobj: list[Any] = ...,
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] = ...,
extobj: list[Any] = ...,
axes: list[_2Tuple[SupportsIndex]] = ...,
) -> NDArray[Any]: ...

View File

@@ -0,0 +1,10 @@
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration('_typing', parent_package, top_path)
config.add_data_files('*.pyi')
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(configuration=configuration)

View File

@@ -0,0 +1,21 @@
# This file was generated by 'versioneer.py' (0.26) from
# revision-control system data, or from the parent directory name of an
# unpacked source archive. Distribution tarballs contain a pre-generated copy
# of this file.
import json
version_json = '''
{
"date": "2023-02-05T11:25:52-0500",
"dirty": false,
"error": null,
"full-revisionid": "85f38ab180ece5290f64e8ddbd9cf06ad8fa4a5e",
"version": "1.24.2"
}
''' # END VERSION_JSON
def get_versions():
return json.loads(version_json)

View File

@@ -0,0 +1,377 @@
"""
A NumPy sub-namespace that conforms to the Python array API standard.
This submodule accompanies NEP 47, which proposes its inclusion in NumPy. It
is still considered experimental, and will issue a warning when imported.
This is a proof-of-concept namespace that wraps the corresponding NumPy
functions to give a conforming implementation of the Python array API standard
(https://data-apis.github.io/array-api/latest/). The standard is currently in
an RFC phase and comments on it are both welcome and encouraged. Comments
should be made either at https://github.com/data-apis/array-api or at
https://github.com/data-apis/consortium-feedback/discussions.
NumPy already follows the proposed spec for the most part, so this module
serves mostly as a thin wrapper around it. However, NumPy also implements a
lot of behavior that is not included in the spec, so this serves as a
restricted subset of the API. Only those functions that are part of the spec
are included in this namespace, and all functions are given with the exact
signature given in the spec, including the use of position-only arguments, and
omitting any extra keyword arguments implemented by NumPy but not part of the
spec. The behavior of some functions is also modified from the NumPy behavior
to conform to the standard. Note that the underlying array object itself is
wrapped in a wrapper Array() class, but is otherwise unchanged. This submodule
is implemented in pure Python with no C extensions.
The array API spec is designed as a "minimal API subset" and explicitly allows
libraries to include behaviors not specified by it. But users of this module
that intend to write portable code should be aware that only those behaviors
that are listed in the spec are guaranteed to be implemented across libraries.
Consequently, the NumPy implementation was chosen to be both conforming and
minimal, so that users can use this implementation of the array API namespace
and be sure that behaviors that it defines will be available in conforming
namespaces from other libraries.
A few notes about the current state of this submodule:
- There is a test suite that tests modules against the array API standard at
https://github.com/data-apis/array-api-tests. The test suite is still a work
in progress, but the existing tests pass on this module, with a few
exceptions:
- DLPack support (see https://github.com/data-apis/array-api/pull/106) is
not included here, as it requires a full implementation in NumPy proper
first.
The test suite is not yet complete, and even the tests that exist are not
guaranteed to give a comprehensive coverage of the spec. Therefore, when
reviewing and using this submodule, you should refer to the standard
documents themselves. There are some tests in numpy.array_api.tests, but
they primarily focus on things that are not tested by the official array API
test suite.
- There is a custom array object, numpy.array_api.Array, which is returned by
all functions in this module. All functions in the array API namespace
implicitly assume that they will only receive this object as input. The only
way to create instances of this object is to use one of the array creation
functions. It does not have a public constructor on the object itself. The
object is a small wrapper class around numpy.ndarray. The main purpose of it
is to restrict the namespace of the array object to only those dtypes and
only those methods that are required by the spec, as well as to limit/change
certain behavior that differs in the spec. In particular:
- The array API namespace does not have scalar objects, only 0-D arrays.
Operations on Array that would create a scalar in NumPy create a 0-D
array.
- Indexing: Only a subset of indices supported by NumPy are required by the
spec. The Array object restricts indexing to only allow those types of
indices that are required by the spec. See the docstring of the
numpy.array_api.Array._validate_indices helper function for more
information.
- Type promotion: Some type promotion rules are different in the spec. In
particular, the spec does not have any value-based casting. The spec also
does not require cross-kind casting, like integer -> floating-point. Only
those promotions that are explicitly required by the array API
specification are allowed in this module. See NEP 47 for more info.
- Functions do not automatically call asarray() on their input, and will not
work if the input type is not Array. The exception is array creation
functions, and Python operators on the Array object, which accept Python
scalars of the same type as the array dtype.
- All functions include type annotations, corresponding to those given in the
spec (see _typing.py for definitions of some custom types). These do not
currently fully pass mypy due to some limitations in mypy.
- Dtype objects are just the NumPy dtype objects, e.g., float64 =
np.dtype('float64'). The spec does not require any behavior on these dtype
objects other than that they be accessible by name and be comparable by
equality, but it was considered too much extra complexity to create custom
objects to represent dtypes.
- All places where the implementations in this submodule are known to deviate
from their corresponding functions in NumPy are marked with "# Note:"
comments.
Still TODO in this module are:
- DLPack support for numpy.ndarray is still in progress. See
https://github.com/numpy/numpy/pull/19083.
- The copy=False keyword argument to asarray() is not yet implemented. This
requires support in numpy.asarray() first.
- Some functions are not yet fully tested in the array API test suite, and may
require updates that are not yet known until the tests are written.
- The spec is still in an RFC phase and may still have minor updates, which
will need to be reflected here.
- Complex number support in array API spec is planned but not yet finalized,
as are the fft extension and certain linear algebra functions such as eig
that require complex dtypes.
"""
import warnings
warnings.warn(
"The numpy.array_api submodule is still experimental. See NEP 47.", stacklevel=2
)
__array_api_version__ = "2021.12"
__all__ = ["__array_api_version__"]
from ._constants import e, inf, nan, pi
__all__ += ["e", "inf", "nan", "pi"]
from ._creation_functions import (
asarray,
arange,
empty,
empty_like,
eye,
from_dlpack,
full,
full_like,
linspace,
meshgrid,
ones,
ones_like,
tril,
triu,
zeros,
zeros_like,
)
__all__ += [
"asarray",
"arange",
"empty",
"empty_like",
"eye",
"from_dlpack",
"full",
"full_like",
"linspace",
"meshgrid",
"ones",
"ones_like",
"tril",
"triu",
"zeros",
"zeros_like",
]
from ._data_type_functions import (
astype,
broadcast_arrays,
broadcast_to,
can_cast,
finfo,
iinfo,
result_type,
)
__all__ += [
"astype",
"broadcast_arrays",
"broadcast_to",
"can_cast",
"finfo",
"iinfo",
"result_type",
]
from ._dtypes import (
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
bool,
)
__all__ += [
"int8",
"int16",
"int32",
"int64",
"uint8",
"uint16",
"uint32",
"uint64",
"float32",
"float64",
"bool",
]
from ._elementwise_functions import (
abs,
acos,
acosh,
add,
asin,
asinh,
atan,
atan2,
atanh,
bitwise_and,
bitwise_left_shift,
bitwise_invert,
bitwise_or,
bitwise_right_shift,
bitwise_xor,
ceil,
cos,
cosh,
divide,
equal,
exp,
expm1,
floor,
floor_divide,
greater,
greater_equal,
isfinite,
isinf,
isnan,
less,
less_equal,
log,
log1p,
log2,
log10,
logaddexp,
logical_and,
logical_not,
logical_or,
logical_xor,
multiply,
negative,
not_equal,
positive,
pow,
remainder,
round,
sign,
sin,
sinh,
square,
sqrt,
subtract,
tan,
tanh,
trunc,
)
__all__ += [
"abs",
"acos",
"acosh",
"add",
"asin",
"asinh",
"atan",
"atan2",
"atanh",
"bitwise_and",
"bitwise_left_shift",
"bitwise_invert",
"bitwise_or",
"bitwise_right_shift",
"bitwise_xor",
"ceil",
"cos",
"cosh",
"divide",
"equal",
"exp",
"expm1",
"floor",
"floor_divide",
"greater",
"greater_equal",
"isfinite",
"isinf",
"isnan",
"less",
"less_equal",
"log",
"log1p",
"log2",
"log10",
"logaddexp",
"logical_and",
"logical_not",
"logical_or",
"logical_xor",
"multiply",
"negative",
"not_equal",
"positive",
"pow",
"remainder",
"round",
"sign",
"sin",
"sinh",
"square",
"sqrt",
"subtract",
"tan",
"tanh",
"trunc",
]
# linalg is an extension in the array API spec, which is a sub-namespace. Only
# a subset of functions in it are imported into the top-level namespace.
from . import linalg
__all__ += ["linalg"]
from .linalg import matmul, tensordot, matrix_transpose, vecdot
__all__ += ["matmul", "tensordot", "matrix_transpose", "vecdot"]
from ._manipulation_functions import (
concat,
expand_dims,
flip,
permute_dims,
reshape,
roll,
squeeze,
stack,
)
__all__ += ["concat", "expand_dims", "flip", "permute_dims", "reshape", "roll", "squeeze", "stack"]
from ._searching_functions import argmax, argmin, nonzero, where
__all__ += ["argmax", "argmin", "nonzero", "where"]
from ._set_functions import unique_all, unique_counts, unique_inverse, unique_values
__all__ += ["unique_all", "unique_counts", "unique_inverse", "unique_values"]
from ._sorting_functions import argsort, sort
__all__ += ["argsort", "sort"]
from ._statistical_functions import max, mean, min, prod, std, sum, var
__all__ += ["max", "mean", "min", "prod", "std", "sum", "var"]
from ._utility_functions import all, any
__all__ += ["all", "any"]

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
import numpy as np
e = np.e
inf = np.inf
nan = np.nan
pi = np.pi

View File

@@ -0,0 +1,351 @@
from __future__ import annotations
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
if TYPE_CHECKING:
from ._typing import (
Array,
Device,
Dtype,
NestedSequence,
SupportsBufferProtocol,
)
from collections.abc import Sequence
from ._dtypes import _all_dtypes
import numpy as np
def _check_valid_dtype(dtype):
# Note: Only spelling dtypes as the dtype objects is supported.
# We use this instead of "dtype in _all_dtypes" because the dtype objects
# define equality with the sorts of things we want to disallow.
for d in (None,) + _all_dtypes:
if dtype is d:
return
raise ValueError("dtype must be one of the supported dtypes")
def asarray(
obj: Union[
Array,
bool,
int,
float,
NestedSequence[bool | int | float],
SupportsBufferProtocol,
],
/,
*,
dtype: Optional[Dtype] = None,
device: Optional[Device] = None,
copy: Optional[Union[bool, np._CopyMode]] = None,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.asarray <numpy.asarray>`.
See its docstring for more information.
"""
# _array_object imports in this file are inside the functions to avoid
# circular imports
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
if copy in (False, np._CopyMode.IF_NEEDED):
# Note: copy=False is not yet implemented in np.asarray
raise NotImplementedError("copy=False is not yet implemented")
if isinstance(obj, Array):
if dtype is not None and obj.dtype != dtype:
copy = True
if copy in (True, np._CopyMode.ALWAYS):
return Array._new(np.array(obj._array, copy=True, dtype=dtype))
return obj
if dtype is None and isinstance(obj, int) and (obj > 2 ** 64 or obj < -(2 ** 63)):
# Give a better error message in this case. NumPy would convert this
# to an object array. TODO: This won't handle large integers in lists.
raise OverflowError("Integer out of bounds for array dtypes")
res = np.asarray(obj, dtype=dtype)
return Array._new(res)
def arange(
start: Union[int, float],
/,
stop: Optional[Union[int, float]] = None,
step: Union[int, float] = 1,
*,
dtype: Optional[Dtype] = None,
device: Optional[Device] = None,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.arange <numpy.arange>`.
See its docstring for more information.
"""
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
return Array._new(np.arange(start, stop=stop, step=step, dtype=dtype))
def empty(
shape: Union[int, Tuple[int, ...]],
*,
dtype: Optional[Dtype] = None,
device: Optional[Device] = None,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.empty <numpy.empty>`.
See its docstring for more information.
"""
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
return Array._new(np.empty(shape, dtype=dtype))
def empty_like(
x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.empty_like <numpy.empty_like>`.
See its docstring for more information.
"""
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
return Array._new(np.empty_like(x._array, dtype=dtype))
def eye(
n_rows: int,
n_cols: Optional[int] = None,
/,
*,
k: int = 0,
dtype: Optional[Dtype] = None,
device: Optional[Device] = None,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.eye <numpy.eye>`.
See its docstring for more information.
"""
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
return Array._new(np.eye(n_rows, M=n_cols, k=k, dtype=dtype))
def from_dlpack(x: object, /) -> Array:
from ._array_object import Array
return Array._new(np.from_dlpack(x))
def full(
shape: Union[int, Tuple[int, ...]],
fill_value: Union[int, float],
*,
dtype: Optional[Dtype] = None,
device: Optional[Device] = None,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.full <numpy.full>`.
See its docstring for more information.
"""
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
if isinstance(fill_value, Array) and fill_value.ndim == 0:
fill_value = fill_value._array
res = np.full(shape, fill_value, dtype=dtype)
if res.dtype not in _all_dtypes:
# This will happen if the fill value is not something that NumPy
# coerces to one of the acceptable dtypes.
raise TypeError("Invalid input to full")
return Array._new(res)
def full_like(
x: Array,
/,
fill_value: Union[int, float],
*,
dtype: Optional[Dtype] = None,
device: Optional[Device] = None,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.full_like <numpy.full_like>`.
See its docstring for more information.
"""
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
res = np.full_like(x._array, fill_value, dtype=dtype)
if res.dtype not in _all_dtypes:
# This will happen if the fill value is not something that NumPy
# coerces to one of the acceptable dtypes.
raise TypeError("Invalid input to full_like")
return Array._new(res)
def linspace(
start: Union[int, float],
stop: Union[int, float],
/,
num: int,
*,
dtype: Optional[Dtype] = None,
device: Optional[Device] = None,
endpoint: bool = True,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.linspace <numpy.linspace>`.
See its docstring for more information.
"""
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
return Array._new(np.linspace(start, stop, num, dtype=dtype, endpoint=endpoint))
def meshgrid(*arrays: Array, indexing: str = "xy") -> List[Array]:
"""
Array API compatible wrapper for :py:func:`np.meshgrid <numpy.meshgrid>`.
See its docstring for more information.
"""
from ._array_object import Array
# Note: unlike np.meshgrid, only inputs with all the same dtype are
# allowed
if len({a.dtype for a in arrays}) > 1:
raise ValueError("meshgrid inputs must all have the same dtype")
return [
Array._new(array)
for array in np.meshgrid(*[a._array for a in arrays], indexing=indexing)
]
def ones(
shape: Union[int, Tuple[int, ...]],
*,
dtype: Optional[Dtype] = None,
device: Optional[Device] = None,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.ones <numpy.ones>`.
See its docstring for more information.
"""
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
return Array._new(np.ones(shape, dtype=dtype))
def ones_like(
x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.ones_like <numpy.ones_like>`.
See its docstring for more information.
"""
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
return Array._new(np.ones_like(x._array, dtype=dtype))
def tril(x: Array, /, *, k: int = 0) -> Array:
"""
Array API compatible wrapper for :py:func:`np.tril <numpy.tril>`.
See its docstring for more information.
"""
from ._array_object import Array
if x.ndim < 2:
# Note: Unlike np.tril, x must be at least 2-D
raise ValueError("x must be at least 2-dimensional for tril")
return Array._new(np.tril(x._array, k=k))
def triu(x: Array, /, *, k: int = 0) -> Array:
"""
Array API compatible wrapper for :py:func:`np.triu <numpy.triu>`.
See its docstring for more information.
"""
from ._array_object import Array
if x.ndim < 2:
# Note: Unlike np.triu, x must be at least 2-D
raise ValueError("x must be at least 2-dimensional for triu")
return Array._new(np.triu(x._array, k=k))
def zeros(
shape: Union[int, Tuple[int, ...]],
*,
dtype: Optional[Dtype] = None,
device: Optional[Device] = None,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.zeros <numpy.zeros>`.
See its docstring for more information.
"""
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
return Array._new(np.zeros(shape, dtype=dtype))
def zeros_like(
x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.zeros_like <numpy.zeros_like>`.
See its docstring for more information.
"""
from ._array_object import Array
_check_valid_dtype(dtype)
if device not in ["cpu", None]:
raise ValueError(f"Unsupported device {device!r}")
return Array._new(np.zeros_like(x._array, dtype=dtype))

View File

@@ -0,0 +1,146 @@
from __future__ import annotations
from ._array_object import Array
from ._dtypes import _all_dtypes, _result_type
from dataclasses import dataclass
from typing import TYPE_CHECKING, List, Tuple, Union
if TYPE_CHECKING:
from ._typing import Dtype
from collections.abc import Sequence
import numpy as np
# Note: astype is a function, not an array method as in NumPy.
def astype(x: Array, dtype: Dtype, /, *, copy: bool = True) -> Array:
if not copy and dtype == x.dtype:
return x
return Array._new(x._array.astype(dtype=dtype, copy=copy))
def broadcast_arrays(*arrays: Array) -> List[Array]:
"""
Array API compatible wrapper for :py:func:`np.broadcast_arrays <numpy.broadcast_arrays>`.
See its docstring for more information.
"""
from ._array_object import Array
return [
Array._new(array) for array in np.broadcast_arrays(*[a._array for a in arrays])
]
def broadcast_to(x: Array, /, shape: Tuple[int, ...]) -> Array:
"""
Array API compatible wrapper for :py:func:`np.broadcast_to <numpy.broadcast_to>`.
See its docstring for more information.
"""
from ._array_object import Array
return Array._new(np.broadcast_to(x._array, shape))
def can_cast(from_: Union[Dtype, Array], to: Dtype, /) -> bool:
"""
Array API compatible wrapper for :py:func:`np.can_cast <numpy.can_cast>`.
See its docstring for more information.
"""
if isinstance(from_, Array):
from_ = from_.dtype
elif from_ not in _all_dtypes:
raise TypeError(f"{from_=}, but should be an array_api array or dtype")
if to not in _all_dtypes:
raise TypeError(f"{to=}, but should be a dtype")
# Note: We avoid np.can_cast() as it has discrepancies with the array API,
# since NumPy allows cross-kind casting (e.g., NumPy allows bool -> int8).
# See https://github.com/numpy/numpy/issues/20870
try:
# We promote `from_` and `to` together. We then check if the promoted
# dtype is `to`, which indicates if `from_` can (up)cast to `to`.
dtype = _result_type(from_, to)
return to == dtype
except TypeError:
# _result_type() raises if the dtypes don't promote together
return False
# These are internal objects for the return types of finfo and iinfo, since
# the NumPy versions contain extra data that isn't part of the spec.
@dataclass
class finfo_object:
bits: int
# Note: The types of the float data here are float, whereas in NumPy they
# are scalars of the corresponding float dtype.
eps: float
max: float
min: float
smallest_normal: float
@dataclass
class iinfo_object:
bits: int
max: int
min: int
def finfo(type: Union[Dtype, Array], /) -> finfo_object:
"""
Array API compatible wrapper for :py:func:`np.finfo <numpy.finfo>`.
See its docstring for more information.
"""
fi = np.finfo(type)
# Note: The types of the float data here are float, whereas in NumPy they
# are scalars of the corresponding float dtype.
return finfo_object(
fi.bits,
float(fi.eps),
float(fi.max),
float(fi.min),
float(fi.smallest_normal),
)
def iinfo(type: Union[Dtype, Array], /) -> iinfo_object:
"""
Array API compatible wrapper for :py:func:`np.iinfo <numpy.iinfo>`.
See its docstring for more information.
"""
ii = np.iinfo(type)
return iinfo_object(ii.bits, ii.max, ii.min)
def result_type(*arrays_and_dtypes: Union[Array, Dtype]) -> Dtype:
"""
Array API compatible wrapper for :py:func:`np.result_type <numpy.result_type>`.
See its docstring for more information.
"""
# Note: we use a custom implementation that gives only the type promotions
# required by the spec rather than using np.result_type. NumPy implements
# too many extra type promotions like int64 + uint64 -> float64, and does
# value-based casting on scalar arrays.
A = []
for a in arrays_and_dtypes:
if isinstance(a, Array):
a = a.dtype
elif isinstance(a, np.ndarray) or a not in _all_dtypes:
raise TypeError("result_type() inputs must be array_api arrays or dtypes")
A.append(a)
if len(A) == 0:
raise ValueError("at least one array or dtype is required")
elif len(A) == 1:
return A[0]
else:
t = A[0]
for t2 in A[1:]:
t = _result_type(t, t2)
return t

View File

@@ -0,0 +1,143 @@
import numpy as np
# Note: we use dtype objects instead of dtype classes. The spec does not
# require any behavior on dtypes other than equality.
int8 = np.dtype("int8")
int16 = np.dtype("int16")
int32 = np.dtype("int32")
int64 = np.dtype("int64")
uint8 = np.dtype("uint8")
uint16 = np.dtype("uint16")
uint32 = np.dtype("uint32")
uint64 = np.dtype("uint64")
float32 = np.dtype("float32")
float64 = np.dtype("float64")
# Note: This name is changed
bool = np.dtype("bool")
_all_dtypes = (
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
bool,
)
_boolean_dtypes = (bool,)
_floating_dtypes = (float32, float64)
_integer_dtypes = (int8, int16, int32, int64, uint8, uint16, uint32, uint64)
_integer_or_boolean_dtypes = (
bool,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
)
_numeric_dtypes = (
float32,
float64,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
)
_dtype_categories = {
"all": _all_dtypes,
"numeric": _numeric_dtypes,
"integer": _integer_dtypes,
"integer or boolean": _integer_or_boolean_dtypes,
"boolean": _boolean_dtypes,
"floating-point": _floating_dtypes,
}
# Note: the spec defines a restricted type promotion table compared to NumPy.
# In particular, cross-kind promotions like integer + float or boolean +
# integer are not allowed, even for functions that accept both kinds.
# Additionally, NumPy promotes signed integer + uint64 to float64, but this
# promotion is not allowed here. To be clear, Python scalar int objects are
# allowed to promote to floating-point dtypes, but only in array operators
# (see Array._promote_scalar) method in _array_object.py.
_promotion_table = {
(int8, int8): int8,
(int8, int16): int16,
(int8, int32): int32,
(int8, int64): int64,
(int16, int8): int16,
(int16, int16): int16,
(int16, int32): int32,
(int16, int64): int64,
(int32, int8): int32,
(int32, int16): int32,
(int32, int32): int32,
(int32, int64): int64,
(int64, int8): int64,
(int64, int16): int64,
(int64, int32): int64,
(int64, int64): int64,
(uint8, uint8): uint8,
(uint8, uint16): uint16,
(uint8, uint32): uint32,
(uint8, uint64): uint64,
(uint16, uint8): uint16,
(uint16, uint16): uint16,
(uint16, uint32): uint32,
(uint16, uint64): uint64,
(uint32, uint8): uint32,
(uint32, uint16): uint32,
(uint32, uint32): uint32,
(uint32, uint64): uint64,
(uint64, uint8): uint64,
(uint64, uint16): uint64,
(uint64, uint32): uint64,
(uint64, uint64): uint64,
(int8, uint8): int16,
(int8, uint16): int32,
(int8, uint32): int64,
(int16, uint8): int16,
(int16, uint16): int32,
(int16, uint32): int64,
(int32, uint8): int32,
(int32, uint16): int32,
(int32, uint32): int64,
(int64, uint8): int64,
(int64, uint16): int64,
(int64, uint32): int64,
(uint8, int8): int16,
(uint16, int8): int32,
(uint32, int8): int64,
(uint8, int16): int16,
(uint16, int16): int32,
(uint32, int16): int64,
(uint8, int32): int32,
(uint16, int32): int32,
(uint32, int32): int64,
(uint8, int64): int64,
(uint16, int64): int64,
(uint32, int64): int64,
(float32, float32): float32,
(float32, float64): float64,
(float64, float32): float64,
(float64, float64): float64,
(bool, bool): bool,
}
def _result_type(type1, type2):
if (type1, type2) in _promotion_table:
return _promotion_table[type1, type2]
raise TypeError(f"{type1} and {type2} cannot be type promoted together")

View File

@@ -0,0 +1,729 @@
from __future__ import annotations
from ._dtypes import (
_boolean_dtypes,
_floating_dtypes,
_integer_dtypes,
_integer_or_boolean_dtypes,
_numeric_dtypes,
_result_type,
)
from ._array_object import Array
import numpy as np
def abs(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.abs <numpy.abs>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in abs")
return Array._new(np.abs(x._array))
# Note: the function name is different here
def acos(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.arccos <numpy.arccos>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in acos")
return Array._new(np.arccos(x._array))
# Note: the function name is different here
def acosh(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.arccosh <numpy.arccosh>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in acosh")
return Array._new(np.arccosh(x._array))
def add(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.add <numpy.add>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in add")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.add(x1._array, x2._array))
# Note: the function name is different here
def asin(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.arcsin <numpy.arcsin>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in asin")
return Array._new(np.arcsin(x._array))
# Note: the function name is different here
def asinh(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.arcsinh <numpy.arcsinh>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in asinh")
return Array._new(np.arcsinh(x._array))
# Note: the function name is different here
def atan(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.arctan <numpy.arctan>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in atan")
return Array._new(np.arctan(x._array))
# Note: the function name is different here
def atan2(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.arctan2 <numpy.arctan2>`.
See its docstring for more information.
"""
if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in atan2")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.arctan2(x1._array, x2._array))
# Note: the function name is different here
def atanh(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.arctanh <numpy.arctanh>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in atanh")
return Array._new(np.arctanh(x._array))
def bitwise_and(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.bitwise_and <numpy.bitwise_and>`.
See its docstring for more information.
"""
if (
x1.dtype not in _integer_or_boolean_dtypes
or x2.dtype not in _integer_or_boolean_dtypes
):
raise TypeError("Only integer or boolean dtypes are allowed in bitwise_and")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.bitwise_and(x1._array, x2._array))
# Note: the function name is different here
def bitwise_left_shift(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.left_shift <numpy.left_shift>`.
See its docstring for more information.
"""
if x1.dtype not in _integer_dtypes or x2.dtype not in _integer_dtypes:
raise TypeError("Only integer dtypes are allowed in bitwise_left_shift")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
# Note: bitwise_left_shift is only defined for x2 nonnegative.
if np.any(x2._array < 0):
raise ValueError("bitwise_left_shift(x1, x2) is only defined for x2 >= 0")
return Array._new(np.left_shift(x1._array, x2._array))
# Note: the function name is different here
def bitwise_invert(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.invert <numpy.invert>`.
See its docstring for more information.
"""
if x.dtype not in _integer_or_boolean_dtypes:
raise TypeError("Only integer or boolean dtypes are allowed in bitwise_invert")
return Array._new(np.invert(x._array))
def bitwise_or(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.bitwise_or <numpy.bitwise_or>`.
See its docstring for more information.
"""
if (
x1.dtype not in _integer_or_boolean_dtypes
or x2.dtype not in _integer_or_boolean_dtypes
):
raise TypeError("Only integer or boolean dtypes are allowed in bitwise_or")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.bitwise_or(x1._array, x2._array))
# Note: the function name is different here
def bitwise_right_shift(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.right_shift <numpy.right_shift>`.
See its docstring for more information.
"""
if x1.dtype not in _integer_dtypes or x2.dtype not in _integer_dtypes:
raise TypeError("Only integer dtypes are allowed in bitwise_right_shift")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
# Note: bitwise_right_shift is only defined for x2 nonnegative.
if np.any(x2._array < 0):
raise ValueError("bitwise_right_shift(x1, x2) is only defined for x2 >= 0")
return Array._new(np.right_shift(x1._array, x2._array))
def bitwise_xor(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.bitwise_xor <numpy.bitwise_xor>`.
See its docstring for more information.
"""
if (
x1.dtype not in _integer_or_boolean_dtypes
or x2.dtype not in _integer_or_boolean_dtypes
):
raise TypeError("Only integer or boolean dtypes are allowed in bitwise_xor")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.bitwise_xor(x1._array, x2._array))
def ceil(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.ceil <numpy.ceil>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in ceil")
if x.dtype in _integer_dtypes:
# Note: The return dtype of ceil is the same as the input
return x
return Array._new(np.ceil(x._array))
def cos(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.cos <numpy.cos>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in cos")
return Array._new(np.cos(x._array))
def cosh(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.cosh <numpy.cosh>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in cosh")
return Array._new(np.cosh(x._array))
def divide(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.divide <numpy.divide>`.
See its docstring for more information.
"""
if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in divide")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.divide(x1._array, x2._array))
def equal(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.equal <numpy.equal>`.
See its docstring for more information.
"""
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.equal(x1._array, x2._array))
def exp(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.exp <numpy.exp>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in exp")
return Array._new(np.exp(x._array))
def expm1(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.expm1 <numpy.expm1>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in expm1")
return Array._new(np.expm1(x._array))
def floor(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.floor <numpy.floor>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in floor")
if x.dtype in _integer_dtypes:
# Note: The return dtype of floor is the same as the input
return x
return Array._new(np.floor(x._array))
def floor_divide(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.floor_divide <numpy.floor_divide>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in floor_divide")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.floor_divide(x1._array, x2._array))
def greater(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.greater <numpy.greater>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in greater")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.greater(x1._array, x2._array))
def greater_equal(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.greater_equal <numpy.greater_equal>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in greater_equal")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.greater_equal(x1._array, x2._array))
def isfinite(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.isfinite <numpy.isfinite>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in isfinite")
return Array._new(np.isfinite(x._array))
def isinf(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.isinf <numpy.isinf>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in isinf")
return Array._new(np.isinf(x._array))
def isnan(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.isnan <numpy.isnan>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in isnan")
return Array._new(np.isnan(x._array))
def less(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.less <numpy.less>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in less")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.less(x1._array, x2._array))
def less_equal(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.less_equal <numpy.less_equal>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in less_equal")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.less_equal(x1._array, x2._array))
def log(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.log <numpy.log>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in log")
return Array._new(np.log(x._array))
def log1p(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.log1p <numpy.log1p>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in log1p")
return Array._new(np.log1p(x._array))
def log2(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.log2 <numpy.log2>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in log2")
return Array._new(np.log2(x._array))
def log10(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.log10 <numpy.log10>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in log10")
return Array._new(np.log10(x._array))
def logaddexp(x1: Array, x2: Array) -> Array:
"""
Array API compatible wrapper for :py:func:`np.logaddexp <numpy.logaddexp>`.
See its docstring for more information.
"""
if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in logaddexp")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.logaddexp(x1._array, x2._array))
def logical_and(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.logical_and <numpy.logical_and>`.
See its docstring for more information.
"""
if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes:
raise TypeError("Only boolean dtypes are allowed in logical_and")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.logical_and(x1._array, x2._array))
def logical_not(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.logical_not <numpy.logical_not>`.
See its docstring for more information.
"""
if x.dtype not in _boolean_dtypes:
raise TypeError("Only boolean dtypes are allowed in logical_not")
return Array._new(np.logical_not(x._array))
def logical_or(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.logical_or <numpy.logical_or>`.
See its docstring for more information.
"""
if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes:
raise TypeError("Only boolean dtypes are allowed in logical_or")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.logical_or(x1._array, x2._array))
def logical_xor(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.logical_xor <numpy.logical_xor>`.
See its docstring for more information.
"""
if x1.dtype not in _boolean_dtypes or x2.dtype not in _boolean_dtypes:
raise TypeError("Only boolean dtypes are allowed in logical_xor")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.logical_xor(x1._array, x2._array))
def multiply(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.multiply <numpy.multiply>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in multiply")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.multiply(x1._array, x2._array))
def negative(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.negative <numpy.negative>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in negative")
return Array._new(np.negative(x._array))
def not_equal(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.not_equal <numpy.not_equal>`.
See its docstring for more information.
"""
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.not_equal(x1._array, x2._array))
def positive(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.positive <numpy.positive>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in positive")
return Array._new(np.positive(x._array))
# Note: the function name is different here
def pow(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.power <numpy.power>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in pow")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.power(x1._array, x2._array))
def remainder(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.remainder <numpy.remainder>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in remainder")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.remainder(x1._array, x2._array))
def round(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.round <numpy.round>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in round")
return Array._new(np.round(x._array))
def sign(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.sign <numpy.sign>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in sign")
return Array._new(np.sign(x._array))
def sin(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.sin <numpy.sin>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in sin")
return Array._new(np.sin(x._array))
def sinh(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.sinh <numpy.sinh>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in sinh")
return Array._new(np.sinh(x._array))
def square(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.square <numpy.square>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in square")
return Array._new(np.square(x._array))
def sqrt(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.sqrt <numpy.sqrt>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in sqrt")
return Array._new(np.sqrt(x._array))
def subtract(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.subtract <numpy.subtract>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in subtract")
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.subtract(x1._array, x2._array))
def tan(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.tan <numpy.tan>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in tan")
return Array._new(np.tan(x._array))
def tanh(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.tanh <numpy.tanh>`.
See its docstring for more information.
"""
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in tanh")
return Array._new(np.tanh(x._array))
def trunc(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.trunc <numpy.trunc>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in trunc")
if x.dtype in _integer_dtypes:
# Note: The return dtype of trunc is the same as the input
return x
return Array._new(np.trunc(x._array))

View File

@@ -0,0 +1,98 @@
from __future__ import annotations
from ._array_object import Array
from ._data_type_functions import result_type
from typing import List, Optional, Tuple, Union
import numpy as np
# Note: the function name is different here
def concat(
arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: Optional[int] = 0
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.concatenate <numpy.concatenate>`.
See its docstring for more information.
"""
# Note: Casting rules here are different from the np.concatenate default
# (no for scalars with axis=None, no cross-kind casting)
dtype = result_type(*arrays)
arrays = tuple(a._array for a in arrays)
return Array._new(np.concatenate(arrays, axis=axis, dtype=dtype))
def expand_dims(x: Array, /, *, axis: int) -> Array:
"""
Array API compatible wrapper for :py:func:`np.expand_dims <numpy.expand_dims>`.
See its docstring for more information.
"""
return Array._new(np.expand_dims(x._array, axis))
def flip(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None) -> Array:
"""
Array API compatible wrapper for :py:func:`np.flip <numpy.flip>`.
See its docstring for more information.
"""
return Array._new(np.flip(x._array, axis=axis))
# Note: The function name is different here (see also matrix_transpose).
# Unlike transpose(), the axes argument is required.
def permute_dims(x: Array, /, axes: Tuple[int, ...]) -> Array:
"""
Array API compatible wrapper for :py:func:`np.transpose <numpy.transpose>`.
See its docstring for more information.
"""
return Array._new(np.transpose(x._array, axes))
# Note: the optional argument is called 'shape', not 'newshape'
def reshape(x: Array, /, shape: Tuple[int, ...]) -> Array:
"""
Array API compatible wrapper for :py:func:`np.reshape <numpy.reshape>`.
See its docstring for more information.
"""
return Array._new(np.reshape(x._array, shape))
def roll(
x: Array,
/,
shift: Union[int, Tuple[int, ...]],
*,
axis: Optional[Union[int, Tuple[int, ...]]] = None,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.roll <numpy.roll>`.
See its docstring for more information.
"""
return Array._new(np.roll(x._array, shift, axis=axis))
def squeeze(x: Array, /, axis: Union[int, Tuple[int, ...]]) -> Array:
"""
Array API compatible wrapper for :py:func:`np.squeeze <numpy.squeeze>`.
See its docstring for more information.
"""
return Array._new(np.squeeze(x._array, axis=axis))
def stack(arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: int = 0) -> Array:
"""
Array API compatible wrapper for :py:func:`np.stack <numpy.stack>`.
See its docstring for more information.
"""
# Call result type here just to raise on disallowed type combinations
result_type(*arrays)
arrays = tuple(a._array for a in arrays)
return Array._new(np.stack(arrays, axis=axis))

View File

@@ -0,0 +1,47 @@
from __future__ import annotations
from ._array_object import Array
from ._dtypes import _result_type
from typing import Optional, Tuple
import numpy as np
def argmax(x: Array, /, *, axis: Optional[int] = None, keepdims: bool = False) -> Array:
"""
Array API compatible wrapper for :py:func:`np.argmax <numpy.argmax>`.
See its docstring for more information.
"""
return Array._new(np.asarray(np.argmax(x._array, axis=axis, keepdims=keepdims)))
def argmin(x: Array, /, *, axis: Optional[int] = None, keepdims: bool = False) -> Array:
"""
Array API compatible wrapper for :py:func:`np.argmin <numpy.argmin>`.
See its docstring for more information.
"""
return Array._new(np.asarray(np.argmin(x._array, axis=axis, keepdims=keepdims)))
def nonzero(x: Array, /) -> Tuple[Array, ...]:
"""
Array API compatible wrapper for :py:func:`np.nonzero <numpy.nonzero>`.
See its docstring for more information.
"""
return tuple(Array._new(i) for i in np.nonzero(x._array))
def where(condition: Array, x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.where <numpy.where>`.
See its docstring for more information.
"""
# Call result type here just to raise on disallowed type combinations
_result_type(x1.dtype, x2.dtype)
x1, x2 = Array._normalize_two_args(x1, x2)
return Array._new(np.where(condition._array, x1._array, x2._array))

View File

@@ -0,0 +1,106 @@
from __future__ import annotations
from ._array_object import Array
from typing import NamedTuple
import numpy as np
# Note: np.unique() is split into four functions in the array API:
# unique_all, unique_counts, unique_inverse, and unique_values (this is done
# to remove polymorphic return types).
# Note: The various unique() functions are supposed to return multiple NaNs.
# This does not match the NumPy behavior, however, this is currently left as a
# TODO in this implementation as this behavior may be reverted in np.unique().
# See https://github.com/numpy/numpy/issues/20326.
# Note: The functions here return a namedtuple (np.unique() returns a normal
# tuple).
class UniqueAllResult(NamedTuple):
values: Array
indices: Array
inverse_indices: Array
counts: Array
class UniqueCountsResult(NamedTuple):
values: Array
counts: Array
class UniqueInverseResult(NamedTuple):
values: Array
inverse_indices: Array
def unique_all(x: Array, /) -> UniqueAllResult:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
values, indices, inverse_indices, counts = np.unique(
x._array,
return_counts=True,
return_index=True,
return_inverse=True,
equal_nan=False,
)
# np.unique() flattens inverse indices, but they need to share x's shape
# See https://github.com/numpy/numpy/issues/20638
inverse_indices = inverse_indices.reshape(x.shape)
return UniqueAllResult(
Array._new(values),
Array._new(indices),
Array._new(inverse_indices),
Array._new(counts),
)
def unique_counts(x: Array, /) -> UniqueCountsResult:
res = np.unique(
x._array,
return_counts=True,
return_index=False,
return_inverse=False,
equal_nan=False,
)
return UniqueCountsResult(*[Array._new(i) for i in res])
def unique_inverse(x: Array, /) -> UniqueInverseResult:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
values, inverse_indices = np.unique(
x._array,
return_counts=False,
return_index=False,
return_inverse=True,
equal_nan=False,
)
# np.unique() flattens inverse indices, but they need to share x's shape
# See https://github.com/numpy/numpy/issues/20638
inverse_indices = inverse_indices.reshape(x.shape)
return UniqueInverseResult(Array._new(values), Array._new(inverse_indices))
def unique_values(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.unique <numpy.unique>`.
See its docstring for more information.
"""
res = np.unique(
x._array,
return_counts=False,
return_index=False,
return_inverse=False,
equal_nan=False,
)
return Array._new(res)

View File

@@ -0,0 +1,49 @@
from __future__ import annotations
from ._array_object import Array
import numpy as np
# Note: the descending keyword argument is new in this function
def argsort(
x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.argsort <numpy.argsort>`.
See its docstring for more information.
"""
# Note: this keyword argument is different, and the default is different.
kind = "stable" if stable else "quicksort"
if not descending:
res = np.argsort(x._array, axis=axis, kind=kind)
else:
# As NumPy has no native descending sort, we imitate it here. Note that
# simply flipping the results of np.argsort(x._array, ...) would not
# respect the relative order like it would in native descending sorts.
res = np.flip(
np.argsort(np.flip(x._array, axis=axis), axis=axis, kind=kind),
axis=axis,
)
# Rely on flip()/argsort() to validate axis
normalised_axis = axis if axis >= 0 else x.ndim + axis
max_i = x.shape[normalised_axis] - 1
res = max_i - res
return Array._new(res)
# Note: the descending keyword argument is new in this function
def sort(
x: Array, /, *, axis: int = -1, descending: bool = False, stable: bool = True
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.sort <numpy.sort>`.
See its docstring for more information.
"""
# Note: this keyword argument is different, and the default is different.
kind = "stable" if stable else "quicksort"
res = np.sort(x._array, axis=axis, kind=kind)
if descending:
res = np.flip(res, axis=axis)
return Array._new(res)

View File

@@ -0,0 +1,115 @@
from __future__ import annotations
from ._dtypes import (
_floating_dtypes,
_numeric_dtypes,
)
from ._array_object import Array
from ._creation_functions import asarray
from ._dtypes import float32, float64
from typing import TYPE_CHECKING, Optional, Tuple, Union
if TYPE_CHECKING:
from ._typing import Dtype
import numpy as np
def max(
x: Array,
/,
*,
axis: Optional[Union[int, Tuple[int, ...]]] = None,
keepdims: bool = False,
) -> Array:
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in max")
return Array._new(np.max(x._array, axis=axis, keepdims=keepdims))
def mean(
x: Array,
/,
*,
axis: Optional[Union[int, Tuple[int, ...]]] = None,
keepdims: bool = False,
) -> Array:
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in mean")
return Array._new(np.mean(x._array, axis=axis, keepdims=keepdims))
def min(
x: Array,
/,
*,
axis: Optional[Union[int, Tuple[int, ...]]] = None,
keepdims: bool = False,
) -> Array:
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in min")
return Array._new(np.min(x._array, axis=axis, keepdims=keepdims))
def prod(
x: Array,
/,
*,
axis: Optional[Union[int, Tuple[int, ...]]] = None,
dtype: Optional[Dtype] = None,
keepdims: bool = False,
) -> Array:
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in prod")
# Note: sum() and prod() always upcast float32 to float64 for dtype=None
# We need to do so here before computing the product to avoid overflow
if dtype is None and x.dtype == float32:
dtype = float64
return Array._new(np.prod(x._array, dtype=dtype, axis=axis, keepdims=keepdims))
def std(
x: Array,
/,
*,
axis: Optional[Union[int, Tuple[int, ...]]] = None,
correction: Union[int, float] = 0.0,
keepdims: bool = False,
) -> Array:
# Note: the keyword argument correction is different here
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in std")
return Array._new(np.std(x._array, axis=axis, ddof=correction, keepdims=keepdims))
def sum(
x: Array,
/,
*,
axis: Optional[Union[int, Tuple[int, ...]]] = None,
dtype: Optional[Dtype] = None,
keepdims: bool = False,
) -> Array:
if x.dtype not in _numeric_dtypes:
raise TypeError("Only numeric dtypes are allowed in sum")
# Note: sum() and prod() always upcast integers to (u)int64 and float32 to
# float64 for dtype=None. `np.sum` does that too for integers, but not for
# float32, so we need to special-case it here
if dtype is None and x.dtype == float32:
dtype = float64
return Array._new(np.sum(x._array, axis=axis, dtype=dtype, keepdims=keepdims))
def var(
x: Array,
/,
*,
axis: Optional[Union[int, Tuple[int, ...]]] = None,
correction: Union[int, float] = 0.0,
keepdims: bool = False,
) -> Array:
# Note: the keyword argument correction is different here
if x.dtype not in _floating_dtypes:
raise TypeError("Only floating-point dtypes are allowed in var")
return Array._new(np.var(x._array, axis=axis, ddof=correction, keepdims=keepdims))

View File

@@ -0,0 +1,74 @@
"""
This file defines the types for type annotations.
These names aren't part of the module namespace, but they are used in the
annotations in the function signatures. The functions in the module are only
valid for inputs that match the given type annotations.
"""
from __future__ import annotations
__all__ = [
"Array",
"Device",
"Dtype",
"SupportsDLPack",
"SupportsBufferProtocol",
"PyCapsule",
]
import sys
from typing import (
Any,
Literal,
Sequence,
Type,
Union,
TYPE_CHECKING,
TypeVar,
Protocol,
)
from ._array_object import Array
from numpy import (
dtype,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
)
_T_co = TypeVar("_T_co", covariant=True)
class NestedSequence(Protocol[_T_co]):
def __getitem__(self, key: int, /) -> _T_co | NestedSequence[_T_co]: ...
def __len__(self, /) -> int: ...
Device = Literal["cpu"]
if TYPE_CHECKING or sys.version_info >= (3, 9):
Dtype = dtype[Union[
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
]]
else:
Dtype = dtype
SupportsBufferProtocol = Any
PyCapsule = Any
class SupportsDLPack(Protocol):
def __dlpack__(self, /, *, stream: None = ...) -> PyCapsule: ...

View File

@@ -0,0 +1,37 @@
from __future__ import annotations
from ._array_object import Array
from typing import Optional, Tuple, Union
import numpy as np
def all(
x: Array,
/,
*,
axis: Optional[Union[int, Tuple[int, ...]]] = None,
keepdims: bool = False,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.all <numpy.all>`.
See its docstring for more information.
"""
return Array._new(np.asarray(np.all(x._array, axis=axis, keepdims=keepdims)))
def any(
x: Array,
/,
*,
axis: Optional[Union[int, Tuple[int, ...]]] = None,
keepdims: bool = False,
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.any <numpy.any>`.
See its docstring for more information.
"""
return Array._new(np.asarray(np.any(x._array, axis=axis, keepdims=keepdims)))

View File

@@ -0,0 +1,446 @@
from __future__ import annotations
from ._dtypes import _floating_dtypes, _numeric_dtypes
from ._manipulation_functions import reshape
from ._array_object import Array
from ..core.numeric import normalize_axis_tuple
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ._typing import Literal, Optional, Sequence, Tuple, Union
from typing import NamedTuple
import numpy.linalg
import numpy as np
class EighResult(NamedTuple):
eigenvalues: Array
eigenvectors: Array
class QRResult(NamedTuple):
Q: Array
R: Array
class SlogdetResult(NamedTuple):
sign: Array
logabsdet: Array
class SVDResult(NamedTuple):
U: Array
S: Array
Vh: Array
# Note: the inclusion of the upper keyword is different from
# np.linalg.cholesky, which does not have it.
def cholesky(x: Array, /, *, upper: bool = False) -> Array:
"""
Array API compatible wrapper for :py:func:`np.linalg.cholesky <numpy.linalg.cholesky>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.cholesky.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in cholesky')
L = np.linalg.cholesky(x._array)
if upper:
return Array._new(L).mT
return Array._new(L)
# Note: cross is the numpy top-level namespace, not np.linalg
def cross(x1: Array, x2: Array, /, *, axis: int = -1) -> Array:
"""
Array API compatible wrapper for :py:func:`np.cross <numpy.cross>`.
See its docstring for more information.
"""
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError('Only numeric dtypes are allowed in cross')
# Note: this is different from np.cross(), which broadcasts
if x1.shape != x2.shape:
raise ValueError('x1 and x2 must have the same shape')
if x1.ndim == 0:
raise ValueError('cross() requires arrays of dimension at least 1')
# Note: this is different from np.cross(), which allows dimension 2
if x1.shape[axis] != 3:
raise ValueError('cross() dimension must equal 3')
return Array._new(np.cross(x1._array, x2._array, axis=axis))
def det(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.linalg.det <numpy.linalg.det>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.det.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in det')
return Array._new(np.linalg.det(x._array))
# Note: diagonal is the numpy top-level namespace, not np.linalg
def diagonal(x: Array, /, *, offset: int = 0) -> Array:
"""
Array API compatible wrapper for :py:func:`np.diagonal <numpy.diagonal>`.
See its docstring for more information.
"""
# Note: diagonal always operates on the last two axes, whereas np.diagonal
# operates on the first two axes by default
return Array._new(np.diagonal(x._array, offset=offset, axis1=-2, axis2=-1))
def eigh(x: Array, /) -> EighResult:
"""
Array API compatible wrapper for :py:func:`np.linalg.eigh <numpy.linalg.eigh>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.eigh.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in eigh')
# Note: the return type here is a namedtuple, which is different from
# np.eigh, which only returns a tuple.
return EighResult(*map(Array._new, np.linalg.eigh(x._array)))
def eigvalsh(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.linalg.eigvalsh <numpy.linalg.eigvalsh>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.eigvalsh.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in eigvalsh')
return Array._new(np.linalg.eigvalsh(x._array))
def inv(x: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.linalg.inv <numpy.linalg.inv>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.inv.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in inv')
return Array._new(np.linalg.inv(x._array))
# Note: matmul is the numpy top-level namespace but not in np.linalg
def matmul(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.matmul <numpy.matmul>`.
See its docstring for more information.
"""
# Note: the restriction to numeric dtypes only is different from
# np.matmul.
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError('Only numeric dtypes are allowed in matmul')
return Array._new(np.matmul(x1._array, x2._array))
# Note: the name here is different from norm(). The array API norm is split
# into matrix_norm and vector_norm().
# The type for ord should be Optional[Union[int, float, Literal[np.inf,
# -np.inf, 'fro', 'nuc']]], but Literal does not support floating-point
# literals.
def matrix_norm(x: Array, /, *, keepdims: bool = False, ord: Optional[Union[int, float, Literal['fro', 'nuc']]] = 'fro') -> Array:
"""
Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.norm.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in matrix_norm')
return Array._new(np.linalg.norm(x._array, axis=(-2, -1), keepdims=keepdims, ord=ord))
def matrix_power(x: Array, n: int, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.matrix_power <numpy.matrix_power>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.matrix_power.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed for the first argument of matrix_power')
# np.matrix_power already checks if n is an integer
return Array._new(np.linalg.matrix_power(x._array, n))
# Note: the keyword argument name rtol is different from np.linalg.matrix_rank
def matrix_rank(x: Array, /, *, rtol: Optional[Union[float, Array]] = None) -> Array:
"""
Array API compatible wrapper for :py:func:`np.matrix_rank <numpy.matrix_rank>`.
See its docstring for more information.
"""
# Note: this is different from np.linalg.matrix_rank, which supports 1
# dimensional arrays.
if x.ndim < 2:
raise np.linalg.LinAlgError("1-dimensional array given. Array must be at least two-dimensional")
S = np.linalg.svd(x._array, compute_uv=False)
if rtol is None:
tol = S.max(axis=-1, keepdims=True) * max(x.shape[-2:]) * np.finfo(S.dtype).eps
else:
if isinstance(rtol, Array):
rtol = rtol._array
# Note: this is different from np.linalg.matrix_rank, which does not multiply
# the tolerance by the largest singular value.
tol = S.max(axis=-1, keepdims=True)*np.asarray(rtol)[..., np.newaxis]
return Array._new(np.count_nonzero(S > tol, axis=-1))
# Note: this function is new in the array API spec. Unlike transpose, it only
# transposes the last two axes.
def matrix_transpose(x: Array, /) -> Array:
if x.ndim < 2:
raise ValueError("x must be at least 2-dimensional for matrix_transpose")
return Array._new(np.swapaxes(x._array, -1, -2))
# Note: outer is the numpy top-level namespace, not np.linalg
def outer(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.outer <numpy.outer>`.
See its docstring for more information.
"""
# Note: the restriction to numeric dtypes only is different from
# np.outer.
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError('Only numeric dtypes are allowed in outer')
# Note: the restriction to only 1-dim arrays is different from np.outer
if x1.ndim != 1 or x2.ndim != 1:
raise ValueError('The input arrays to outer must be 1-dimensional')
return Array._new(np.outer(x1._array, x2._array))
# Note: the keyword argument name rtol is different from np.linalg.pinv
def pinv(x: Array, /, *, rtol: Optional[Union[float, Array]] = None) -> Array:
"""
Array API compatible wrapper for :py:func:`np.linalg.pinv <numpy.linalg.pinv>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.pinv.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in pinv')
# Note: this is different from np.linalg.pinv, which does not multiply the
# default tolerance by max(M, N).
if rtol is None:
rtol = max(x.shape[-2:]) * np.finfo(x.dtype).eps
return Array._new(np.linalg.pinv(x._array, rcond=rtol))
def qr(x: Array, /, *, mode: Literal['reduced', 'complete'] = 'reduced') -> QRResult:
"""
Array API compatible wrapper for :py:func:`np.linalg.qr <numpy.linalg.qr>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.qr.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in qr')
# Note: the return type here is a namedtuple, which is different from
# np.linalg.qr, which only returns a tuple.
return QRResult(*map(Array._new, np.linalg.qr(x._array, mode=mode)))
def slogdet(x: Array, /) -> SlogdetResult:
"""
Array API compatible wrapper for :py:func:`np.linalg.slogdet <numpy.linalg.slogdet>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.slogdet.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in slogdet')
# Note: the return type here is a namedtuple, which is different from
# np.linalg.slogdet, which only returns a tuple.
return SlogdetResult(*map(Array._new, np.linalg.slogdet(x._array)))
# Note: unlike np.linalg.solve, the array API solve() only accepts x2 as a
# vector when it is exactly 1-dimensional. All other cases treat x2 as a stack
# of matrices. The np.linalg.solve behavior of allowing stacks of both
# matrices and vectors is ambiguous c.f.
# https://github.com/numpy/numpy/issues/15349 and
# https://github.com/data-apis/array-api/issues/285.
# To workaround this, the below is the code from np.linalg.solve except
# only calling solve1 in the exactly 1D case.
def _solve(a, b):
from ..linalg.linalg import (_makearray, _assert_stacked_2d,
_assert_stacked_square, _commonType,
isComplexType, get_linalg_error_extobj,
_raise_linalgerror_singular)
from ..linalg import _umath_linalg
a, _ = _makearray(a)
_assert_stacked_2d(a)
_assert_stacked_square(a)
b, wrap = _makearray(b)
t, result_t = _commonType(a, b)
# This part is different from np.linalg.solve
if b.ndim == 1:
gufunc = _umath_linalg.solve1
else:
gufunc = _umath_linalg.solve
# This does nothing currently but is left in because it will be relevant
# when complex dtype support is added to the spec in 2022.
signature = 'DD->D' if isComplexType(t) else 'dd->d'
extobj = get_linalg_error_extobj(_raise_linalgerror_singular)
r = gufunc(a, b, signature=signature, extobj=extobj)
return wrap(r.astype(result_t, copy=False))
def solve(x1: Array, x2: Array, /) -> Array:
"""
Array API compatible wrapper for :py:func:`np.linalg.solve <numpy.linalg.solve>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.solve.
if x1.dtype not in _floating_dtypes or x2.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in solve')
return Array._new(_solve(x1._array, x2._array))
def svd(x: Array, /, *, full_matrices: bool = True) -> SVDResult:
"""
Array API compatible wrapper for :py:func:`np.linalg.svd <numpy.linalg.svd>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.svd.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in svd')
# Note: the return type here is a namedtuple, which is different from
# np.svd, which only returns a tuple.
return SVDResult(*map(Array._new, np.linalg.svd(x._array, full_matrices=full_matrices)))
# Note: svdvals is not in NumPy (but it is in SciPy). It is equivalent to
# np.linalg.svd(compute_uv=False).
def svdvals(x: Array, /) -> Union[Array, Tuple[Array, ...]]:
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in svdvals')
return Array._new(np.linalg.svd(x._array, compute_uv=False))
# Note: tensordot is the numpy top-level namespace but not in np.linalg
# Note: axes must be a tuple, unlike np.tensordot where it can be an array or array-like.
def tensordot(x1: Array, x2: Array, /, *, axes: Union[int, Tuple[Sequence[int], Sequence[int]]] = 2) -> Array:
# Note: the restriction to numeric dtypes only is different from
# np.tensordot.
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError('Only numeric dtypes are allowed in tensordot')
return Array._new(np.tensordot(x1._array, x2._array, axes=axes))
# Note: trace is the numpy top-level namespace, not np.linalg
def trace(x: Array, /, *, offset: int = 0) -> Array:
"""
Array API compatible wrapper for :py:func:`np.trace <numpy.trace>`.
See its docstring for more information.
"""
if x.dtype not in _numeric_dtypes:
raise TypeError('Only numeric dtypes are allowed in trace')
# Note: trace always operates on the last two axes, whereas np.trace
# operates on the first two axes by default
return Array._new(np.asarray(np.trace(x._array, offset=offset, axis1=-2, axis2=-1)))
# Note: vecdot is not in NumPy
def vecdot(x1: Array, x2: Array, /, *, axis: int = -1) -> Array:
if x1.dtype not in _numeric_dtypes or x2.dtype not in _numeric_dtypes:
raise TypeError('Only numeric dtypes are allowed in vecdot')
ndim = max(x1.ndim, x2.ndim)
x1_shape = (1,)*(ndim - x1.ndim) + tuple(x1.shape)
x2_shape = (1,)*(ndim - x2.ndim) + tuple(x2.shape)
if x1_shape[axis] != x2_shape[axis]:
raise ValueError("x1 and x2 must have the same size along the given axis")
x1_, x2_ = np.broadcast_arrays(x1._array, x2._array)
x1_ = np.moveaxis(x1_, axis, -1)
x2_ = np.moveaxis(x2_, axis, -1)
res = x1_[..., None, :] @ x2_[..., None]
return Array._new(res[..., 0, 0])
# Note: the name here is different from norm(). The array API norm is split
# into matrix_norm and vector_norm().
# The type for ord should be Optional[Union[int, float, Literal[np.inf,
# -np.inf]]] but Literal does not support floating-point literals.
def vector_norm(x: Array, /, *, axis: Optional[Union[int, Tuple[int, ...]]] = None, keepdims: bool = False, ord: Optional[Union[int, float]] = 2) -> Array:
"""
Array API compatible wrapper for :py:func:`np.linalg.norm <numpy.linalg.norm>`.
See its docstring for more information.
"""
# Note: the restriction to floating-point dtypes only is different from
# np.linalg.norm.
if x.dtype not in _floating_dtypes:
raise TypeError('Only floating-point dtypes are allowed in norm')
# np.linalg.norm tries to do a matrix norm whenever axis is a 2-tuple or
# when axis=None and the input is 2-D, so to force a vector norm, we make
# it so the input is 1-D (for axis=None), or reshape so that norm is done
# on a single dimension.
a = x._array
if axis is None:
# Note: np.linalg.norm() doesn't handle 0-D arrays
a = a.ravel()
_axis = 0
elif isinstance(axis, tuple):
# Note: The axis argument supports any number of axes, whereas
# np.linalg.norm() only supports a single axis for vector norm.
normalized_axis = normalize_axis_tuple(axis, x.ndim)
rest = tuple(i for i in range(a.ndim) if i not in normalized_axis)
newshape = axis + rest
a = np.transpose(a, newshape).reshape(
(np.prod([a.shape[i] for i in axis], dtype=int), *[a.shape[i] for i in rest]))
_axis = 0
else:
_axis = axis
res = Array._new(np.linalg.norm(a, axis=_axis, ord=ord))
if keepdims:
# We can't reuse np.linalg.norm(keepdims) because of the reshape hacks
# above to avoid matrix norm logic.
shape = list(x.shape)
_axis = normalize_axis_tuple(range(x.ndim) if axis is None else axis, x.ndim)
for i in _axis:
shape[i] = 1
res = reshape(res, tuple(shape))
return res
__all__ = ['cholesky', 'cross', 'det', 'diagonal', 'eigh', 'eigvalsh', 'inv', 'matmul', 'matrix_norm', 'matrix_power', 'matrix_rank', 'matrix_transpose', 'outer', 'pinv', 'qr', 'slogdet', 'solve', 'svd', 'svdvals', 'tensordot', 'trace', 'vecdot', 'vector_norm']

View File

@@ -0,0 +1,12 @@
def configuration(parent_package="", top_path=None):
from numpy.distutils.misc_util import Configuration
config = Configuration("array_api", parent_package, top_path)
config.add_subpackage("tests")
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(configuration=configuration)

View File

@@ -0,0 +1,7 @@
"""
Tests for the array API namespace.
Note, full compliance with the array API can be tested with the official array API test
suite https://github.com/data-apis/array-api-tests. This test suite primarily
focuses on those things that are not tested by the official test suite.
"""

View File

@@ -0,0 +1,375 @@
import operator
from numpy.testing import assert_raises
import numpy as np
import pytest
from .. import ones, asarray, reshape, result_type, all, equal
from .._array_object import Array
from .._dtypes import (
_all_dtypes,
_boolean_dtypes,
_floating_dtypes,
_integer_dtypes,
_integer_or_boolean_dtypes,
_numeric_dtypes,
int8,
int16,
int32,
int64,
uint64,
bool as bool_,
)
def test_validate_index():
# The indexing tests in the official array API test suite test that the
# array object correctly handles the subset of indices that are required
# by the spec. But the NumPy array API implementation specifically
# disallows any index not required by the spec, via Array._validate_index.
# This test focuses on testing that non-valid indices are correctly
# rejected. See
# https://data-apis.org/array-api/latest/API_specification/indexing.html
# and the docstring of Array._validate_index for the exact indexing
# behavior that should be allowed. This does not test indices that are
# already invalid in NumPy itself because Array will generally just pass
# such indices directly to the underlying np.ndarray.
a = ones((3, 4))
# Out of bounds slices are not allowed
assert_raises(IndexError, lambda: a[:4])
assert_raises(IndexError, lambda: a[:-4])
assert_raises(IndexError, lambda: a[:3:-1])
assert_raises(IndexError, lambda: a[:-5:-1])
assert_raises(IndexError, lambda: a[4:])
assert_raises(IndexError, lambda: a[-4:])
assert_raises(IndexError, lambda: a[4::-1])
assert_raises(IndexError, lambda: a[-4::-1])
assert_raises(IndexError, lambda: a[...,:5])
assert_raises(IndexError, lambda: a[...,:-5])
assert_raises(IndexError, lambda: a[...,:5:-1])
assert_raises(IndexError, lambda: a[...,:-6:-1])
assert_raises(IndexError, lambda: a[...,5:])
assert_raises(IndexError, lambda: a[...,-5:])
assert_raises(IndexError, lambda: a[...,5::-1])
assert_raises(IndexError, lambda: a[...,-5::-1])
# Boolean indices cannot be part of a larger tuple index
assert_raises(IndexError, lambda: a[a[:,0]==1,0])
assert_raises(IndexError, lambda: a[a[:,0]==1,...])
assert_raises(IndexError, lambda: a[..., a[0]==1])
assert_raises(IndexError, lambda: a[[True, True, True]])
assert_raises(IndexError, lambda: a[(True, True, True),])
# Integer array indices are not allowed (except for 0-D)
idx = asarray([[0, 1]])
assert_raises(IndexError, lambda: a[idx])
assert_raises(IndexError, lambda: a[idx,])
assert_raises(IndexError, lambda: a[[0, 1]])
assert_raises(IndexError, lambda: a[(0, 1), (0, 1)])
assert_raises(IndexError, lambda: a[[0, 1]])
assert_raises(IndexError, lambda: a[np.array([[0, 1]])])
# Multiaxis indices must contain exactly as many indices as dimensions
assert_raises(IndexError, lambda: a[()])
assert_raises(IndexError, lambda: a[0,])
assert_raises(IndexError, lambda: a[0])
assert_raises(IndexError, lambda: a[:])
def test_operators():
# For every operator, we test that it works for the required type
# combinations and raises TypeError otherwise
binary_op_dtypes = {
"__add__": "numeric",
"__and__": "integer_or_boolean",
"__eq__": "all",
"__floordiv__": "numeric",
"__ge__": "numeric",
"__gt__": "numeric",
"__le__": "numeric",
"__lshift__": "integer",
"__lt__": "numeric",
"__mod__": "numeric",
"__mul__": "numeric",
"__ne__": "all",
"__or__": "integer_or_boolean",
"__pow__": "numeric",
"__rshift__": "integer",
"__sub__": "numeric",
"__truediv__": "floating",
"__xor__": "integer_or_boolean",
}
# Recompute each time because of in-place ops
def _array_vals():
for d in _integer_dtypes:
yield asarray(1, dtype=d)
for d in _boolean_dtypes:
yield asarray(False, dtype=d)
for d in _floating_dtypes:
yield asarray(1.0, dtype=d)
for op, dtypes in binary_op_dtypes.items():
ops = [op]
if op not in ["__eq__", "__ne__", "__le__", "__ge__", "__lt__", "__gt__"]:
rop = "__r" + op[2:]
iop = "__i" + op[2:]
ops += [rop, iop]
for s in [1, 1.0, False]:
for _op in ops:
for a in _array_vals():
# Test array op scalar. From the spec, the following combinations
# are supported:
# - Python bool for a bool array dtype,
# - a Python int within the bounds of the given dtype for integer array dtypes,
# - a Python int or float for floating-point array dtypes
# We do not do bounds checking for int scalars, but rather use the default
# NumPy behavior for casting in that case.
if ((dtypes == "all"
or dtypes == "numeric" and a.dtype in _numeric_dtypes
or dtypes == "integer" and a.dtype in _integer_dtypes
or dtypes == "integer_or_boolean" and a.dtype in _integer_or_boolean_dtypes
or dtypes == "boolean" and a.dtype in _boolean_dtypes
or dtypes == "floating" and a.dtype in _floating_dtypes
)
# bool is a subtype of int, which is why we avoid
# isinstance here.
and (a.dtype in _boolean_dtypes and type(s) == bool
or a.dtype in _integer_dtypes and type(s) == int
or a.dtype in _floating_dtypes and type(s) in [float, int]
)):
# Only test for no error
getattr(a, _op)(s)
else:
assert_raises(TypeError, lambda: getattr(a, _op)(s))
# Test array op array.
for _op in ops:
for x in _array_vals():
for y in _array_vals():
# See the promotion table in NEP 47 or the array
# API spec page on type promotion. Mixed kind
# promotion is not defined.
if (x.dtype == uint64 and y.dtype in [int8, int16, int32, int64]
or y.dtype == uint64 and x.dtype in [int8, int16, int32, int64]
or x.dtype in _integer_dtypes and y.dtype not in _integer_dtypes
or y.dtype in _integer_dtypes and x.dtype not in _integer_dtypes
or x.dtype in _boolean_dtypes and y.dtype not in _boolean_dtypes
or y.dtype in _boolean_dtypes and x.dtype not in _boolean_dtypes
or x.dtype in _floating_dtypes and y.dtype not in _floating_dtypes
or y.dtype in _floating_dtypes and x.dtype not in _floating_dtypes
):
assert_raises(TypeError, lambda: getattr(x, _op)(y))
# Ensure in-place operators only promote to the same dtype as the left operand.
elif (
_op.startswith("__i")
and result_type(x.dtype, y.dtype) != x.dtype
):
assert_raises(TypeError, lambda: getattr(x, _op)(y))
# Ensure only those dtypes that are required for every operator are allowed.
elif (dtypes == "all" and (x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes
or x.dtype in _numeric_dtypes and y.dtype in _numeric_dtypes)
or (dtypes == "numeric" and x.dtype in _numeric_dtypes and y.dtype in _numeric_dtypes)
or dtypes == "integer" and x.dtype in _integer_dtypes and y.dtype in _numeric_dtypes
or dtypes == "integer_or_boolean" and (x.dtype in _integer_dtypes and y.dtype in _integer_dtypes
or x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes)
or dtypes == "boolean" and x.dtype in _boolean_dtypes and y.dtype in _boolean_dtypes
or dtypes == "floating" and x.dtype in _floating_dtypes and y.dtype in _floating_dtypes
):
getattr(x, _op)(y)
else:
assert_raises(TypeError, lambda: getattr(x, _op)(y))
unary_op_dtypes = {
"__abs__": "numeric",
"__invert__": "integer_or_boolean",
"__neg__": "numeric",
"__pos__": "numeric",
}
for op, dtypes in unary_op_dtypes.items():
for a in _array_vals():
if (
dtypes == "numeric"
and a.dtype in _numeric_dtypes
or dtypes == "integer_or_boolean"
and a.dtype in _integer_or_boolean_dtypes
):
# Only test for no error
getattr(a, op)()
else:
assert_raises(TypeError, lambda: getattr(a, op)())
# Finally, matmul() must be tested separately, because it works a bit
# different from the other operations.
def _matmul_array_vals():
for a in _array_vals():
yield a
for d in _all_dtypes:
yield ones((3, 4), dtype=d)
yield ones((4, 2), dtype=d)
yield ones((4, 4), dtype=d)
# Scalars always error
for _op in ["__matmul__", "__rmatmul__", "__imatmul__"]:
for s in [1, 1.0, False]:
for a in _matmul_array_vals():
if (type(s) in [float, int] and a.dtype in _floating_dtypes
or type(s) == int and a.dtype in _integer_dtypes):
# Type promotion is valid, but @ is not allowed on 0-D
# inputs, so the error is a ValueError
assert_raises(ValueError, lambda: getattr(a, _op)(s))
else:
assert_raises(TypeError, lambda: getattr(a, _op)(s))
for x in _matmul_array_vals():
for y in _matmul_array_vals():
if (x.dtype == uint64 and y.dtype in [int8, int16, int32, int64]
or y.dtype == uint64 and x.dtype in [int8, int16, int32, int64]
or x.dtype in _integer_dtypes and y.dtype not in _integer_dtypes
or y.dtype in _integer_dtypes and x.dtype not in _integer_dtypes
or x.dtype in _floating_dtypes and y.dtype not in _floating_dtypes
or y.dtype in _floating_dtypes and x.dtype not in _floating_dtypes
or x.dtype in _boolean_dtypes
or y.dtype in _boolean_dtypes
):
assert_raises(TypeError, lambda: x.__matmul__(y))
assert_raises(TypeError, lambda: y.__rmatmul__(x))
assert_raises(TypeError, lambda: x.__imatmul__(y))
elif x.shape == () or y.shape == () or x.shape[1] != y.shape[0]:
assert_raises(ValueError, lambda: x.__matmul__(y))
assert_raises(ValueError, lambda: y.__rmatmul__(x))
if result_type(x.dtype, y.dtype) != x.dtype:
assert_raises(TypeError, lambda: x.__imatmul__(y))
else:
assert_raises(ValueError, lambda: x.__imatmul__(y))
else:
x.__matmul__(y)
y.__rmatmul__(x)
if result_type(x.dtype, y.dtype) != x.dtype:
assert_raises(TypeError, lambda: x.__imatmul__(y))
elif y.shape[0] != y.shape[1]:
# This one fails because x @ y has a different shape from x
assert_raises(ValueError, lambda: x.__imatmul__(y))
else:
x.__imatmul__(y)
def test_python_scalar_construtors():
b = asarray(False)
i = asarray(0)
f = asarray(0.0)
assert bool(b) == False
assert int(i) == 0
assert float(f) == 0.0
assert operator.index(i) == 0
# bool/int/float should only be allowed on 0-D arrays.
assert_raises(TypeError, lambda: bool(asarray([False])))
assert_raises(TypeError, lambda: int(asarray([0])))
assert_raises(TypeError, lambda: float(asarray([0.0])))
assert_raises(TypeError, lambda: operator.index(asarray([0])))
# bool/int/float should only be allowed on arrays of the corresponding
# dtype
assert_raises(ValueError, lambda: bool(i))
assert_raises(ValueError, lambda: bool(f))
assert_raises(ValueError, lambda: int(b))
assert_raises(ValueError, lambda: int(f))
assert_raises(ValueError, lambda: float(b))
assert_raises(ValueError, lambda: float(i))
assert_raises(TypeError, lambda: operator.index(b))
assert_raises(TypeError, lambda: operator.index(f))
def test_device_property():
a = ones((3, 4))
assert a.device == 'cpu'
assert all(equal(a.to_device('cpu'), a))
assert_raises(ValueError, lambda: a.to_device('gpu'))
assert all(equal(asarray(a, device='cpu'), a))
assert_raises(ValueError, lambda: asarray(a, device='gpu'))
def test_array_properties():
a = ones((1, 2, 3))
b = ones((2, 3))
assert_raises(ValueError, lambda: a.T)
assert isinstance(b.T, Array)
assert b.T.shape == (3, 2)
assert isinstance(a.mT, Array)
assert a.mT.shape == (1, 3, 2)
assert isinstance(b.mT, Array)
assert b.mT.shape == (3, 2)
def test___array__():
a = ones((2, 3), dtype=int16)
assert np.asarray(a) is a._array
b = np.asarray(a, dtype=np.float64)
assert np.all(np.equal(b, np.ones((2, 3), dtype=np.float64)))
assert b.dtype == np.float64
def test_allow_newaxis():
a = ones(5)
indexed_a = a[None, :]
assert indexed_a.shape == (1, 5)
def test_disallow_flat_indexing_with_newaxis():
a = ones((3, 3, 3))
with pytest.raises(IndexError):
a[None, 0, 0]
def test_disallow_mask_with_newaxis():
a = ones((3, 3, 3))
with pytest.raises(IndexError):
a[None, asarray(True)]
@pytest.mark.parametrize("shape", [(), (5,), (3, 3, 3)])
@pytest.mark.parametrize("index", ["string", False, True])
def test_error_on_invalid_index(shape, index):
a = ones(shape)
with pytest.raises(IndexError):
a[index]
def test_mask_0d_array_without_errors():
a = ones(())
a[asarray(True)]
@pytest.mark.parametrize(
"i", [slice(5), slice(5, 0), asarray(True), asarray([0, 1])]
)
def test_error_on_invalid_index_with_ellipsis(i):
a = ones((3, 3, 3))
with pytest.raises(IndexError):
a[..., i]
with pytest.raises(IndexError):
a[i, ...]
def test_array_keys_use_private_array():
"""
Indexing operations convert array keys before indexing the internal array
Fails when array_api array keys are not converted into NumPy-proper arrays
in __getitem__(). This is achieved by passing array_api arrays with 0-sized
dimensions, which NumPy-proper treats erroneously - not sure why!
TODO: Find and use appropriate __setitem__() case.
"""
a = ones((0, 0), dtype=bool_)
assert a[a].shape == (0,)
a = ones((0,), dtype=bool_)
key = ones((0, 0), dtype=bool_)
with pytest.raises(IndexError):
a[key]

View File

@@ -0,0 +1,142 @@
from numpy.testing import assert_raises
import numpy as np
from .. import all
from .._creation_functions import (
asarray,
arange,
empty,
empty_like,
eye,
full,
full_like,
linspace,
meshgrid,
ones,
ones_like,
zeros,
zeros_like,
)
from .._dtypes import float32, float64
from .._array_object import Array
def test_asarray_errors():
# Test various protections against incorrect usage
assert_raises(TypeError, lambda: Array([1]))
assert_raises(TypeError, lambda: asarray(["a"]))
assert_raises(ValueError, lambda: asarray([1.0], dtype=np.float16))
assert_raises(OverflowError, lambda: asarray(2**100))
# Preferably this would be OverflowError
# assert_raises(OverflowError, lambda: asarray([2**100]))
assert_raises(TypeError, lambda: asarray([2**100]))
asarray([1], device="cpu") # Doesn't error
assert_raises(ValueError, lambda: asarray([1], device="gpu"))
assert_raises(ValueError, lambda: asarray([1], dtype=int))
assert_raises(ValueError, lambda: asarray([1], dtype="i"))
def test_asarray_copy():
a = asarray([1])
b = asarray(a, copy=True)
a[0] = 0
assert all(b[0] == 1)
assert all(a[0] == 0)
a = asarray([1])
b = asarray(a, copy=np._CopyMode.ALWAYS)
a[0] = 0
assert all(b[0] == 1)
assert all(a[0] == 0)
a = asarray([1])
b = asarray(a, copy=np._CopyMode.NEVER)
a[0] = 0
assert all(b[0] == 0)
assert_raises(NotImplementedError, lambda: asarray(a, copy=False))
assert_raises(NotImplementedError,
lambda: asarray(a, copy=np._CopyMode.IF_NEEDED))
def test_arange_errors():
arange(1, device="cpu") # Doesn't error
assert_raises(ValueError, lambda: arange(1, device="gpu"))
assert_raises(ValueError, lambda: arange(1, dtype=int))
assert_raises(ValueError, lambda: arange(1, dtype="i"))
def test_empty_errors():
empty((1,), device="cpu") # Doesn't error
assert_raises(ValueError, lambda: empty((1,), device="gpu"))
assert_raises(ValueError, lambda: empty((1,), dtype=int))
assert_raises(ValueError, lambda: empty((1,), dtype="i"))
def test_empty_like_errors():
empty_like(asarray(1), device="cpu") # Doesn't error
assert_raises(ValueError, lambda: empty_like(asarray(1), device="gpu"))
assert_raises(ValueError, lambda: empty_like(asarray(1), dtype=int))
assert_raises(ValueError, lambda: empty_like(asarray(1), dtype="i"))
def test_eye_errors():
eye(1, device="cpu") # Doesn't error
assert_raises(ValueError, lambda: eye(1, device="gpu"))
assert_raises(ValueError, lambda: eye(1, dtype=int))
assert_raises(ValueError, lambda: eye(1, dtype="i"))
def test_full_errors():
full((1,), 0, device="cpu") # Doesn't error
assert_raises(ValueError, lambda: full((1,), 0, device="gpu"))
assert_raises(ValueError, lambda: full((1,), 0, dtype=int))
assert_raises(ValueError, lambda: full((1,), 0, dtype="i"))
def test_full_like_errors():
full_like(asarray(1), 0, device="cpu") # Doesn't error
assert_raises(ValueError, lambda: full_like(asarray(1), 0, device="gpu"))
assert_raises(ValueError, lambda: full_like(asarray(1), 0, dtype=int))
assert_raises(ValueError, lambda: full_like(asarray(1), 0, dtype="i"))
def test_linspace_errors():
linspace(0, 1, 10, device="cpu") # Doesn't error
assert_raises(ValueError, lambda: linspace(0, 1, 10, device="gpu"))
assert_raises(ValueError, lambda: linspace(0, 1, 10, dtype=float))
assert_raises(ValueError, lambda: linspace(0, 1, 10, dtype="f"))
def test_ones_errors():
ones((1,), device="cpu") # Doesn't error
assert_raises(ValueError, lambda: ones((1,), device="gpu"))
assert_raises(ValueError, lambda: ones((1,), dtype=int))
assert_raises(ValueError, lambda: ones((1,), dtype="i"))
def test_ones_like_errors():
ones_like(asarray(1), device="cpu") # Doesn't error
assert_raises(ValueError, lambda: ones_like(asarray(1), device="gpu"))
assert_raises(ValueError, lambda: ones_like(asarray(1), dtype=int))
assert_raises(ValueError, lambda: ones_like(asarray(1), dtype="i"))
def test_zeros_errors():
zeros((1,), device="cpu") # Doesn't error
assert_raises(ValueError, lambda: zeros((1,), device="gpu"))
assert_raises(ValueError, lambda: zeros((1,), dtype=int))
assert_raises(ValueError, lambda: zeros((1,), dtype="i"))
def test_zeros_like_errors():
zeros_like(asarray(1), device="cpu") # Doesn't error
assert_raises(ValueError, lambda: zeros_like(asarray(1), device="gpu"))
assert_raises(ValueError, lambda: zeros_like(asarray(1), dtype=int))
assert_raises(ValueError, lambda: zeros_like(asarray(1), dtype="i"))
def test_meshgrid_dtype_errors():
# Doesn't raise
meshgrid()
meshgrid(asarray([1.], dtype=float32))
meshgrid(asarray([1.], dtype=float32), asarray([1.], dtype=float32))
assert_raises(ValueError, lambda: meshgrid(asarray([1.], dtype=float32), asarray([1.], dtype=float64)))

Some files were not shown because too many files have changed in this diff Show More