Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- janus/lib/python3.10/site-packages/numpy/char/__pycache__/__init__.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/core/__init__.pyi +0 -0
- janus/lib/python3.10/site-packages/numpy/core/__pycache__/_dtype.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/core/__pycache__/_utils.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/core/__pycache__/umath.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/core/_multiarray_umath.py +55 -0
- janus/lib/python3.10/site-packages/numpy/core/_utils.py +21 -0
- janus/lib/python3.10/site-packages/numpy/core/arrayprint.py +9 -0
- janus/lib/python3.10/site-packages/numpy/core/defchararray.py +9 -0
- janus/lib/python3.10/site-packages/numpy/core/einsumfunc.py +9 -0
- janus/lib/python3.10/site-packages/numpy/core/fromnumeric.py +9 -0
- janus/lib/python3.10/site-packages/numpy/core/function_base.py +9 -0
- janus/lib/python3.10/site-packages/numpy/core/multiarray.py +24 -0
- janus/lib/python3.10/site-packages/numpy/core/numerictypes.py +9 -0
- janus/lib/python3.10/site-packages/numpy/core/shape_base.py +9 -0
- janus/lib/python3.10/site-packages/numpy/core/umath.py +9 -0
- janus/lib/python3.10/site-packages/numpy/fft/__init__.py +215 -0
- janus/lib/python3.10/site-packages/numpy/fft/__init__.pyi +43 -0
- janus/lib/python3.10/site-packages/numpy/fft/__pycache__/__init__.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/fft/__pycache__/_helper.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/fft/__pycache__/_pocketfft.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/fft/__pycache__/helper.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/fft/_helper.py +235 -0
- janus/lib/python3.10/site-packages/numpy/fft/_helper.pyi +51 -0
- janus/lib/python3.10/site-packages/numpy/fft/_pocketfft.py +1687 -0
- janus/lib/python3.10/site-packages/numpy/fft/_pocketfft.pyi +137 -0
- janus/lib/python3.10/site-packages/numpy/fft/helper.py +16 -0
- janus/lib/python3.10/site-packages/numpy/fft/tests/__init__.py +0 -0
- janus/lib/python3.10/site-packages/numpy/fft/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/fft/tests/__pycache__/test_helper.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/fft/tests/__pycache__/test_pocketfft.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/fft/tests/test_helper.py +167 -0
- janus/lib/python3.10/site-packages/numpy/fft/tests/test_pocketfft.py +589 -0
- janus/lib/python3.10/site-packages/numpy/lib/_arraypad_impl.py +891 -0
- janus/lib/python3.10/site-packages/numpy/lib/stride_tricks.py +3 -0
- janus/lib/python3.10/site-packages/numpy/linalg/__init__.py +95 -0
- janus/lib/python3.10/site-packages/numpy/linalg/__init__.pyi +70 -0
- janus/lib/python3.10/site-packages/numpy/linalg/__pycache__/__init__.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/linalg/__pycache__/linalg.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/linalg/_linalg.py +0 -0
- janus/lib/python3.10/site-packages/numpy/linalg/_linalg.pyi +463 -0
- janus/lib/python3.10/site-packages/numpy/linalg/lapack_lite.cpython-310-x86_64-linux-gnu.so +0 -0
- janus/lib/python3.10/site-packages/numpy/linalg/linalg.py +16 -0
- janus/lib/python3.10/site-packages/numpy/linalg/tests/__init__.py +0 -0
- janus/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_deprecations.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_linalg.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_regression.cpython-310.pyc +0 -0
- janus/lib/python3.10/site-packages/numpy/linalg/tests/test_deprecations.py +20 -0
- janus/lib/python3.10/site-packages/numpy/linalg/tests/test_linalg.py +2386 -0
janus/lib/python3.10/site-packages/numpy/char/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (250 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/core/__init__.pyi
ADDED
|
File without changes
|
janus/lib/python3.10/site-packages/numpy/core/__pycache__/_dtype.cpython-310.pyc
ADDED
|
Binary file (509 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/core/__pycache__/_utils.cpython-310.pyc
ADDED
|
Binary file (1 kB). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/core/__pycache__/umath.cpython-310.pyc
ADDED
|
Binary file (506 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/core/_multiarray_umath.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numpy._core import _multiarray_umath
|
| 2 |
+
from numpy import ufunc
|
| 3 |
+
|
| 4 |
+
for item in _multiarray_umath.__dir__():
|
| 5 |
+
# ufuncs appear in pickles with a path in numpy.core._multiarray_umath
|
| 6 |
+
# and so must import from this namespace without warning or error
|
| 7 |
+
attr = getattr(_multiarray_umath, item)
|
| 8 |
+
if isinstance(attr, ufunc):
|
| 9 |
+
globals()[item] = attr
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def __getattr__(attr_name):
|
| 13 |
+
from numpy._core import _multiarray_umath
|
| 14 |
+
from ._utils import _raise_warning
|
| 15 |
+
|
| 16 |
+
if attr_name in {"_ARRAY_API", "_UFUNC_API"}:
|
| 17 |
+
from numpy.version import short_version
|
| 18 |
+
import textwrap
|
| 19 |
+
import traceback
|
| 20 |
+
import sys
|
| 21 |
+
|
| 22 |
+
msg = textwrap.dedent(f"""
|
| 23 |
+
A module that was compiled using NumPy 1.x cannot be run in
|
| 24 |
+
NumPy {short_version} as it may crash. To support both 1.x and 2.x
|
| 25 |
+
versions of NumPy, modules must be compiled with NumPy 2.0.
|
| 26 |
+
Some module may need to rebuild instead e.g. with 'pybind11>=2.12'.
|
| 27 |
+
|
| 28 |
+
If you are a user of the module, the easiest solution will be to
|
| 29 |
+
downgrade to 'numpy<2' or try to upgrade the affected module.
|
| 30 |
+
We expect that some modules will need time to support NumPy 2.
|
| 31 |
+
|
| 32 |
+
""")
|
| 33 |
+
tb_msg = "Traceback (most recent call last):"
|
| 34 |
+
for line in traceback.format_stack()[:-1]:
|
| 35 |
+
if "frozen importlib" in line:
|
| 36 |
+
continue
|
| 37 |
+
tb_msg += line
|
| 38 |
+
|
| 39 |
+
# Also print the message (with traceback). This is because old versions
|
| 40 |
+
# of NumPy unfortunately set up the import to replace (and hide) the
|
| 41 |
+
# error. The traceback shouldn't be needed, but e.g. pytest plugins
|
| 42 |
+
# seem to swallow it and we should be failing anyway...
|
| 43 |
+
sys.stderr.write(msg + tb_msg)
|
| 44 |
+
raise ImportError(msg)
|
| 45 |
+
|
| 46 |
+
ret = getattr(_multiarray_umath, attr_name, None)
|
| 47 |
+
if ret is None:
|
| 48 |
+
raise AttributeError(
|
| 49 |
+
"module 'numpy.core._multiarray_umath' has no attribute "
|
| 50 |
+
f"{attr_name}")
|
| 51 |
+
_raise_warning(attr_name, "_multiarray_umath")
|
| 52 |
+
return ret
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
del _multiarray_umath, ufunc
|
janus/lib/python3.10/site-packages/numpy/core/_utils.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import warnings
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def _raise_warning(attr: str, submodule: str | None = None) -> None:
|
| 5 |
+
new_module = "numpy._core"
|
| 6 |
+
old_module = "numpy.core"
|
| 7 |
+
if submodule is not None:
|
| 8 |
+
new_module = f"{new_module}.{submodule}"
|
| 9 |
+
old_module = f"{old_module}.{submodule}"
|
| 10 |
+
warnings.warn(
|
| 11 |
+
f"{old_module} is deprecated and has been renamed to {new_module}. "
|
| 12 |
+
"The numpy._core namespace contains private NumPy internals and its "
|
| 13 |
+
"use is discouraged, as NumPy internals can change without warning in "
|
| 14 |
+
"any release. In practice, most real-world usage of numpy.core is to "
|
| 15 |
+
"access functionality in the public NumPy API. If that is the case, "
|
| 16 |
+
"use the public NumPy API. If not, you are using NumPy internals. "
|
| 17 |
+
"If you would still like to access an internal attribute, "
|
| 18 |
+
f"use {new_module}.{attr}.",
|
| 19 |
+
DeprecationWarning,
|
| 20 |
+
stacklevel=3
|
| 21 |
+
)
|
janus/lib/python3.10/site-packages/numpy/core/arrayprint.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(attr_name):
|
| 2 |
+
from numpy._core import arrayprint
|
| 3 |
+
from ._utils import _raise_warning
|
| 4 |
+
ret = getattr(arrayprint, attr_name, None)
|
| 5 |
+
if ret is None:
|
| 6 |
+
raise AttributeError(
|
| 7 |
+
f"module 'numpy.core.arrayprint' has no attribute {attr_name}")
|
| 8 |
+
_raise_warning(attr_name, "arrayprint")
|
| 9 |
+
return ret
|
janus/lib/python3.10/site-packages/numpy/core/defchararray.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(attr_name):
|
| 2 |
+
from numpy._core import defchararray
|
| 3 |
+
from ._utils import _raise_warning
|
| 4 |
+
ret = getattr(defchararray, attr_name, None)
|
| 5 |
+
if ret is None:
|
| 6 |
+
raise AttributeError(
|
| 7 |
+
f"module 'numpy.core.defchararray' has no attribute {attr_name}")
|
| 8 |
+
_raise_warning(attr_name, "defchararray")
|
| 9 |
+
return ret
|
janus/lib/python3.10/site-packages/numpy/core/einsumfunc.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(attr_name):
|
| 2 |
+
from numpy._core import einsumfunc
|
| 3 |
+
from ._utils import _raise_warning
|
| 4 |
+
ret = getattr(einsumfunc, attr_name, None)
|
| 5 |
+
if ret is None:
|
| 6 |
+
raise AttributeError(
|
| 7 |
+
f"module 'numpy.core.einsumfunc' has no attribute {attr_name}")
|
| 8 |
+
_raise_warning(attr_name, "einsumfunc")
|
| 9 |
+
return ret
|
janus/lib/python3.10/site-packages/numpy/core/fromnumeric.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(attr_name):
|
| 2 |
+
from numpy._core import fromnumeric
|
| 3 |
+
from ._utils import _raise_warning
|
| 4 |
+
ret = getattr(fromnumeric, attr_name, None)
|
| 5 |
+
if ret is None:
|
| 6 |
+
raise AttributeError(
|
| 7 |
+
f"module 'numpy.core.fromnumeric' has no attribute {attr_name}")
|
| 8 |
+
_raise_warning(attr_name, "fromnumeric")
|
| 9 |
+
return ret
|
janus/lib/python3.10/site-packages/numpy/core/function_base.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(attr_name):
|
| 2 |
+
from numpy._core import function_base
|
| 3 |
+
from ._utils import _raise_warning
|
| 4 |
+
ret = getattr(function_base, attr_name, None)
|
| 5 |
+
if ret is None:
|
| 6 |
+
raise AttributeError(
|
| 7 |
+
f"module 'numpy.core.function_base' has no attribute {attr_name}")
|
| 8 |
+
_raise_warning(attr_name, "function_base")
|
| 9 |
+
return ret
|
janus/lib/python3.10/site-packages/numpy/core/multiarray.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numpy._core import multiarray
|
| 2 |
+
|
| 3 |
+
# these must import without warning or error from numpy.core.multiarray to
|
| 4 |
+
# support old pickle files
|
| 5 |
+
for item in ["_reconstruct", "scalar"]:
|
| 6 |
+
globals()[item] = getattr(multiarray, item)
|
| 7 |
+
|
| 8 |
+
# Pybind11 (in versions <= 2.11.1) imports _ARRAY_API from the multiarray
|
| 9 |
+
# submodule as a part of NumPy initialization, therefore it must be importable
|
| 10 |
+
# without a warning.
|
| 11 |
+
_ARRAY_API = multiarray._ARRAY_API
|
| 12 |
+
|
| 13 |
+
def __getattr__(attr_name):
|
| 14 |
+
from numpy._core import multiarray
|
| 15 |
+
from ._utils import _raise_warning
|
| 16 |
+
ret = getattr(multiarray, attr_name, None)
|
| 17 |
+
if ret is None:
|
| 18 |
+
raise AttributeError(
|
| 19 |
+
f"module 'numpy.core.multiarray' has no attribute {attr_name}")
|
| 20 |
+
_raise_warning(attr_name, "multiarray")
|
| 21 |
+
return ret
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
del multiarray
|
janus/lib/python3.10/site-packages/numpy/core/numerictypes.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(attr_name):
|
| 2 |
+
from numpy._core import numerictypes
|
| 3 |
+
from ._utils import _raise_warning
|
| 4 |
+
ret = getattr(numerictypes, attr_name, None)
|
| 5 |
+
if ret is None:
|
| 6 |
+
raise AttributeError(
|
| 7 |
+
f"module 'numpy.core.numerictypes' has no attribute {attr_name}")
|
| 8 |
+
_raise_warning(attr_name, "numerictypes")
|
| 9 |
+
return ret
|
janus/lib/python3.10/site-packages/numpy/core/shape_base.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(attr_name):
|
| 2 |
+
from numpy._core import shape_base
|
| 3 |
+
from ._utils import _raise_warning
|
| 4 |
+
ret = getattr(shape_base, attr_name, None)
|
| 5 |
+
if ret is None:
|
| 6 |
+
raise AttributeError(
|
| 7 |
+
f"module 'numpy.core.shape_base' has no attribute {attr_name}")
|
| 8 |
+
_raise_warning(attr_name, "shape_base")
|
| 9 |
+
return ret
|
janus/lib/python3.10/site-packages/numpy/core/umath.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(attr_name):
|
| 2 |
+
from numpy._core import umath
|
| 3 |
+
from ._utils import _raise_warning
|
| 4 |
+
ret = getattr(umath, attr_name, None)
|
| 5 |
+
if ret is None:
|
| 6 |
+
raise AttributeError(
|
| 7 |
+
f"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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Discrete Fourier Transform (:mod:`numpy.fft`)
|
| 3 |
+
=============================================
|
| 4 |
+
|
| 5 |
+
.. currentmodule:: numpy.fft
|
| 6 |
+
|
| 7 |
+
The SciPy module `scipy.fft` is a more comprehensive superset
|
| 8 |
+
of ``numpy.fft``, which includes only a basic set of routines.
|
| 9 |
+
|
| 10 |
+
Standard FFTs
|
| 11 |
+
-------------
|
| 12 |
+
|
| 13 |
+
.. autosummary::
|
| 14 |
+
:toctree: generated/
|
| 15 |
+
|
| 16 |
+
fft Discrete Fourier transform.
|
| 17 |
+
ifft Inverse discrete Fourier transform.
|
| 18 |
+
fft2 Discrete Fourier transform in two dimensions.
|
| 19 |
+
ifft2 Inverse discrete Fourier transform in two dimensions.
|
| 20 |
+
fftn Discrete Fourier transform in N-dimensions.
|
| 21 |
+
ifftn Inverse discrete Fourier transform in N dimensions.
|
| 22 |
+
|
| 23 |
+
Real FFTs
|
| 24 |
+
---------
|
| 25 |
+
|
| 26 |
+
.. autosummary::
|
| 27 |
+
:toctree: generated/
|
| 28 |
+
|
| 29 |
+
rfft Real discrete Fourier transform.
|
| 30 |
+
irfft Inverse real discrete Fourier transform.
|
| 31 |
+
rfft2 Real discrete Fourier transform in two dimensions.
|
| 32 |
+
irfft2 Inverse real discrete Fourier transform in two dimensions.
|
| 33 |
+
rfftn Real discrete Fourier transform in N dimensions.
|
| 34 |
+
irfftn Inverse real discrete Fourier transform in N dimensions.
|
| 35 |
+
|
| 36 |
+
Hermitian FFTs
|
| 37 |
+
--------------
|
| 38 |
+
|
| 39 |
+
.. autosummary::
|
| 40 |
+
:toctree: generated/
|
| 41 |
+
|
| 42 |
+
hfft Hermitian discrete Fourier transform.
|
| 43 |
+
ihfft Inverse Hermitian discrete Fourier transform.
|
| 44 |
+
|
| 45 |
+
Helper routines
|
| 46 |
+
---------------
|
| 47 |
+
|
| 48 |
+
.. autosummary::
|
| 49 |
+
:toctree: generated/
|
| 50 |
+
|
| 51 |
+
fftfreq Discrete Fourier Transform sample frequencies.
|
| 52 |
+
rfftfreq DFT sample frequencies (for usage with rfft, irfft).
|
| 53 |
+
fftshift Shift zero-frequency component to center of spectrum.
|
| 54 |
+
ifftshift Inverse of fftshift.
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
Background information
|
| 58 |
+
----------------------
|
| 59 |
+
|
| 60 |
+
Fourier analysis is fundamentally a method for expressing a function as a
|
| 61 |
+
sum of periodic components, and for recovering the function from those
|
| 62 |
+
components. When both the function and its Fourier transform are
|
| 63 |
+
replaced with discretized counterparts, it is called the discrete Fourier
|
| 64 |
+
transform (DFT). The DFT has become a mainstay of numerical computing in
|
| 65 |
+
part because of a very fast algorithm for computing it, called the Fast
|
| 66 |
+
Fourier Transform (FFT), which was known to Gauss (1805) and was brought
|
| 67 |
+
to light in its current form by Cooley and Tukey [CT]_. Press et al. [NR]_
|
| 68 |
+
provide an accessible introduction to Fourier analysis and its
|
| 69 |
+
applications.
|
| 70 |
+
|
| 71 |
+
Because the discrete Fourier transform separates its input into
|
| 72 |
+
components that contribute at discrete frequencies, it has a great number
|
| 73 |
+
of applications in digital signal processing, e.g., for filtering, and in
|
| 74 |
+
this context the discretized input to the transform is customarily
|
| 75 |
+
referred to as a *signal*, which exists in the *time domain*. The output
|
| 76 |
+
is called a *spectrum* or *transform* and exists in the *frequency
|
| 77 |
+
domain*.
|
| 78 |
+
|
| 79 |
+
Implementation details
|
| 80 |
+
----------------------
|
| 81 |
+
|
| 82 |
+
There are many ways to define the DFT, varying in the sign of the
|
| 83 |
+
exponent, normalization, etc. In this implementation, the DFT is defined
|
| 84 |
+
as
|
| 85 |
+
|
| 86 |
+
.. math::
|
| 87 |
+
A_k = \\sum_{m=0}^{n-1} a_m \\exp\\left\\{-2\\pi i{mk \\over n}\\right\\}
|
| 88 |
+
\\qquad k = 0,\\ldots,n-1.
|
| 89 |
+
|
| 90 |
+
The DFT is in general defined for complex inputs and outputs, and a
|
| 91 |
+
single-frequency component at linear frequency :math:`f` is
|
| 92 |
+
represented by a complex exponential
|
| 93 |
+
:math:`a_m = \\exp\\{2\\pi i\\,f m\\Delta t\\}`, where :math:`\\Delta t`
|
| 94 |
+
is the sampling interval.
|
| 95 |
+
|
| 96 |
+
The values in the result follow so-called "standard" order: If ``A =
|
| 97 |
+
fft(a, n)``, then ``A[0]`` contains the zero-frequency term (the sum of
|
| 98 |
+
the signal), which is always purely real for real inputs. Then ``A[1:n/2]``
|
| 99 |
+
contains the positive-frequency terms, and ``A[n/2+1:]`` contains the
|
| 100 |
+
negative-frequency terms, in order of decreasingly negative frequency.
|
| 101 |
+
For an even number of input points, ``A[n/2]`` represents both positive and
|
| 102 |
+
negative Nyquist frequency, and is also purely real for real input. For
|
| 103 |
+
an odd number of input points, ``A[(n-1)/2]`` contains the largest positive
|
| 104 |
+
frequency, while ``A[(n+1)/2]`` contains the largest negative frequency.
|
| 105 |
+
The routine ``np.fft.fftfreq(n)`` returns an array giving the frequencies
|
| 106 |
+
of corresponding elements in the output. The routine
|
| 107 |
+
``np.fft.fftshift(A)`` shifts transforms and their frequencies to put the
|
| 108 |
+
zero-frequency components in the middle, and ``np.fft.ifftshift(A)`` undoes
|
| 109 |
+
that shift.
|
| 110 |
+
|
| 111 |
+
When the input `a` is a time-domain signal and ``A = fft(a)``, ``np.abs(A)``
|
| 112 |
+
is its amplitude spectrum and ``np.abs(A)**2`` is its power spectrum.
|
| 113 |
+
The phase spectrum is obtained by ``np.angle(A)``.
|
| 114 |
+
|
| 115 |
+
The inverse DFT is defined as
|
| 116 |
+
|
| 117 |
+
.. math::
|
| 118 |
+
a_m = \\frac{1}{n}\\sum_{k=0}^{n-1}A_k\\exp\\left\\{2\\pi i{mk\\over n}\\right\\}
|
| 119 |
+
\\qquad m = 0,\\ldots,n-1.
|
| 120 |
+
|
| 121 |
+
It differs from the forward transform by the sign of the exponential
|
| 122 |
+
argument and the default normalization by :math:`1/n`.
|
| 123 |
+
|
| 124 |
+
Type Promotion
|
| 125 |
+
--------------
|
| 126 |
+
|
| 127 |
+
`numpy.fft` promotes ``float32`` and ``complex64`` arrays to ``float64`` and
|
| 128 |
+
``complex128`` arrays respectively. For an FFT implementation that does not
|
| 129 |
+
promote input arrays, see `scipy.fftpack`.
|
| 130 |
+
|
| 131 |
+
Normalization
|
| 132 |
+
-------------
|
| 133 |
+
|
| 134 |
+
The argument ``norm`` indicates which direction of the pair of direct/inverse
|
| 135 |
+
transforms is scaled and with what normalization factor.
|
| 136 |
+
The default normalization (``"backward"``) has the direct (forward) transforms
|
| 137 |
+
unscaled and the inverse (backward) transforms scaled by :math:`1/n`. It is
|
| 138 |
+
possible to obtain unitary transforms by setting the keyword argument ``norm``
|
| 139 |
+
to ``"ortho"`` so that both direct and inverse transforms are scaled by
|
| 140 |
+
:math:`1/\\sqrt{n}`. Finally, setting the keyword argument ``norm`` to
|
| 141 |
+
``"forward"`` has the direct transforms scaled by :math:`1/n` and the inverse
|
| 142 |
+
transforms unscaled (i.e. exactly opposite to the default ``"backward"``).
|
| 143 |
+
`None` is an alias of the default option ``"backward"`` for backward
|
| 144 |
+
compatibility.
|
| 145 |
+
|
| 146 |
+
Real and Hermitian transforms
|
| 147 |
+
-----------------------------
|
| 148 |
+
|
| 149 |
+
When the input is purely real, its transform is Hermitian, i.e., the
|
| 150 |
+
component at frequency :math:`f_k` is the complex conjugate of the
|
| 151 |
+
component at frequency :math:`-f_k`, which means that for real
|
| 152 |
+
inputs there is no information in the negative frequency components that
|
| 153 |
+
is not already available from the positive frequency components.
|
| 154 |
+
The family of `rfft` functions is
|
| 155 |
+
designed to operate on real inputs, and exploits this symmetry by
|
| 156 |
+
computing only the positive frequency components, up to and including the
|
| 157 |
+
Nyquist frequency. Thus, ``n`` input points produce ``n/2+1`` complex
|
| 158 |
+
output points. The inverses of this family assumes the same symmetry of
|
| 159 |
+
its input, and for an output of ``n`` points uses ``n/2+1`` input points.
|
| 160 |
+
|
| 161 |
+
Correspondingly, when the spectrum is purely real, the signal is
|
| 162 |
+
Hermitian. The `hfft` family of functions exploits this symmetry by
|
| 163 |
+
using ``n/2+1`` complex points in the input (time) domain for ``n`` real
|
| 164 |
+
points in the frequency domain.
|
| 165 |
+
|
| 166 |
+
In higher dimensions, FFTs are used, e.g., for image analysis and
|
| 167 |
+
filtering. The computational efficiency of the FFT means that it can
|
| 168 |
+
also be a faster way to compute large convolutions, using the property
|
| 169 |
+
that a convolution in the time domain is equivalent to a point-by-point
|
| 170 |
+
multiplication in the frequency domain.
|
| 171 |
+
|
| 172 |
+
Higher dimensions
|
| 173 |
+
-----------------
|
| 174 |
+
|
| 175 |
+
In two dimensions, the DFT is defined as
|
| 176 |
+
|
| 177 |
+
.. math::
|
| 178 |
+
A_{kl} = \\sum_{m=0}^{M-1} \\sum_{n=0}^{N-1}
|
| 179 |
+
a_{mn}\\exp\\left\\{-2\\pi i \\left({mk\\over M}+{nl\\over N}\\right)\\right\\}
|
| 180 |
+
\\qquad k = 0, \\ldots, M-1;\\quad l = 0, \\ldots, N-1,
|
| 181 |
+
|
| 182 |
+
which extends in the obvious way to higher dimensions, and the inverses
|
| 183 |
+
in higher dimensions also extend in the same way.
|
| 184 |
+
|
| 185 |
+
References
|
| 186 |
+
----------
|
| 187 |
+
|
| 188 |
+
.. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
|
| 189 |
+
machine calculation of complex Fourier series," *Math. Comput.*
|
| 190 |
+
19: 297-301.
|
| 191 |
+
|
| 192 |
+
.. [NR] Press, W., Teukolsky, S., Vetterline, W.T., and Flannery, B.P.,
|
| 193 |
+
2007, *Numerical Recipes: The Art of Scientific Computing*, ch.
|
| 194 |
+
12-13. Cambridge Univ. Press, Cambridge, UK.
|
| 195 |
+
|
| 196 |
+
Examples
|
| 197 |
+
--------
|
| 198 |
+
|
| 199 |
+
For examples, see the various functions.
|
| 200 |
+
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
from . import _pocketfft, _helper
|
| 204 |
+
# TODO: `numpy.fft.helper`` was deprecated in NumPy 2.0. It should
|
| 205 |
+
# be deleted once downstream libraries move to `numpy.fft`.
|
| 206 |
+
from . import helper
|
| 207 |
+
from ._pocketfft import *
|
| 208 |
+
from ._helper import *
|
| 209 |
+
|
| 210 |
+
__all__ = _pocketfft.__all__.copy()
|
| 211 |
+
__all__ += _helper.__all__
|
| 212 |
+
|
| 213 |
+
from numpy._pytesttester import PytestTester
|
| 214 |
+
test = PytestTester(__name__)
|
| 215 |
+
del PytestTester
|
janus/lib/python3.10/site-packages/numpy/fft/__init__.pyi
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ._pocketfft import (
|
| 2 |
+
fft,
|
| 3 |
+
ifft,
|
| 4 |
+
rfft,
|
| 5 |
+
irfft,
|
| 6 |
+
hfft,
|
| 7 |
+
ihfft,
|
| 8 |
+
rfftn,
|
| 9 |
+
irfftn,
|
| 10 |
+
rfft2,
|
| 11 |
+
irfft2,
|
| 12 |
+
fft2,
|
| 13 |
+
ifft2,
|
| 14 |
+
fftn,
|
| 15 |
+
ifftn,
|
| 16 |
+
)
|
| 17 |
+
from ._helper import (
|
| 18 |
+
fftshift,
|
| 19 |
+
ifftshift,
|
| 20 |
+
fftfreq,
|
| 21 |
+
rfftfreq,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
__all__ = [
|
| 25 |
+
"fft",
|
| 26 |
+
"ifft",
|
| 27 |
+
"rfft",
|
| 28 |
+
"irfft",
|
| 29 |
+
"hfft",
|
| 30 |
+
"ihfft",
|
| 31 |
+
"rfftn",
|
| 32 |
+
"irfftn",
|
| 33 |
+
"rfft2",
|
| 34 |
+
"irfft2",
|
| 35 |
+
"fft2",
|
| 36 |
+
"ifft2",
|
| 37 |
+
"fftn",
|
| 38 |
+
"ifftn",
|
| 39 |
+
"fftshift",
|
| 40 |
+
"ifftshift",
|
| 41 |
+
"fftfreq",
|
| 42 |
+
"rfftfreq",
|
| 43 |
+
]
|
janus/lib/python3.10/site-packages/numpy/fft/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (8.3 kB). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/fft/__pycache__/_helper.cpython-310.pyc
ADDED
|
Binary file (7.25 kB). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/fft/__pycache__/_pocketfft.cpython-310.pyc
ADDED
|
Binary file (61.1 kB). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/fft/__pycache__/helper.cpython-310.pyc
ADDED
|
Binary file (763 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/fft/_helper.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Discrete Fourier Transforms - _helper.py
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
from numpy._core import integer, empty, arange, asarray, roll
|
| 6 |
+
from numpy._core.overrides import array_function_dispatch, set_module
|
| 7 |
+
|
| 8 |
+
# Created by Pearu Peterson, September 2002
|
| 9 |
+
|
| 10 |
+
__all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq']
|
| 11 |
+
|
| 12 |
+
integer_types = (int, integer)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _fftshift_dispatcher(x, axes=None):
|
| 16 |
+
return (x,)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@array_function_dispatch(_fftshift_dispatcher, module='numpy.fft')
|
| 20 |
+
def fftshift(x, axes=None):
|
| 21 |
+
"""
|
| 22 |
+
Shift the zero-frequency component to the center of the spectrum.
|
| 23 |
+
|
| 24 |
+
This function swaps half-spaces for all axes listed (defaults to all).
|
| 25 |
+
Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
|
| 26 |
+
|
| 27 |
+
Parameters
|
| 28 |
+
----------
|
| 29 |
+
x : array_like
|
| 30 |
+
Input array.
|
| 31 |
+
axes : int or shape tuple, optional
|
| 32 |
+
Axes over which to shift. Default is None, which shifts all axes.
|
| 33 |
+
|
| 34 |
+
Returns
|
| 35 |
+
-------
|
| 36 |
+
y : ndarray
|
| 37 |
+
The shifted array.
|
| 38 |
+
|
| 39 |
+
See Also
|
| 40 |
+
--------
|
| 41 |
+
ifftshift : The inverse of `fftshift`.
|
| 42 |
+
|
| 43 |
+
Examples
|
| 44 |
+
--------
|
| 45 |
+
>>> import numpy as np
|
| 46 |
+
>>> freqs = np.fft.fftfreq(10, 0.1)
|
| 47 |
+
>>> freqs
|
| 48 |
+
array([ 0., 1., 2., ..., -3., -2., -1.])
|
| 49 |
+
>>> np.fft.fftshift(freqs)
|
| 50 |
+
array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.])
|
| 51 |
+
|
| 52 |
+
Shift the zero-frequency component only along the second axis:
|
| 53 |
+
|
| 54 |
+
>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
|
| 55 |
+
>>> freqs
|
| 56 |
+
array([[ 0., 1., 2.],
|
| 57 |
+
[ 3., 4., -4.],
|
| 58 |
+
[-3., -2., -1.]])
|
| 59 |
+
>>> np.fft.fftshift(freqs, axes=(1,))
|
| 60 |
+
array([[ 2., 0., 1.],
|
| 61 |
+
[-4., 3., 4.],
|
| 62 |
+
[-1., -3., -2.]])
|
| 63 |
+
|
| 64 |
+
"""
|
| 65 |
+
x = asarray(x)
|
| 66 |
+
if axes is None:
|
| 67 |
+
axes = tuple(range(x.ndim))
|
| 68 |
+
shift = [dim // 2 for dim in x.shape]
|
| 69 |
+
elif isinstance(axes, integer_types):
|
| 70 |
+
shift = x.shape[axes] // 2
|
| 71 |
+
else:
|
| 72 |
+
shift = [x.shape[ax] // 2 for ax in axes]
|
| 73 |
+
|
| 74 |
+
return roll(x, shift, axes)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
@array_function_dispatch(_fftshift_dispatcher, module='numpy.fft')
|
| 78 |
+
def ifftshift(x, axes=None):
|
| 79 |
+
"""
|
| 80 |
+
The inverse of `fftshift`. Although identical for even-length `x`, the
|
| 81 |
+
functions differ by one sample for odd-length `x`.
|
| 82 |
+
|
| 83 |
+
Parameters
|
| 84 |
+
----------
|
| 85 |
+
x : array_like
|
| 86 |
+
Input array.
|
| 87 |
+
axes : int or shape tuple, optional
|
| 88 |
+
Axes over which to calculate. Defaults to None, which shifts all axes.
|
| 89 |
+
|
| 90 |
+
Returns
|
| 91 |
+
-------
|
| 92 |
+
y : ndarray
|
| 93 |
+
The shifted array.
|
| 94 |
+
|
| 95 |
+
See Also
|
| 96 |
+
--------
|
| 97 |
+
fftshift : Shift zero-frequency component to the center of the spectrum.
|
| 98 |
+
|
| 99 |
+
Examples
|
| 100 |
+
--------
|
| 101 |
+
>>> import numpy as np
|
| 102 |
+
>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
|
| 103 |
+
>>> freqs
|
| 104 |
+
array([[ 0., 1., 2.],
|
| 105 |
+
[ 3., 4., -4.],
|
| 106 |
+
[-3., -2., -1.]])
|
| 107 |
+
>>> np.fft.ifftshift(np.fft.fftshift(freqs))
|
| 108 |
+
array([[ 0., 1., 2.],
|
| 109 |
+
[ 3., 4., -4.],
|
| 110 |
+
[-3., -2., -1.]])
|
| 111 |
+
|
| 112 |
+
"""
|
| 113 |
+
x = asarray(x)
|
| 114 |
+
if axes is None:
|
| 115 |
+
axes = tuple(range(x.ndim))
|
| 116 |
+
shift = [-(dim // 2) for dim in x.shape]
|
| 117 |
+
elif isinstance(axes, integer_types):
|
| 118 |
+
shift = -(x.shape[axes] // 2)
|
| 119 |
+
else:
|
| 120 |
+
shift = [-(x.shape[ax] // 2) for ax in axes]
|
| 121 |
+
|
| 122 |
+
return roll(x, shift, axes)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@set_module('numpy.fft')
|
| 126 |
+
def fftfreq(n, d=1.0, device=None):
|
| 127 |
+
"""
|
| 128 |
+
Return the Discrete Fourier Transform sample frequencies.
|
| 129 |
+
|
| 130 |
+
The returned float array `f` contains the frequency bin centers in cycles
|
| 131 |
+
per unit of the sample spacing (with zero at the start). For instance, if
|
| 132 |
+
the sample spacing is in seconds, then the frequency unit is cycles/second.
|
| 133 |
+
|
| 134 |
+
Given a window length `n` and a sample spacing `d`::
|
| 135 |
+
|
| 136 |
+
f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is even
|
| 137 |
+
f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd
|
| 138 |
+
|
| 139 |
+
Parameters
|
| 140 |
+
----------
|
| 141 |
+
n : int
|
| 142 |
+
Window length.
|
| 143 |
+
d : scalar, optional
|
| 144 |
+
Sample spacing (inverse of the sampling rate). Defaults to 1.
|
| 145 |
+
device : str, optional
|
| 146 |
+
The device on which to place the created array. Default: ``None``.
|
| 147 |
+
For Array-API interoperability only, so must be ``"cpu"`` if passed.
|
| 148 |
+
|
| 149 |
+
.. versionadded:: 2.0.0
|
| 150 |
+
|
| 151 |
+
Returns
|
| 152 |
+
-------
|
| 153 |
+
f : ndarray
|
| 154 |
+
Array of length `n` containing the sample frequencies.
|
| 155 |
+
|
| 156 |
+
Examples
|
| 157 |
+
--------
|
| 158 |
+
>>> import numpy as np
|
| 159 |
+
>>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
|
| 160 |
+
>>> fourier = np.fft.fft(signal)
|
| 161 |
+
>>> n = signal.size
|
| 162 |
+
>>> timestep = 0.1
|
| 163 |
+
>>> freq = np.fft.fftfreq(n, d=timestep)
|
| 164 |
+
>>> freq
|
| 165 |
+
array([ 0. , 1.25, 2.5 , ..., -3.75, -2.5 , -1.25])
|
| 166 |
+
|
| 167 |
+
"""
|
| 168 |
+
if not isinstance(n, integer_types):
|
| 169 |
+
raise ValueError("n should be an integer")
|
| 170 |
+
val = 1.0 / (n * d)
|
| 171 |
+
results = empty(n, int, device=device)
|
| 172 |
+
N = (n-1)//2 + 1
|
| 173 |
+
p1 = arange(0, N, dtype=int, device=device)
|
| 174 |
+
results[:N] = p1
|
| 175 |
+
p2 = arange(-(n//2), 0, dtype=int, device=device)
|
| 176 |
+
results[N:] = p2
|
| 177 |
+
return results * val
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
@set_module('numpy.fft')
|
| 181 |
+
def rfftfreq(n, d=1.0, device=None):
|
| 182 |
+
"""
|
| 183 |
+
Return the Discrete Fourier Transform sample frequencies
|
| 184 |
+
(for usage with rfft, irfft).
|
| 185 |
+
|
| 186 |
+
The returned float array `f` contains the frequency bin centers in cycles
|
| 187 |
+
per unit of the sample spacing (with zero at the start). For instance, if
|
| 188 |
+
the sample spacing is in seconds, then the frequency unit is cycles/second.
|
| 189 |
+
|
| 190 |
+
Given a window length `n` and a sample spacing `d`::
|
| 191 |
+
|
| 192 |
+
f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even
|
| 193 |
+
f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd
|
| 194 |
+
|
| 195 |
+
Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`)
|
| 196 |
+
the Nyquist frequency component is considered to be positive.
|
| 197 |
+
|
| 198 |
+
Parameters
|
| 199 |
+
----------
|
| 200 |
+
n : int
|
| 201 |
+
Window length.
|
| 202 |
+
d : scalar, optional
|
| 203 |
+
Sample spacing (inverse of the sampling rate). Defaults to 1.
|
| 204 |
+
device : str, optional
|
| 205 |
+
The device on which to place the created array. Default: ``None``.
|
| 206 |
+
For Array-API interoperability only, so must be ``"cpu"`` if passed.
|
| 207 |
+
|
| 208 |
+
.. versionadded:: 2.0.0
|
| 209 |
+
|
| 210 |
+
Returns
|
| 211 |
+
-------
|
| 212 |
+
f : ndarray
|
| 213 |
+
Array of length ``n//2 + 1`` containing the sample frequencies.
|
| 214 |
+
|
| 215 |
+
Examples
|
| 216 |
+
--------
|
| 217 |
+
>>> import numpy as np
|
| 218 |
+
>>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
|
| 219 |
+
>>> fourier = np.fft.rfft(signal)
|
| 220 |
+
>>> n = signal.size
|
| 221 |
+
>>> sample_rate = 100
|
| 222 |
+
>>> freq = np.fft.fftfreq(n, d=1./sample_rate)
|
| 223 |
+
>>> freq
|
| 224 |
+
array([ 0., 10., 20., ..., -30., -20., -10.])
|
| 225 |
+
>>> freq = np.fft.rfftfreq(n, d=1./sample_rate)
|
| 226 |
+
>>> freq
|
| 227 |
+
array([ 0., 10., 20., 30., 40., 50.])
|
| 228 |
+
|
| 229 |
+
"""
|
| 230 |
+
if not isinstance(n, integer_types):
|
| 231 |
+
raise ValueError("n should be an integer")
|
| 232 |
+
val = 1.0/(n*d)
|
| 233 |
+
N = n//2 + 1
|
| 234 |
+
results = arange(0, N, dtype=int, device=device)
|
| 235 |
+
return results * val
|
janus/lib/python3.10/site-packages/numpy/fft/_helper.pyi
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, TypeVar, overload, Literal as L
|
| 2 |
+
|
| 3 |
+
from numpy import generic, integer, floating, complexfloating
|
| 4 |
+
from numpy._typing import (
|
| 5 |
+
NDArray,
|
| 6 |
+
ArrayLike,
|
| 7 |
+
_ShapeLike,
|
| 8 |
+
_ArrayLike,
|
| 9 |
+
_ArrayLikeFloat_co,
|
| 10 |
+
_ArrayLikeComplex_co,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
__all__ = ["fftshift", "ifftshift", "fftfreq", "rfftfreq"]
|
| 14 |
+
|
| 15 |
+
_SCT = TypeVar("_SCT", bound=generic)
|
| 16 |
+
|
| 17 |
+
@overload
|
| 18 |
+
def fftshift(x: _ArrayLike[_SCT], axes: None | _ShapeLike = ...) -> NDArray[_SCT]: ...
|
| 19 |
+
@overload
|
| 20 |
+
def fftshift(x: ArrayLike, axes: None | _ShapeLike = ...) -> NDArray[Any]: ...
|
| 21 |
+
|
| 22 |
+
@overload
|
| 23 |
+
def ifftshift(x: _ArrayLike[_SCT], axes: None | _ShapeLike = ...) -> NDArray[_SCT]: ...
|
| 24 |
+
@overload
|
| 25 |
+
def ifftshift(x: ArrayLike, axes: None | _ShapeLike = ...) -> NDArray[Any]: ...
|
| 26 |
+
|
| 27 |
+
@overload
|
| 28 |
+
def fftfreq(
|
| 29 |
+
n: int | integer[Any],
|
| 30 |
+
d: _ArrayLikeFloat_co = ...,
|
| 31 |
+
device: None | L["cpu"] = ...,
|
| 32 |
+
) -> NDArray[floating[Any]]: ...
|
| 33 |
+
@overload
|
| 34 |
+
def fftfreq(
|
| 35 |
+
n: int | integer[Any],
|
| 36 |
+
d: _ArrayLikeComplex_co = ...,
|
| 37 |
+
device: None | L["cpu"] = ...,
|
| 38 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
| 39 |
+
|
| 40 |
+
@overload
|
| 41 |
+
def rfftfreq(
|
| 42 |
+
n: int | integer[Any],
|
| 43 |
+
d: _ArrayLikeFloat_co = ...,
|
| 44 |
+
device: None | L["cpu"] = ...,
|
| 45 |
+
) -> NDArray[floating[Any]]: ...
|
| 46 |
+
@overload
|
| 47 |
+
def rfftfreq(
|
| 48 |
+
n: int | integer[Any],
|
| 49 |
+
d: _ArrayLikeComplex_co = ...,
|
| 50 |
+
device: None | L["cpu"] = ...,
|
| 51 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
janus/lib/python3.10/site-packages/numpy/fft/_pocketfft.py
ADDED
|
@@ -0,0 +1,1687 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ft(a, n=None, axis=-1, norm="backward")
|
| 9 |
+
irfft(a, n=None, axis=-1, norm="backward")
|
| 10 |
+
hfft(a, n=None, axis=-1, norm="backward")
|
| 11 |
+
ihfft(a, n=None, axis=-1, norm="backward")
|
| 12 |
+
fftn(a, s=None, axes=None, norm="backward")
|
| 13 |
+
ifftn(a, s=None, axes=None, norm="backward")
|
| 14 |
+
rfftn(a, s=None, axes=None, norm="backward")
|
| 15 |
+
irfftn(a, s=None, axes=None, norm="backward")
|
| 16 |
+
fft2(a, s=None, axes=(-2,-1), norm="backward")
|
| 17 |
+
ifft2(a, s=None, axes=(-2, -1), norm="backward")
|
| 18 |
+
rfft2(a, s=None, axes=(-2,-1), norm="backward")
|
| 19 |
+
irfft2(a, s=None, axes=(-2, -1), norm="backward")
|
| 20 |
+
|
| 21 |
+
i = inverse transform
|
| 22 |
+
r = transform of purely real data
|
| 23 |
+
h = Hermite transform
|
| 24 |
+
n = n-dimensional transform
|
| 25 |
+
2 = 2-dimensional transform
|
| 26 |
+
(Note: 2D routines are just nD routines with different default
|
| 27 |
+
behavior.)
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
__all__ = ['fft', 'ifft', 'rfft', 'irfft', 'hfft', 'ihfft', 'rfftn',
|
| 31 |
+
'irfftn', 'rfft2', 'irfft2', 'fft2', 'ifft2', 'fftn', 'ifftn']
|
| 32 |
+
|
| 33 |
+
import functools
|
| 34 |
+
import warnings
|
| 35 |
+
|
| 36 |
+
from numpy.lib.array_utils import normalize_axis_index
|
| 37 |
+
from numpy._core import (asarray, empty_like, result_type,
|
| 38 |
+
conjugate, take, sqrt, reciprocal)
|
| 39 |
+
from . import _pocketfft_umath as pfu
|
| 40 |
+
from numpy._core import overrides
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
array_function_dispatch = functools.partial(
|
| 44 |
+
overrides.array_function_dispatch, module='numpy.fft')
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# `inv_norm` is a float by which the result of the transform needs to be
|
| 48 |
+
# divided. This replaces the original, more intuitive 'fct` parameter to avoid
|
| 49 |
+
# divisions by zero (or alternatively additional checks) in the case of
|
| 50 |
+
# zero-length axes during its computation.
|
| 51 |
+
def _raw_fft(a, n, axis, is_real, is_forward, norm, out=None):
|
| 52 |
+
if n < 1:
|
| 53 |
+
raise ValueError(f"Invalid number of FFT data points ({n}) specified.")
|
| 54 |
+
|
| 55 |
+
# Calculate the normalization factor, passing in the array dtype to
|
| 56 |
+
# avoid precision loss in the possible sqrt or reciprocal.
|
| 57 |
+
if not is_forward:
|
| 58 |
+
norm = _swap_direction(norm)
|
| 59 |
+
|
| 60 |
+
real_dtype = result_type(a.real.dtype, 1.0)
|
| 61 |
+
if norm is None or norm == "backward":
|
| 62 |
+
fct = 1
|
| 63 |
+
elif norm == "ortho":
|
| 64 |
+
fct = reciprocal(sqrt(n, dtype=real_dtype))
|
| 65 |
+
elif norm == "forward":
|
| 66 |
+
fct = reciprocal(n, dtype=real_dtype)
|
| 67 |
+
else:
|
| 68 |
+
raise ValueError(f'Invalid norm value {norm}; should be "backward",'
|
| 69 |
+
'"ortho" or "forward".')
|
| 70 |
+
|
| 71 |
+
n_out = n
|
| 72 |
+
if is_real:
|
| 73 |
+
if is_forward:
|
| 74 |
+
ufunc = pfu.rfft_n_even if n % 2 == 0 else pfu.rfft_n_odd
|
| 75 |
+
n_out = n // 2 + 1
|
| 76 |
+
else:
|
| 77 |
+
ufunc = pfu.irfft
|
| 78 |
+
else:
|
| 79 |
+
ufunc = pfu.fft if is_forward else pfu.ifft
|
| 80 |
+
|
| 81 |
+
axis = normalize_axis_index(axis, a.ndim)
|
| 82 |
+
|
| 83 |
+
if out is None:
|
| 84 |
+
if is_real and not is_forward: # irfft, complex in, real output.
|
| 85 |
+
out_dtype = real_dtype
|
| 86 |
+
else: # Others, complex output.
|
| 87 |
+
out_dtype = result_type(a.dtype, 1j)
|
| 88 |
+
out = empty_like(a, shape=a.shape[:axis] + (n_out,) + a.shape[axis+1:],
|
| 89 |
+
dtype=out_dtype)
|
| 90 |
+
elif ((shape := getattr(out, "shape", None)) is not None
|
| 91 |
+
and (len(shape) != a.ndim or shape[axis] != n_out)):
|
| 92 |
+
raise ValueError("output array has wrong shape.")
|
| 93 |
+
|
| 94 |
+
return ufunc(a, fct, axes=[(axis,), (), (axis,)], out=out)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
_SWAP_DIRECTION_MAP = {"backward": "forward", None: "forward",
|
| 98 |
+
"ortho": "ortho", "forward": "backward"}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _swap_direction(norm):
|
| 102 |
+
try:
|
| 103 |
+
return _SWAP_DIRECTION_MAP[norm]
|
| 104 |
+
except KeyError:
|
| 105 |
+
raise ValueError(f'Invalid norm value {norm}; should be "backward", '
|
| 106 |
+
'"ortho" or "forward".') from None
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _fft_dispatcher(a, n=None, axis=None, norm=None, out=None):
|
| 110 |
+
return (a, out)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@array_function_dispatch(_fft_dispatcher)
|
| 114 |
+
def fft(a, n=None, axis=-1, norm=None, out=None):
|
| 115 |
+
"""
|
| 116 |
+
Compute the one-dimensional discrete Fourier Transform.
|
| 117 |
+
|
| 118 |
+
This function computes the one-dimensional *n*-point discrete Fourier
|
| 119 |
+
Transform (DFT) with the efficient Fast Fourier Transform (FFT)
|
| 120 |
+
algorithm [CT].
|
| 121 |
+
|
| 122 |
+
Parameters
|
| 123 |
+
----------
|
| 124 |
+
a : array_like
|
| 125 |
+
Input array, can be complex.
|
| 126 |
+
n : int, optional
|
| 127 |
+
Length of the transformed axis of the output.
|
| 128 |
+
If `n` is smaller than the length of the input, the input is cropped.
|
| 129 |
+
If it is larger, the input is padded with zeros. If `n` is not given,
|
| 130 |
+
the length of the input along the axis specified by `axis` is used.
|
| 131 |
+
axis : int, optional
|
| 132 |
+
Axis over which to compute the FFT. If not given, the last axis is
|
| 133 |
+
used.
|
| 134 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 135 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 136 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 137 |
+
is scaled and with what normalization factor.
|
| 138 |
+
|
| 139 |
+
.. versionadded:: 1.20.0
|
| 140 |
+
|
| 141 |
+
The "backward", "forward" values were added.
|
| 142 |
+
out : complex ndarray, optional
|
| 143 |
+
If provided, the result will be placed in this array. It should be
|
| 144 |
+
of the appropriate shape and dtype.
|
| 145 |
+
|
| 146 |
+
.. versionadded:: 2.0.0
|
| 147 |
+
|
| 148 |
+
Returns
|
| 149 |
+
-------
|
| 150 |
+
out : complex ndarray
|
| 151 |
+
The truncated or zero-padded input, transformed along the axis
|
| 152 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
| 153 |
+
|
| 154 |
+
Raises
|
| 155 |
+
------
|
| 156 |
+
IndexError
|
| 157 |
+
If `axis` is not a valid axis of `a`.
|
| 158 |
+
|
| 159 |
+
See Also
|
| 160 |
+
--------
|
| 161 |
+
numpy.fft : for definition of the DFT and conventions used.
|
| 162 |
+
ifft : The inverse of `fft`.
|
| 163 |
+
fft2 : The two-dimensional FFT.
|
| 164 |
+
fftn : The *n*-dimensional FFT.
|
| 165 |
+
rfftn : The *n*-dimensional FFT of real input.
|
| 166 |
+
fftfreq : Frequency bins for given FFT parameters.
|
| 167 |
+
|
| 168 |
+
Notes
|
| 169 |
+
-----
|
| 170 |
+
FFT (Fast Fourier Transform) refers to a way the discrete Fourier
|
| 171 |
+
Transform (DFT) can be calculated efficiently, by using symmetries in the
|
| 172 |
+
calculated terms. The symmetry is highest when `n` is a power of 2, and
|
| 173 |
+
the transform is therefore most efficient for these sizes.
|
| 174 |
+
|
| 175 |
+
The DFT is defined, with the conventions used in this implementation, in
|
| 176 |
+
the documentation for the `numpy.fft` module.
|
| 177 |
+
|
| 178 |
+
References
|
| 179 |
+
----------
|
| 180 |
+
.. [CT] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
|
| 181 |
+
machine calculation of complex Fourier series," *Math. Comput.*
|
| 182 |
+
19: 297-301.
|
| 183 |
+
|
| 184 |
+
Examples
|
| 185 |
+
--------
|
| 186 |
+
>>> import numpy as np
|
| 187 |
+
>>> np.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
|
| 188 |
+
array([-2.33486982e-16+1.14423775e-17j, 8.00000000e+00-1.25557246e-15j,
|
| 189 |
+
2.33486982e-16+2.33486982e-16j, 0.00000000e+00+1.22464680e-16j,
|
| 190 |
+
-1.14423775e-17+2.33486982e-16j, 0.00000000e+00+5.20784380e-16j,
|
| 191 |
+
1.14423775e-17+1.14423775e-17j, 0.00000000e+00+1.22464680e-16j])
|
| 192 |
+
|
| 193 |
+
In this example, real input has an FFT which is Hermitian, i.e., symmetric
|
| 194 |
+
in the real part and anti-symmetric in the imaginary part, as described in
|
| 195 |
+
the `numpy.fft` documentation:
|
| 196 |
+
|
| 197 |
+
>>> import matplotlib.pyplot as plt
|
| 198 |
+
>>> t = np.arange(256)
|
| 199 |
+
>>> sp = np.fft.fft(np.sin(t))
|
| 200 |
+
>>> freq = np.fft.fftfreq(t.shape[-1])
|
| 201 |
+
>>> plt.plot(freq, sp.real, freq, sp.imag)
|
| 202 |
+
[<matplotlib.lines.Line2D object at 0x...>, <matplotlib.lines.Line2D object at 0x...>]
|
| 203 |
+
>>> plt.show()
|
| 204 |
+
|
| 205 |
+
"""
|
| 206 |
+
a = asarray(a)
|
| 207 |
+
if n is None:
|
| 208 |
+
n = a.shape[axis]
|
| 209 |
+
output = _raw_fft(a, n, axis, False, True, norm, out)
|
| 210 |
+
return output
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
@array_function_dispatch(_fft_dispatcher)
|
| 214 |
+
def ifft(a, n=None, axis=-1, norm=None, out=None):
|
| 215 |
+
"""
|
| 216 |
+
Compute the one-dimensional inverse discrete Fourier Transform.
|
| 217 |
+
|
| 218 |
+
This function computes the inverse of the one-dimensional *n*-point
|
| 219 |
+
discrete Fourier transform computed by `fft`. In other words,
|
| 220 |
+
``ifft(fft(a)) == a`` to within numerical accuracy.
|
| 221 |
+
For a general description of the algorithm and definitions,
|
| 222 |
+
see `numpy.fft`.
|
| 223 |
+
|
| 224 |
+
The input should be ordered in the same way as is returned by `fft`,
|
| 225 |
+
i.e.,
|
| 226 |
+
|
| 227 |
+
* ``a[0]`` should contain the zero frequency term,
|
| 228 |
+
* ``a[1:n//2]`` should contain the positive-frequency terms,
|
| 229 |
+
* ``a[n//2 + 1:]`` should contain the negative-frequency terms, in
|
| 230 |
+
increasing order starting from the most negative frequency.
|
| 231 |
+
|
| 232 |
+
For an even number of input points, ``A[n//2]`` represents the sum of
|
| 233 |
+
the values at the positive and negative Nyquist frequencies, as the two
|
| 234 |
+
are aliased together. See `numpy.fft` for details.
|
| 235 |
+
|
| 236 |
+
Parameters
|
| 237 |
+
----------
|
| 238 |
+
a : array_like
|
| 239 |
+
Input array, can be complex.
|
| 240 |
+
n : int, optional
|
| 241 |
+
Length of the transformed axis of the output.
|
| 242 |
+
If `n` is smaller than the length of the input, the input is cropped.
|
| 243 |
+
If it is larger, the input is padded with zeros. If `n` is not given,
|
| 244 |
+
the length of the input along the axis specified by `axis` is used.
|
| 245 |
+
See notes about padding issues.
|
| 246 |
+
axis : int, optional
|
| 247 |
+
Axis over which to compute the inverse DFT. If not given, the last
|
| 248 |
+
axis is used.
|
| 249 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 250 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 251 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 252 |
+
is scaled and with what normalization factor.
|
| 253 |
+
|
| 254 |
+
.. versionadded:: 1.20.0
|
| 255 |
+
|
| 256 |
+
The "backward", "forward" values were added.
|
| 257 |
+
|
| 258 |
+
out : complex ndarray, optional
|
| 259 |
+
If provided, the result will be placed in this array. It should be
|
| 260 |
+
of the appropriate shape and dtype.
|
| 261 |
+
|
| 262 |
+
.. versionadded:: 2.0.0
|
| 263 |
+
|
| 264 |
+
Returns
|
| 265 |
+
-------
|
| 266 |
+
out : complex ndarray
|
| 267 |
+
The truncated or zero-padded input, transformed along the axis
|
| 268 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
| 269 |
+
|
| 270 |
+
Raises
|
| 271 |
+
------
|
| 272 |
+
IndexError
|
| 273 |
+
If `axis` is not a valid axis of `a`.
|
| 274 |
+
|
| 275 |
+
See Also
|
| 276 |
+
--------
|
| 277 |
+
numpy.fft : An introduction, with definitions and general explanations.
|
| 278 |
+
fft : The one-dimensional (forward) FFT, of which `ifft` is the inverse
|
| 279 |
+
ifft2 : The two-dimensional inverse FFT.
|
| 280 |
+
ifftn : The n-dimensional inverse FFT.
|
| 281 |
+
|
| 282 |
+
Notes
|
| 283 |
+
-----
|
| 284 |
+
If the input parameter `n` is larger than the size of the input, the input
|
| 285 |
+
is padded by appending zeros at the end. Even though this is the common
|
| 286 |
+
approach, it might lead to surprising results. If a different padding is
|
| 287 |
+
desired, it must be performed before calling `ifft`.
|
| 288 |
+
|
| 289 |
+
Examples
|
| 290 |
+
--------
|
| 291 |
+
>>> import numpy as np
|
| 292 |
+
>>> np.fft.ifft([0, 4, 0, 0])
|
| 293 |
+
array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) # may vary
|
| 294 |
+
|
| 295 |
+
Create and plot a band-limited signal with random phases:
|
| 296 |
+
|
| 297 |
+
>>> import matplotlib.pyplot as plt
|
| 298 |
+
>>> t = np.arange(400)
|
| 299 |
+
>>> n = np.zeros((400,), dtype=complex)
|
| 300 |
+
>>> n[40:60] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20,)))
|
| 301 |
+
>>> s = np.fft.ifft(n)
|
| 302 |
+
>>> plt.plot(t, s.real, label='real')
|
| 303 |
+
[<matplotlib.lines.Line2D object at ...>]
|
| 304 |
+
>>> plt.plot(t, s.imag, '--', label='imaginary')
|
| 305 |
+
[<matplotlib.lines.Line2D object at ...>]
|
| 306 |
+
>>> plt.legend()
|
| 307 |
+
<matplotlib.legend.Legend object at ...>
|
| 308 |
+
>>> plt.show()
|
| 309 |
+
|
| 310 |
+
"""
|
| 311 |
+
a = asarray(a)
|
| 312 |
+
if n is None:
|
| 313 |
+
n = a.shape[axis]
|
| 314 |
+
output = _raw_fft(a, n, axis, False, False, norm, out=out)
|
| 315 |
+
return output
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
@array_function_dispatch(_fft_dispatcher)
|
| 319 |
+
def rfft(a, n=None, axis=-1, norm=None, out=None):
|
| 320 |
+
"""
|
| 321 |
+
Compute the one-dimensional discrete Fourier Transform for real input.
|
| 322 |
+
|
| 323 |
+
This function computes the one-dimensional *n*-point discrete Fourier
|
| 324 |
+
Transform (DFT) of a real-valued array by means of an efficient algorithm
|
| 325 |
+
called the Fast Fourier Transform (FFT).
|
| 326 |
+
|
| 327 |
+
Parameters
|
| 328 |
+
----------
|
| 329 |
+
a : array_like
|
| 330 |
+
Input array
|
| 331 |
+
n : int, optional
|
| 332 |
+
Number of points along transformation axis in the input to use.
|
| 333 |
+
If `n` is smaller than the length of the input, the input is cropped.
|
| 334 |
+
If it is larger, the input is padded with zeros. If `n` is not given,
|
| 335 |
+
the length of the input along the axis specified by `axis` is used.
|
| 336 |
+
axis : int, optional
|
| 337 |
+
Axis over which to compute the FFT. If not given, the last axis is
|
| 338 |
+
used.
|
| 339 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 340 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 341 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 342 |
+
is scaled and with what normalization factor.
|
| 343 |
+
|
| 344 |
+
.. versionadded:: 1.20.0
|
| 345 |
+
|
| 346 |
+
The "backward", "forward" values were added.
|
| 347 |
+
|
| 348 |
+
out : complex ndarray, optional
|
| 349 |
+
If provided, the result will be placed in this array. It should be
|
| 350 |
+
of the appropriate shape and dtype.
|
| 351 |
+
|
| 352 |
+
.. versionadded:: 2.0.0
|
| 353 |
+
|
| 354 |
+
Returns
|
| 355 |
+
-------
|
| 356 |
+
out : complex ndarray
|
| 357 |
+
The truncated or zero-padded input, transformed along the axis
|
| 358 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
| 359 |
+
If `n` is even, the length of the transformed axis is ``(n/2)+1``.
|
| 360 |
+
If `n` is odd, the length is ``(n+1)/2``.
|
| 361 |
+
|
| 362 |
+
Raises
|
| 363 |
+
------
|
| 364 |
+
IndexError
|
| 365 |
+
If `axis` is not a valid axis of `a`.
|
| 366 |
+
|
| 367 |
+
See Also
|
| 368 |
+
--------
|
| 369 |
+
numpy.fft : For definition of the DFT and conventions used.
|
| 370 |
+
irfft : The inverse of `rfft`.
|
| 371 |
+
fft : The one-dimensional FFT of general (complex) input.
|
| 372 |
+
fftn : The *n*-dimensional FFT.
|
| 373 |
+
rfftn : The *n*-dimensional FFT of real input.
|
| 374 |
+
|
| 375 |
+
Notes
|
| 376 |
+
-----
|
| 377 |
+
When the DFT is computed for purely real input, the output is
|
| 378 |
+
Hermitian-symmetric, i.e. the negative frequency terms are just the complex
|
| 379 |
+
conjugates of the corresponding positive-frequency terms, and the
|
| 380 |
+
negative-frequency terms are therefore redundant. This function does not
|
| 381 |
+
compute the negative frequency terms, and the length of the transformed
|
| 382 |
+
axis of the output is therefore ``n//2 + 1``.
|
| 383 |
+
|
| 384 |
+
When ``A = rfft(a)`` and fs is the sampling frequency, ``A[0]`` contains
|
| 385 |
+
the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
|
| 386 |
+
|
| 387 |
+
If `n` is even, ``A[-1]`` contains the term representing both positive
|
| 388 |
+
and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
|
| 389 |
+
real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
|
| 390 |
+
the largest positive frequency (fs/2*(n-1)/n), and is complex in the
|
| 391 |
+
general case.
|
| 392 |
+
|
| 393 |
+
If the input `a` contains an imaginary part, it is silently discarded.
|
| 394 |
+
|
| 395 |
+
Examples
|
| 396 |
+
--------
|
| 397 |
+
>>> import numpy as np
|
| 398 |
+
>>> np.fft.fft([0, 1, 0, 0])
|
| 399 |
+
array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) # may vary
|
| 400 |
+
>>> np.fft.rfft([0, 1, 0, 0])
|
| 401 |
+
array([ 1.+0.j, 0.-1.j, -1.+0.j]) # may vary
|
| 402 |
+
|
| 403 |
+
Notice how the final element of the `fft` output is the complex conjugate
|
| 404 |
+
of the second element, for real input. For `rfft`, this symmetry is
|
| 405 |
+
exploited to compute only the non-negative frequency terms.
|
| 406 |
+
|
| 407 |
+
"""
|
| 408 |
+
a = asarray(a)
|
| 409 |
+
if n is None:
|
| 410 |
+
n = a.shape[axis]
|
| 411 |
+
output = _raw_fft(a, n, axis, True, True, norm, out=out)
|
| 412 |
+
return output
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
@array_function_dispatch(_fft_dispatcher)
|
| 416 |
+
def irfft(a, n=None, axis=-1, norm=None, out=None):
|
| 417 |
+
"""
|
| 418 |
+
Computes the inverse of `rfft`.
|
| 419 |
+
|
| 420 |
+
This function computes the inverse of the one-dimensional *n*-point
|
| 421 |
+
discrete Fourier Transform of real input computed by `rfft`.
|
| 422 |
+
In other words, ``irfft(rfft(a), len(a)) == a`` to within numerical
|
| 423 |
+
accuracy. (See Notes below for why ``len(a)`` is necessary here.)
|
| 424 |
+
|
| 425 |
+
The input is expected to be in the form returned by `rfft`, i.e. the
|
| 426 |
+
real zero-frequency term followed by the complex positive frequency terms
|
| 427 |
+
in order of increasing frequency. Since the discrete Fourier Transform of
|
| 428 |
+
real input is Hermitian-symmetric, the negative frequency terms are taken
|
| 429 |
+
to be the complex conjugates of the corresponding positive frequency terms.
|
| 430 |
+
|
| 431 |
+
Parameters
|
| 432 |
+
----------
|
| 433 |
+
a : array_like
|
| 434 |
+
The input array.
|
| 435 |
+
n : int, optional
|
| 436 |
+
Length of the transformed axis of the output.
|
| 437 |
+
For `n` output points, ``n//2+1`` input points are necessary. If the
|
| 438 |
+
input is longer than this, it is cropped. If it is shorter than this,
|
| 439 |
+
it is padded with zeros. If `n` is not given, it is taken to be
|
| 440 |
+
``2*(m-1)`` where ``m`` is the length of the input along the axis
|
| 441 |
+
specified by `axis`.
|
| 442 |
+
axis : int, optional
|
| 443 |
+
Axis over which to compute the inverse FFT. If not given, the last
|
| 444 |
+
axis is used.
|
| 445 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 446 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 447 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 448 |
+
is scaled and with what normalization factor.
|
| 449 |
+
|
| 450 |
+
.. versionadded:: 1.20.0
|
| 451 |
+
|
| 452 |
+
The "backward", "forward" values were added.
|
| 453 |
+
|
| 454 |
+
out : ndarray, optional
|
| 455 |
+
If provided, the result will be placed in this array. It should be
|
| 456 |
+
of the appropriate shape and dtype.
|
| 457 |
+
|
| 458 |
+
.. versionadded:: 2.0.0
|
| 459 |
+
|
| 460 |
+
Returns
|
| 461 |
+
-------
|
| 462 |
+
out : ndarray
|
| 463 |
+
The truncated or zero-padded input, transformed along the axis
|
| 464 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
| 465 |
+
The length of the transformed axis is `n`, or, if `n` is not given,
|
| 466 |
+
``2*(m-1)`` where ``m`` is the length of the transformed axis of the
|
| 467 |
+
input. To get an odd number of output points, `n` must be specified.
|
| 468 |
+
|
| 469 |
+
Raises
|
| 470 |
+
------
|
| 471 |
+
IndexError
|
| 472 |
+
If `axis` is not a valid axis of `a`.
|
| 473 |
+
|
| 474 |
+
See Also
|
| 475 |
+
--------
|
| 476 |
+
numpy.fft : For definition of the DFT and conventions used.
|
| 477 |
+
rfft : The one-dimensional FFT of real input, of which `irfft` is inverse.
|
| 478 |
+
fft : The one-dimensional FFT.
|
| 479 |
+
irfft2 : The inverse of the two-dimensional FFT of real input.
|
| 480 |
+
irfftn : The inverse of the *n*-dimensional FFT of real input.
|
| 481 |
+
|
| 482 |
+
Notes
|
| 483 |
+
-----
|
| 484 |
+
Returns the real valued `n`-point inverse discrete Fourier transform
|
| 485 |
+
of `a`, where `a` contains the non-negative frequency terms of a
|
| 486 |
+
Hermitian-symmetric sequence. `n` is the length of the result, not the
|
| 487 |
+
input.
|
| 488 |
+
|
| 489 |
+
If you specify an `n` such that `a` must be zero-padded or truncated, the
|
| 490 |
+
extra/removed values will be added/removed at high frequencies. One can
|
| 491 |
+
thus resample a series to `m` points via Fourier interpolation by:
|
| 492 |
+
``a_resamp = irfft(rfft(a), m)``.
|
| 493 |
+
|
| 494 |
+
The correct interpretation of the hermitian input depends on the length of
|
| 495 |
+
the original data, as given by `n`. This is because each input shape could
|
| 496 |
+
correspond to either an odd or even length signal. By default, `irfft`
|
| 497 |
+
assumes an even output length which puts the last entry at the Nyquist
|
| 498 |
+
frequency; aliasing with its symmetric counterpart. By Hermitian symmetry,
|
| 499 |
+
the value is thus treated as purely real. To avoid losing information, the
|
| 500 |
+
correct length of the real input **must** be given.
|
| 501 |
+
|
| 502 |
+
Examples
|
| 503 |
+
--------
|
| 504 |
+
>>> import numpy as np
|
| 505 |
+
>>> np.fft.ifft([1, -1j, -1, 1j])
|
| 506 |
+
array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) # may vary
|
| 507 |
+
>>> np.fft.irfft([1, -1j, -1])
|
| 508 |
+
array([0., 1., 0., 0.])
|
| 509 |
+
|
| 510 |
+
Notice how the last term in the input to the ordinary `ifft` is the
|
| 511 |
+
complex conjugate of the second term, and the output has zero imaginary
|
| 512 |
+
part everywhere. When calling `irfft`, the negative frequencies are not
|
| 513 |
+
specified, and the output array is purely real.
|
| 514 |
+
|
| 515 |
+
"""
|
| 516 |
+
a = asarray(a)
|
| 517 |
+
if n is None:
|
| 518 |
+
n = (a.shape[axis] - 1) * 2
|
| 519 |
+
output = _raw_fft(a, n, axis, True, False, norm, out=out)
|
| 520 |
+
return output
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
@array_function_dispatch(_fft_dispatcher)
|
| 524 |
+
def hfft(a, n=None, axis=-1, norm=None, out=None):
|
| 525 |
+
"""
|
| 526 |
+
Compute the FFT of a signal that has Hermitian symmetry, i.e., a real
|
| 527 |
+
spectrum.
|
| 528 |
+
|
| 529 |
+
Parameters
|
| 530 |
+
----------
|
| 531 |
+
a : array_like
|
| 532 |
+
The input array.
|
| 533 |
+
n : int, optional
|
| 534 |
+
Length of the transformed axis of the output. For `n` output
|
| 535 |
+
points, ``n//2 + 1`` input points are necessary. If the input is
|
| 536 |
+
longer than this, it is cropped. If it is shorter than this, it is
|
| 537 |
+
padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``
|
| 538 |
+
where ``m`` is the length of the input along the axis specified by
|
| 539 |
+
`axis`.
|
| 540 |
+
axis : int, optional
|
| 541 |
+
Axis over which to compute the FFT. If not given, the last
|
| 542 |
+
axis is used.
|
| 543 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 544 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 545 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 546 |
+
is scaled and with what normalization factor.
|
| 547 |
+
|
| 548 |
+
.. versionadded:: 1.20.0
|
| 549 |
+
|
| 550 |
+
The "backward", "forward" values were added.
|
| 551 |
+
|
| 552 |
+
out : ndarray, optional
|
| 553 |
+
If provided, the result will be placed in this array. It should be
|
| 554 |
+
of the appropriate shape and dtype.
|
| 555 |
+
|
| 556 |
+
.. versionadded:: 2.0.0
|
| 557 |
+
|
| 558 |
+
Returns
|
| 559 |
+
-------
|
| 560 |
+
out : ndarray
|
| 561 |
+
The truncated or zero-padded input, transformed along the axis
|
| 562 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
| 563 |
+
The length of the transformed axis is `n`, or, if `n` is not given,
|
| 564 |
+
``2*m - 2`` where ``m`` is the length of the transformed axis of
|
| 565 |
+
the input. To get an odd number of output points, `n` must be
|
| 566 |
+
specified, for instance as ``2*m - 1`` in the typical case,
|
| 567 |
+
|
| 568 |
+
Raises
|
| 569 |
+
------
|
| 570 |
+
IndexError
|
| 571 |
+
If `axis` is not a valid axis of `a`.
|
| 572 |
+
|
| 573 |
+
See also
|
| 574 |
+
--------
|
| 575 |
+
rfft : Compute the one-dimensional FFT for real input.
|
| 576 |
+
ihfft : The inverse of `hfft`.
|
| 577 |
+
|
| 578 |
+
Notes
|
| 579 |
+
-----
|
| 580 |
+
`hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
|
| 581 |
+
opposite case: here the signal has Hermitian symmetry in the time
|
| 582 |
+
domain and is real in the frequency domain. So here it's `hfft` for
|
| 583 |
+
which you must supply the length of the result if it is to be odd.
|
| 584 |
+
|
| 585 |
+
* even: ``ihfft(hfft(a, 2*len(a) - 2)) == a``, within roundoff error,
|
| 586 |
+
* odd: ``ihfft(hfft(a, 2*len(a) - 1)) == a``, within roundoff error.
|
| 587 |
+
|
| 588 |
+
The correct interpretation of the hermitian input depends on the length of
|
| 589 |
+
the original data, as given by `n`. This is because each input shape could
|
| 590 |
+
correspond to either an odd or even length signal. By default, `hfft`
|
| 591 |
+
assumes an even output length which puts the last entry at the Nyquist
|
| 592 |
+
frequency; aliasing with its symmetric counterpart. By Hermitian symmetry,
|
| 593 |
+
the value is thus treated as purely real. To avoid losing information, the
|
| 594 |
+
shape of the full signal **must** be given.
|
| 595 |
+
|
| 596 |
+
Examples
|
| 597 |
+
--------
|
| 598 |
+
>>> import numpy as np
|
| 599 |
+
>>> signal = np.array([1, 2, 3, 4, 3, 2])
|
| 600 |
+
>>> np.fft.fft(signal)
|
| 601 |
+
array([15.+0.j, -4.+0.j, 0.+0.j, -1.-0.j, 0.+0.j, -4.+0.j]) # may vary
|
| 602 |
+
>>> np.fft.hfft(signal[:4]) # Input first half of signal
|
| 603 |
+
array([15., -4., 0., -1., 0., -4.])
|
| 604 |
+
>>> np.fft.hfft(signal, 6) # Input entire signal and truncate
|
| 605 |
+
array([15., -4., 0., -1., 0., -4.])
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
>>> signal = np.array([[1, 1.j], [-1.j, 2]])
|
| 609 |
+
>>> np.conj(signal.T) - signal # check Hermitian symmetry
|
| 610 |
+
array([[ 0.-0.j, -0.+0.j], # may vary
|
| 611 |
+
[ 0.+0.j, 0.-0.j]])
|
| 612 |
+
>>> freq_spectrum = np.fft.hfft(signal)
|
| 613 |
+
>>> freq_spectrum
|
| 614 |
+
array([[ 1., 1.],
|
| 615 |
+
[ 2., -2.]])
|
| 616 |
+
|
| 617 |
+
"""
|
| 618 |
+
a = asarray(a)
|
| 619 |
+
if n is None:
|
| 620 |
+
n = (a.shape[axis] - 1) * 2
|
| 621 |
+
new_norm = _swap_direction(norm)
|
| 622 |
+
output = irfft(conjugate(a), n, axis, norm=new_norm, out=None)
|
| 623 |
+
return output
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
@array_function_dispatch(_fft_dispatcher)
|
| 627 |
+
def ihfft(a, n=None, axis=-1, norm=None, out=None):
|
| 628 |
+
"""
|
| 629 |
+
Compute the inverse FFT of a signal that has Hermitian symmetry.
|
| 630 |
+
|
| 631 |
+
Parameters
|
| 632 |
+
----------
|
| 633 |
+
a : array_like
|
| 634 |
+
Input array.
|
| 635 |
+
n : int, optional
|
| 636 |
+
Length of the inverse FFT, the number of points along
|
| 637 |
+
transformation axis in the input to use. If `n` is smaller than
|
| 638 |
+
the length of the input, the input is cropped. If it is larger,
|
| 639 |
+
the input is padded with zeros. If `n` is not given, the length of
|
| 640 |
+
the input along the axis specified by `axis` is used.
|
| 641 |
+
axis : int, optional
|
| 642 |
+
Axis over which to compute the inverse FFT. If not given, the last
|
| 643 |
+
axis is used.
|
| 644 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 645 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 646 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 647 |
+
is scaled and with what normalization factor.
|
| 648 |
+
|
| 649 |
+
.. versionadded:: 1.20.0
|
| 650 |
+
|
| 651 |
+
The "backward", "forward" values were added.
|
| 652 |
+
|
| 653 |
+
out : complex ndarray, optional
|
| 654 |
+
If provided, the result will be placed in this array. It should be
|
| 655 |
+
of the appropriate shape and dtype.
|
| 656 |
+
|
| 657 |
+
.. versionadded:: 2.0.0
|
| 658 |
+
|
| 659 |
+
Returns
|
| 660 |
+
-------
|
| 661 |
+
out : complex ndarray
|
| 662 |
+
The truncated or zero-padded input, transformed along the axis
|
| 663 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
| 664 |
+
The length of the transformed axis is ``n//2 + 1``.
|
| 665 |
+
|
| 666 |
+
See also
|
| 667 |
+
--------
|
| 668 |
+
hfft, irfft
|
| 669 |
+
|
| 670 |
+
Notes
|
| 671 |
+
-----
|
| 672 |
+
`hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
|
| 673 |
+
opposite case: here the signal has Hermitian symmetry in the time
|
| 674 |
+
domain and is real in the frequency domain. So here it's `hfft` for
|
| 675 |
+
which you must supply the length of the result if it is to be odd:
|
| 676 |
+
|
| 677 |
+
* even: ``ihfft(hfft(a, 2*len(a) - 2)) == a``, within roundoff error,
|
| 678 |
+
* odd: ``ihfft(hfft(a, 2*len(a) - 1)) == a``, within roundoff error.
|
| 679 |
+
|
| 680 |
+
Examples
|
| 681 |
+
--------
|
| 682 |
+
>>> import numpy as np
|
| 683 |
+
>>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
|
| 684 |
+
>>> np.fft.ifft(spectrum)
|
| 685 |
+
array([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.+0.j]) # may vary
|
| 686 |
+
>>> np.fft.ihfft(spectrum)
|
| 687 |
+
array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j]) # may vary
|
| 688 |
+
|
| 689 |
+
"""
|
| 690 |
+
a = asarray(a)
|
| 691 |
+
if n is None:
|
| 692 |
+
n = a.shape[axis]
|
| 693 |
+
new_norm = _swap_direction(norm)
|
| 694 |
+
out = rfft(a, n, axis, norm=new_norm, out=out)
|
| 695 |
+
return conjugate(out, out=out)
|
| 696 |
+
|
| 697 |
+
|
| 698 |
+
def _cook_nd_args(a, s=None, axes=None, invreal=0):
|
| 699 |
+
if s is None:
|
| 700 |
+
shapeless = True
|
| 701 |
+
if axes is None:
|
| 702 |
+
s = list(a.shape)
|
| 703 |
+
else:
|
| 704 |
+
s = take(a.shape, axes)
|
| 705 |
+
else:
|
| 706 |
+
shapeless = False
|
| 707 |
+
s = list(s)
|
| 708 |
+
if axes is None:
|
| 709 |
+
if not shapeless:
|
| 710 |
+
msg = ("`axes` should not be `None` if `s` is not `None` "
|
| 711 |
+
"(Deprecated in NumPy 2.0). In a future version of NumPy, "
|
| 712 |
+
"this will raise an error and `s[i]` will correspond to "
|
| 713 |
+
"the size along the transformed axis specified by "
|
| 714 |
+
"`axes[i]`. To retain current behaviour, pass a sequence "
|
| 715 |
+
"[0, ..., k-1] to `axes` for an array of dimension k.")
|
| 716 |
+
warnings.warn(msg, DeprecationWarning, stacklevel=3)
|
| 717 |
+
axes = list(range(-len(s), 0))
|
| 718 |
+
if len(s) != len(axes):
|
| 719 |
+
raise ValueError("Shape and axes have different lengths.")
|
| 720 |
+
if invreal and shapeless:
|
| 721 |
+
s[-1] = (a.shape[axes[-1]] - 1) * 2
|
| 722 |
+
if None in s:
|
| 723 |
+
msg = ("Passing an array containing `None` values to `s` is "
|
| 724 |
+
"deprecated in NumPy 2.0 and will raise an error in "
|
| 725 |
+
"a future version of NumPy. To use the default behaviour "
|
| 726 |
+
"of the corresponding 1-D transform, pass the value matching "
|
| 727 |
+
"the default for its `n` parameter. To use the default "
|
| 728 |
+
"behaviour for every axis, the `s` argument can be omitted.")
|
| 729 |
+
warnings.warn(msg, DeprecationWarning, stacklevel=3)
|
| 730 |
+
# use the whole input array along axis `i` if `s[i] == -1`
|
| 731 |
+
s = [a.shape[_a] if _s == -1 else _s for _s, _a in zip(s, axes)]
|
| 732 |
+
return s, axes
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
def _raw_fftnd(a, s=None, axes=None, function=fft, norm=None, out=None):
|
| 736 |
+
a = asarray(a)
|
| 737 |
+
s, axes = _cook_nd_args(a, s, axes)
|
| 738 |
+
itl = list(range(len(axes)))
|
| 739 |
+
itl.reverse()
|
| 740 |
+
for ii in itl:
|
| 741 |
+
a = function(a, n=s[ii], axis=axes[ii], norm=norm, out=out)
|
| 742 |
+
return a
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
def _fftn_dispatcher(a, s=None, axes=None, norm=None, out=None):
|
| 746 |
+
return (a, out)
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
@array_function_dispatch(_fftn_dispatcher)
|
| 750 |
+
def fftn(a, s=None, axes=None, norm=None, out=None):
|
| 751 |
+
"""
|
| 752 |
+
Compute the N-dimensional discrete Fourier Transform.
|
| 753 |
+
|
| 754 |
+
This function computes the *N*-dimensional discrete Fourier Transform over
|
| 755 |
+
any number of axes in an *M*-dimensional array by means of the Fast Fourier
|
| 756 |
+
Transform (FFT).
|
| 757 |
+
|
| 758 |
+
Parameters
|
| 759 |
+
----------
|
| 760 |
+
a : array_like
|
| 761 |
+
Input array, can be complex.
|
| 762 |
+
s : sequence of ints, optional
|
| 763 |
+
Shape (length of each transformed axis) of the output
|
| 764 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
|
| 765 |
+
This corresponds to ``n`` for ``fft(x, n)``.
|
| 766 |
+
Along any axis, if the given shape is smaller than that of the input,
|
| 767 |
+
the input is cropped. If it is larger, the input is padded with zeros.
|
| 768 |
+
|
| 769 |
+
.. versionchanged:: 2.0
|
| 770 |
+
|
| 771 |
+
If it is ``-1``, the whole input is used (no padding/trimming).
|
| 772 |
+
|
| 773 |
+
If `s` is not given, the shape of the input along the axes specified
|
| 774 |
+
by `axes` is used.
|
| 775 |
+
|
| 776 |
+
.. deprecated:: 2.0
|
| 777 |
+
|
| 778 |
+
If `s` is not ``None``, `axes` must not be ``None`` either.
|
| 779 |
+
|
| 780 |
+
.. deprecated:: 2.0
|
| 781 |
+
|
| 782 |
+
`s` must contain only ``int`` s, not ``None`` values. ``None``
|
| 783 |
+
values currently mean that the default value for ``n`` is used
|
| 784 |
+
in the corresponding 1-D transform, but this behaviour is
|
| 785 |
+
deprecated.
|
| 786 |
+
|
| 787 |
+
axes : sequence of ints, optional
|
| 788 |
+
Axes over which to compute the FFT. If not given, the last ``len(s)``
|
| 789 |
+
axes are used, or all axes if `s` is also not specified.
|
| 790 |
+
Repeated indices in `axes` means that the transform over that axis is
|
| 791 |
+
performed multiple times.
|
| 792 |
+
|
| 793 |
+
.. deprecated:: 2.0
|
| 794 |
+
|
| 795 |
+
If `s` is specified, the corresponding `axes` to be transformed
|
| 796 |
+
must be explicitly specified too.
|
| 797 |
+
|
| 798 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 799 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 800 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 801 |
+
is scaled and with what normalization factor.
|
| 802 |
+
|
| 803 |
+
.. versionadded:: 1.20.0
|
| 804 |
+
|
| 805 |
+
The "backward", "forward" values were added.
|
| 806 |
+
|
| 807 |
+
out : complex ndarray, optional
|
| 808 |
+
If provided, the result will be placed in this array. It should be
|
| 809 |
+
of the appropriate shape and dtype for all axes (and hence is
|
| 810 |
+
incompatible with passing in all but the trivial ``s``).
|
| 811 |
+
|
| 812 |
+
.. versionadded:: 2.0.0
|
| 813 |
+
|
| 814 |
+
Returns
|
| 815 |
+
-------
|
| 816 |
+
out : complex ndarray
|
| 817 |
+
The truncated or zero-padded input, transformed along the axes
|
| 818 |
+
indicated by `axes`, or by a combination of `s` and `a`,
|
| 819 |
+
as explained in the parameters section above.
|
| 820 |
+
|
| 821 |
+
Raises
|
| 822 |
+
------
|
| 823 |
+
ValueError
|
| 824 |
+
If `s` and `axes` have different length.
|
| 825 |
+
IndexError
|
| 826 |
+
If an element of `axes` is larger than than the number of axes of `a`.
|
| 827 |
+
|
| 828 |
+
See Also
|
| 829 |
+
--------
|
| 830 |
+
numpy.fft : Overall view of discrete Fourier transforms, with definitions
|
| 831 |
+
and conventions used.
|
| 832 |
+
ifftn : The inverse of `fftn`, the inverse *n*-dimensional FFT.
|
| 833 |
+
fft : The one-dimensional FFT, with definitions and conventions used.
|
| 834 |
+
rfftn : The *n*-dimensional FFT of real input.
|
| 835 |
+
fft2 : The two-dimensional FFT.
|
| 836 |
+
fftshift : Shifts zero-frequency terms to centre of array
|
| 837 |
+
|
| 838 |
+
Notes
|
| 839 |
+
-----
|
| 840 |
+
The output, analogously to `fft`, contains the term for zero frequency in
|
| 841 |
+
the low-order corner of all axes, the positive frequency terms in the
|
| 842 |
+
first half of all axes, the term for the Nyquist frequency in the middle
|
| 843 |
+
of all axes and the negative frequency terms in the second half of all
|
| 844 |
+
axes, in order of decreasingly negative frequency.
|
| 845 |
+
|
| 846 |
+
See `numpy.fft` for details, definitions and conventions used.
|
| 847 |
+
|
| 848 |
+
Examples
|
| 849 |
+
--------
|
| 850 |
+
>>> import numpy as np
|
| 851 |
+
>>> a = np.mgrid[:3, :3, :3][0]
|
| 852 |
+
>>> np.fft.fftn(a, axes=(1, 2))
|
| 853 |
+
array([[[ 0.+0.j, 0.+0.j, 0.+0.j], # may vary
|
| 854 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j],
|
| 855 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j]],
|
| 856 |
+
[[ 9.+0.j, 0.+0.j, 0.+0.j],
|
| 857 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j],
|
| 858 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j]],
|
| 859 |
+
[[18.+0.j, 0.+0.j, 0.+0.j],
|
| 860 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j],
|
| 861 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j]]])
|
| 862 |
+
>>> np.fft.fftn(a, (2, 2), axes=(0, 1))
|
| 863 |
+
array([[[ 2.+0.j, 2.+0.j, 2.+0.j], # may vary
|
| 864 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j]],
|
| 865 |
+
[[-2.+0.j, -2.+0.j, -2.+0.j],
|
| 866 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j]]])
|
| 867 |
+
|
| 868 |
+
>>> import matplotlib.pyplot as plt
|
| 869 |
+
>>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
|
| 870 |
+
... 2 * np.pi * np.arange(200) / 34)
|
| 871 |
+
>>> S = np.sin(X) + np.cos(Y) + np.random.uniform(0, 1, X.shape)
|
| 872 |
+
>>> FS = np.fft.fftn(S)
|
| 873 |
+
>>> plt.imshow(np.log(np.abs(np.fft.fftshift(FS))**2))
|
| 874 |
+
<matplotlib.image.AxesImage object at 0x...>
|
| 875 |
+
>>> plt.show()
|
| 876 |
+
|
| 877 |
+
"""
|
| 878 |
+
return _raw_fftnd(a, s, axes, fft, norm, out=out)
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
@array_function_dispatch(_fftn_dispatcher)
|
| 882 |
+
def ifftn(a, s=None, axes=None, norm=None, out=None):
|
| 883 |
+
"""
|
| 884 |
+
Compute the N-dimensional inverse discrete Fourier Transform.
|
| 885 |
+
|
| 886 |
+
This function computes the inverse of the N-dimensional discrete
|
| 887 |
+
Fourier Transform over any number of axes in an M-dimensional array by
|
| 888 |
+
means of the Fast Fourier Transform (FFT). In other words,
|
| 889 |
+
``ifftn(fftn(a)) == a`` to within numerical accuracy.
|
| 890 |
+
For a description of the definitions and conventions used, see `numpy.fft`.
|
| 891 |
+
|
| 892 |
+
The input, analogously to `ifft`, should be ordered in the same way as is
|
| 893 |
+
returned by `fftn`, i.e. it should have the term for zero frequency
|
| 894 |
+
in all axes in the low-order corner, the positive frequency terms in the
|
| 895 |
+
first half of all axes, the term for the Nyquist frequency in the middle
|
| 896 |
+
of all axes and the negative frequency terms in the second half of all
|
| 897 |
+
axes, in order of decreasingly negative frequency.
|
| 898 |
+
|
| 899 |
+
Parameters
|
| 900 |
+
----------
|
| 901 |
+
a : array_like
|
| 902 |
+
Input array, can be complex.
|
| 903 |
+
s : sequence of ints, optional
|
| 904 |
+
Shape (length of each transformed axis) of the output
|
| 905 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
|
| 906 |
+
This corresponds to ``n`` for ``ifft(x, n)``.
|
| 907 |
+
Along any axis, if the given shape is smaller than that of the input,
|
| 908 |
+
the input is cropped. If it is larger, the input is padded with zeros.
|
| 909 |
+
|
| 910 |
+
.. versionchanged:: 2.0
|
| 911 |
+
|
| 912 |
+
If it is ``-1``, the whole input is used (no padding/trimming).
|
| 913 |
+
|
| 914 |
+
If `s` is not given, the shape of the input along the axes specified
|
| 915 |
+
by `axes` is used. See notes for issue on `ifft` zero padding.
|
| 916 |
+
|
| 917 |
+
.. deprecated:: 2.0
|
| 918 |
+
|
| 919 |
+
If `s` is not ``None``, `axes` must not be ``None`` either.
|
| 920 |
+
|
| 921 |
+
.. deprecated:: 2.0
|
| 922 |
+
|
| 923 |
+
`s` must contain only ``int`` s, not ``None`` values. ``None``
|
| 924 |
+
values currently mean that the default value for ``n`` is used
|
| 925 |
+
in the corresponding 1-D transform, but this behaviour is
|
| 926 |
+
deprecated.
|
| 927 |
+
|
| 928 |
+
axes : sequence of ints, optional
|
| 929 |
+
Axes over which to compute the IFFT. If not given, the last ``len(s)``
|
| 930 |
+
axes are used, or all axes if `s` is also not specified.
|
| 931 |
+
Repeated indices in `axes` means that the inverse transform over that
|
| 932 |
+
axis is performed multiple times.
|
| 933 |
+
|
| 934 |
+
.. deprecated:: 2.0
|
| 935 |
+
|
| 936 |
+
If `s` is specified, the corresponding `axes` to be transformed
|
| 937 |
+
must be explicitly specified too.
|
| 938 |
+
|
| 939 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 940 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 941 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 942 |
+
is scaled and with what normalization factor.
|
| 943 |
+
|
| 944 |
+
.. versionadded:: 1.20.0
|
| 945 |
+
|
| 946 |
+
The "backward", "forward" values were added.
|
| 947 |
+
|
| 948 |
+
out : complex ndarray, optional
|
| 949 |
+
If provided, the result will be placed in this array. It should be
|
| 950 |
+
of the appropriate shape and dtype for all axes (and hence is
|
| 951 |
+
incompatible with passing in all but the trivial ``s``).
|
| 952 |
+
|
| 953 |
+
.. versionadded:: 2.0.0
|
| 954 |
+
|
| 955 |
+
Returns
|
| 956 |
+
-------
|
| 957 |
+
out : complex ndarray
|
| 958 |
+
The truncated or zero-padded input, transformed along the axes
|
| 959 |
+
indicated by `axes`, or by a combination of `s` or `a`,
|
| 960 |
+
as explained in the parameters section above.
|
| 961 |
+
|
| 962 |
+
Raises
|
| 963 |
+
------
|
| 964 |
+
ValueError
|
| 965 |
+
If `s` and `axes` have different length.
|
| 966 |
+
IndexError
|
| 967 |
+
If an element of `axes` is larger than than the number of axes of `a`.
|
| 968 |
+
|
| 969 |
+
See Also
|
| 970 |
+
--------
|
| 971 |
+
numpy.fft : Overall view of discrete Fourier transforms, with definitions
|
| 972 |
+
and conventions used.
|
| 973 |
+
fftn : The forward *n*-dimensional FFT, of which `ifftn` is the inverse.
|
| 974 |
+
ifft : The one-dimensional inverse FFT.
|
| 975 |
+
ifft2 : The two-dimensional inverse FFT.
|
| 976 |
+
ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning
|
| 977 |
+
of array.
|
| 978 |
+
|
| 979 |
+
Notes
|
| 980 |
+
-----
|
| 981 |
+
See `numpy.fft` for definitions and conventions used.
|
| 982 |
+
|
| 983 |
+
Zero-padding, analogously with `ifft`, is performed by appending zeros to
|
| 984 |
+
the input along the specified dimension. Although this is the common
|
| 985 |
+
approach, it might lead to surprising results. If another form of zero
|
| 986 |
+
padding is desired, it must be performed before `ifftn` is called.
|
| 987 |
+
|
| 988 |
+
Examples
|
| 989 |
+
--------
|
| 990 |
+
>>> import numpy as np
|
| 991 |
+
>>> a = np.eye(4)
|
| 992 |
+
>>> np.fft.ifftn(np.fft.fftn(a, axes=(0,)), axes=(1,))
|
| 993 |
+
array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary
|
| 994 |
+
[0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j],
|
| 995 |
+
[0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
|
| 996 |
+
[0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]])
|
| 997 |
+
|
| 998 |
+
|
| 999 |
+
Create and plot an image with band-limited frequency content:
|
| 1000 |
+
|
| 1001 |
+
>>> import matplotlib.pyplot as plt
|
| 1002 |
+
>>> n = np.zeros((200,200), dtype=complex)
|
| 1003 |
+
>>> n[60:80, 20:40] = np.exp(1j*np.random.uniform(0, 2*np.pi, (20, 20)))
|
| 1004 |
+
>>> im = np.fft.ifftn(n).real
|
| 1005 |
+
>>> plt.imshow(im)
|
| 1006 |
+
<matplotlib.image.AxesImage object at 0x...>
|
| 1007 |
+
>>> plt.show()
|
| 1008 |
+
|
| 1009 |
+
"""
|
| 1010 |
+
return _raw_fftnd(a, s, axes, ifft, norm, out=out)
|
| 1011 |
+
|
| 1012 |
+
|
| 1013 |
+
@array_function_dispatch(_fftn_dispatcher)
|
| 1014 |
+
def fft2(a, s=None, axes=(-2, -1), norm=None, out=None):
|
| 1015 |
+
"""
|
| 1016 |
+
Compute the 2-dimensional discrete Fourier Transform.
|
| 1017 |
+
|
| 1018 |
+
This function computes the *n*-dimensional discrete Fourier Transform
|
| 1019 |
+
over any axes in an *M*-dimensional array by means of the
|
| 1020 |
+
Fast Fourier Transform (FFT). By default, the transform is computed over
|
| 1021 |
+
the last two axes of the input array, i.e., a 2-dimensional FFT.
|
| 1022 |
+
|
| 1023 |
+
Parameters
|
| 1024 |
+
----------
|
| 1025 |
+
a : array_like
|
| 1026 |
+
Input array, can be complex
|
| 1027 |
+
s : sequence of ints, optional
|
| 1028 |
+
Shape (length of each transformed axis) of the output
|
| 1029 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
|
| 1030 |
+
This corresponds to ``n`` for ``fft(x, n)``.
|
| 1031 |
+
Along each axis, if the given shape is smaller than that of the input,
|
| 1032 |
+
the input is cropped. If it is larger, the input is padded with zeros.
|
| 1033 |
+
|
| 1034 |
+
.. versionchanged:: 2.0
|
| 1035 |
+
|
| 1036 |
+
If it is ``-1``, the whole input is used (no padding/trimming).
|
| 1037 |
+
|
| 1038 |
+
If `s` is not given, the shape of the input along the axes specified
|
| 1039 |
+
by `axes` is used.
|
| 1040 |
+
|
| 1041 |
+
.. deprecated:: 2.0
|
| 1042 |
+
|
| 1043 |
+
If `s` is not ``None``, `axes` must not be ``None`` either.
|
| 1044 |
+
|
| 1045 |
+
.. deprecated:: 2.0
|
| 1046 |
+
|
| 1047 |
+
`s` must contain only ``int`` s, not ``None`` values. ``None``
|
| 1048 |
+
values currently mean that the default value for ``n`` is used
|
| 1049 |
+
in the corresponding 1-D transform, but this behaviour is
|
| 1050 |
+
deprecated.
|
| 1051 |
+
|
| 1052 |
+
axes : sequence of ints, optional
|
| 1053 |
+
Axes over which to compute the FFT. If not given, the last two
|
| 1054 |
+
axes are used. A repeated index in `axes` means the transform over
|
| 1055 |
+
that axis is performed multiple times. A one-element sequence means
|
| 1056 |
+
that a one-dimensional FFT is performed. Default: ``(-2, -1)``.
|
| 1057 |
+
|
| 1058 |
+
.. deprecated:: 2.0
|
| 1059 |
+
|
| 1060 |
+
If `s` is specified, the corresponding `axes` to be transformed
|
| 1061 |
+
must not be ``None``.
|
| 1062 |
+
|
| 1063 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 1064 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 1065 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 1066 |
+
is scaled and with what normalization factor.
|
| 1067 |
+
|
| 1068 |
+
.. versionadded:: 1.20.0
|
| 1069 |
+
|
| 1070 |
+
The "backward", "forward" values were added.
|
| 1071 |
+
|
| 1072 |
+
out : complex ndarray, optional
|
| 1073 |
+
If provided, the result will be placed in this array. It should be
|
| 1074 |
+
of the appropriate shape and dtype for all axes (and hence only the
|
| 1075 |
+
last axis can have ``s`` not equal to the shape at that axis).
|
| 1076 |
+
|
| 1077 |
+
.. versionadded:: 2.0.0
|
| 1078 |
+
|
| 1079 |
+
Returns
|
| 1080 |
+
-------
|
| 1081 |
+
out : complex ndarray
|
| 1082 |
+
The truncated or zero-padded input, transformed along the axes
|
| 1083 |
+
indicated by `axes`, or the last two axes if `axes` is not given.
|
| 1084 |
+
|
| 1085 |
+
Raises
|
| 1086 |
+
------
|
| 1087 |
+
ValueError
|
| 1088 |
+
If `s` and `axes` have different length, or `axes` not given and
|
| 1089 |
+
``len(s) != 2``.
|
| 1090 |
+
IndexError
|
| 1091 |
+
If an element of `axes` is larger than than the number of axes of `a`.
|
| 1092 |
+
|
| 1093 |
+
See Also
|
| 1094 |
+
--------
|
| 1095 |
+
numpy.fft : Overall view of discrete Fourier transforms, with definitions
|
| 1096 |
+
and conventions used.
|
| 1097 |
+
ifft2 : The inverse two-dimensional FFT.
|
| 1098 |
+
fft : The one-dimensional FFT.
|
| 1099 |
+
fftn : The *n*-dimensional FFT.
|
| 1100 |
+
fftshift : Shifts zero-frequency terms to the center of the array.
|
| 1101 |
+
For two-dimensional input, swaps first and third quadrants, and second
|
| 1102 |
+
and fourth quadrants.
|
| 1103 |
+
|
| 1104 |
+
Notes
|
| 1105 |
+
-----
|
| 1106 |
+
`fft2` is just `fftn` with a different default for `axes`.
|
| 1107 |
+
|
| 1108 |
+
The output, analogously to `fft`, contains the term for zero frequency in
|
| 1109 |
+
the low-order corner of the transformed axes, the positive frequency terms
|
| 1110 |
+
in the first half of these axes, the term for the Nyquist frequency in the
|
| 1111 |
+
middle of the axes and the negative frequency terms in the second half of
|
| 1112 |
+
the axes, in order of decreasingly negative frequency.
|
| 1113 |
+
|
| 1114 |
+
See `fftn` for details and a plotting example, and `numpy.fft` for
|
| 1115 |
+
definitions and conventions used.
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
Examples
|
| 1119 |
+
--------
|
| 1120 |
+
>>> import numpy as np
|
| 1121 |
+
>>> a = np.mgrid[:5, :5][0]
|
| 1122 |
+
>>> np.fft.fft2(a)
|
| 1123 |
+
array([[ 50. +0.j , 0. +0.j , 0. +0.j , # may vary
|
| 1124 |
+
0. +0.j , 0. +0.j ],
|
| 1125 |
+
[-12.5+17.20477401j, 0. +0.j , 0. +0.j ,
|
| 1126 |
+
0. +0.j , 0. +0.j ],
|
| 1127 |
+
[-12.5 +4.0614962j , 0. +0.j , 0. +0.j ,
|
| 1128 |
+
0. +0.j , 0. +0.j ],
|
| 1129 |
+
[-12.5 -4.0614962j , 0. +0.j , 0. +0.j ,
|
| 1130 |
+
0. +0.j , 0. +0.j ],
|
| 1131 |
+
[-12.5-17.20477401j, 0. +0.j , 0. +0.j ,
|
| 1132 |
+
0. +0.j , 0. +0.j ]])
|
| 1133 |
+
|
| 1134 |
+
"""
|
| 1135 |
+
return _raw_fftnd(a, s, axes, fft, norm, out=out)
|
| 1136 |
+
|
| 1137 |
+
|
| 1138 |
+
@array_function_dispatch(_fftn_dispatcher)
|
| 1139 |
+
def ifft2(a, s=None, axes=(-2, -1), norm=None, out=None):
|
| 1140 |
+
"""
|
| 1141 |
+
Compute the 2-dimensional inverse discrete Fourier Transform.
|
| 1142 |
+
|
| 1143 |
+
This function computes the inverse of the 2-dimensional discrete Fourier
|
| 1144 |
+
Transform over any number of axes in an M-dimensional array by means of
|
| 1145 |
+
the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(a)) == a``
|
| 1146 |
+
to within numerical accuracy. By default, the inverse transform is
|
| 1147 |
+
computed over the last two axes of the input array.
|
| 1148 |
+
|
| 1149 |
+
The input, analogously to `ifft`, should be ordered in the same way as is
|
| 1150 |
+
returned by `fft2`, i.e. it should have the term for zero frequency
|
| 1151 |
+
in the low-order corner of the two axes, the positive frequency terms in
|
| 1152 |
+
the first half of these axes, the term for the Nyquist frequency in the
|
| 1153 |
+
middle of the axes and the negative frequency terms in the second half of
|
| 1154 |
+
both axes, in order of decreasingly negative frequency.
|
| 1155 |
+
|
| 1156 |
+
Parameters
|
| 1157 |
+
----------
|
| 1158 |
+
a : array_like
|
| 1159 |
+
Input array, can be complex.
|
| 1160 |
+
s : sequence of ints, optional
|
| 1161 |
+
Shape (length of each axis) of the output (``s[0]`` refers to axis 0,
|
| 1162 |
+
``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``.
|
| 1163 |
+
Along each axis, if the given shape is smaller than that of the input,
|
| 1164 |
+
the input is cropped. If it is larger, the input is padded with zeros.
|
| 1165 |
+
|
| 1166 |
+
.. versionchanged:: 2.0
|
| 1167 |
+
|
| 1168 |
+
If it is ``-1``, the whole input is used (no padding/trimming).
|
| 1169 |
+
|
| 1170 |
+
If `s` is not given, the shape of the input along the axes specified
|
| 1171 |
+
by `axes` is used. See notes for issue on `ifft` zero padding.
|
| 1172 |
+
|
| 1173 |
+
.. deprecated:: 2.0
|
| 1174 |
+
|
| 1175 |
+
If `s` is not ``None``, `axes` must not be ``None`` either.
|
| 1176 |
+
|
| 1177 |
+
.. deprecated:: 2.0
|
| 1178 |
+
|
| 1179 |
+
`s` must contain only ``int`` s, not ``None`` values. ``None``
|
| 1180 |
+
values currently mean that the default value for ``n`` is used
|
| 1181 |
+
in the corresponding 1-D transform, but this behaviour is
|
| 1182 |
+
deprecated.
|
| 1183 |
+
|
| 1184 |
+
axes : sequence of ints, optional
|
| 1185 |
+
Axes over which to compute the FFT. If not given, the last two
|
| 1186 |
+
axes are used. A repeated index in `axes` means the transform over
|
| 1187 |
+
that axis is performed multiple times. A one-element sequence means
|
| 1188 |
+
that a one-dimensional FFT is performed. Default: ``(-2, -1)``.
|
| 1189 |
+
|
| 1190 |
+
.. deprecated:: 2.0
|
| 1191 |
+
|
| 1192 |
+
If `s` is specified, the corresponding `axes` to be transformed
|
| 1193 |
+
must not be ``None``.
|
| 1194 |
+
|
| 1195 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 1196 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 1197 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 1198 |
+
is scaled and with what normalization factor.
|
| 1199 |
+
|
| 1200 |
+
.. versionadded:: 1.20.0
|
| 1201 |
+
|
| 1202 |
+
The "backward", "forward" values were added.
|
| 1203 |
+
|
| 1204 |
+
out : complex ndarray, optional
|
| 1205 |
+
If provided, the result will be placed in this array. It should be
|
| 1206 |
+
of the appropriate shape and dtype for all axes (and hence is
|
| 1207 |
+
incompatible with passing in all but the trivial ``s``).
|
| 1208 |
+
|
| 1209 |
+
.. versionadded:: 2.0.0
|
| 1210 |
+
|
| 1211 |
+
Returns
|
| 1212 |
+
-------
|
| 1213 |
+
out : complex ndarray
|
| 1214 |
+
The truncated or zero-padded input, transformed along the axes
|
| 1215 |
+
indicated by `axes`, or the last two axes if `axes` is not given.
|
| 1216 |
+
|
| 1217 |
+
Raises
|
| 1218 |
+
------
|
| 1219 |
+
ValueError
|
| 1220 |
+
If `s` and `axes` have different length, or `axes` not given and
|
| 1221 |
+
``len(s) != 2``.
|
| 1222 |
+
IndexError
|
| 1223 |
+
If an element of `axes` is larger than than the number of axes of `a`.
|
| 1224 |
+
|
| 1225 |
+
See Also
|
| 1226 |
+
--------
|
| 1227 |
+
numpy.fft : Overall view of discrete Fourier transforms, with definitions
|
| 1228 |
+
and conventions used.
|
| 1229 |
+
fft2 : The forward 2-dimensional FFT, of which `ifft2` is the inverse.
|
| 1230 |
+
ifftn : The inverse of the *n*-dimensional FFT.
|
| 1231 |
+
fft : The one-dimensional FFT.
|
| 1232 |
+
ifft : The one-dimensional inverse FFT.
|
| 1233 |
+
|
| 1234 |
+
Notes
|
| 1235 |
+
-----
|
| 1236 |
+
`ifft2` is just `ifftn` with a different default for `axes`.
|
| 1237 |
+
|
| 1238 |
+
See `ifftn` for details and a plotting example, and `numpy.fft` for
|
| 1239 |
+
definition and conventions used.
|
| 1240 |
+
|
| 1241 |
+
Zero-padding, analogously with `ifft`, is performed by appending zeros to
|
| 1242 |
+
the input along the specified dimension. Although this is the common
|
| 1243 |
+
approach, it might lead to surprising results. If another form of zero
|
| 1244 |
+
padding is desired, it must be performed before `ifft2` is called.
|
| 1245 |
+
|
| 1246 |
+
Examples
|
| 1247 |
+
--------
|
| 1248 |
+
>>> import numpy as np
|
| 1249 |
+
>>> a = 4 * np.eye(4)
|
| 1250 |
+
>>> np.fft.ifft2(a)
|
| 1251 |
+
array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary
|
| 1252 |
+
[0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j],
|
| 1253 |
+
[0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
|
| 1254 |
+
[0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]])
|
| 1255 |
+
|
| 1256 |
+
"""
|
| 1257 |
+
return _raw_fftnd(a, s, axes, ifft, norm, out=None)
|
| 1258 |
+
|
| 1259 |
+
|
| 1260 |
+
@array_function_dispatch(_fftn_dispatcher)
|
| 1261 |
+
def rfftn(a, s=None, axes=None, norm=None, out=None):
|
| 1262 |
+
"""
|
| 1263 |
+
Compute the N-dimensional discrete Fourier Transform for real input.
|
| 1264 |
+
|
| 1265 |
+
This function computes the N-dimensional discrete Fourier Transform over
|
| 1266 |
+
any number of axes in an M-dimensional real array by means of the Fast
|
| 1267 |
+
Fourier Transform (FFT). By default, all axes are transformed, with the
|
| 1268 |
+
real transform performed over the last axis, while the remaining
|
| 1269 |
+
transforms are complex.
|
| 1270 |
+
|
| 1271 |
+
Parameters
|
| 1272 |
+
----------
|
| 1273 |
+
a : array_like
|
| 1274 |
+
Input array, taken to be real.
|
| 1275 |
+
s : sequence of ints, optional
|
| 1276 |
+
Shape (length along each transformed axis) to use from the input.
|
| 1277 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
|
| 1278 |
+
The final element of `s` corresponds to `n` for ``rfft(x, n)``, while
|
| 1279 |
+
for the remaining axes, it corresponds to `n` for ``fft(x, n)``.
|
| 1280 |
+
Along any axis, if the given shape is smaller than that of the input,
|
| 1281 |
+
the input is cropped. If it is larger, the input is padded with zeros.
|
| 1282 |
+
|
| 1283 |
+
.. versionchanged:: 2.0
|
| 1284 |
+
|
| 1285 |
+
If it is ``-1``, the whole input is used (no padding/trimming).
|
| 1286 |
+
|
| 1287 |
+
If `s` is not given, the shape of the input along the axes specified
|
| 1288 |
+
by `axes` is used.
|
| 1289 |
+
|
| 1290 |
+
.. deprecated:: 2.0
|
| 1291 |
+
|
| 1292 |
+
If `s` is not ``None``, `axes` must not be ``None`` either.
|
| 1293 |
+
|
| 1294 |
+
.. deprecated:: 2.0
|
| 1295 |
+
|
| 1296 |
+
`s` must contain only ``int`` s, not ``None`` values. ``None``
|
| 1297 |
+
values currently mean that the default value for ``n`` is used
|
| 1298 |
+
in the corresponding 1-D transform, but this behaviour is
|
| 1299 |
+
deprecated.
|
| 1300 |
+
|
| 1301 |
+
axes : sequence of ints, optional
|
| 1302 |
+
Axes over which to compute the FFT. If not given, the last ``len(s)``
|
| 1303 |
+
axes are used, or all axes if `s` is also not specified.
|
| 1304 |
+
|
| 1305 |
+
.. deprecated:: 2.0
|
| 1306 |
+
|
| 1307 |
+
If `s` is specified, the corresponding `axes` to be transformed
|
| 1308 |
+
must be explicitly specified too.
|
| 1309 |
+
|
| 1310 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 1311 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 1312 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 1313 |
+
is scaled and with what normalization factor.
|
| 1314 |
+
|
| 1315 |
+
.. versionadded:: 1.20.0
|
| 1316 |
+
|
| 1317 |
+
The "backward", "forward" values were added.
|
| 1318 |
+
|
| 1319 |
+
out : complex ndarray, optional
|
| 1320 |
+
If provided, the result will be placed in this array. It should be
|
| 1321 |
+
of the appropriate shape and dtype for all axes (and hence is
|
| 1322 |
+
incompatible with passing in all but the trivial ``s``).
|
| 1323 |
+
|
| 1324 |
+
.. versionadded:: 2.0.0
|
| 1325 |
+
|
| 1326 |
+
Returns
|
| 1327 |
+
-------
|
| 1328 |
+
out : complex ndarray
|
| 1329 |
+
The truncated or zero-padded input, transformed along the axes
|
| 1330 |
+
indicated by `axes`, or by a combination of `s` and `a`,
|
| 1331 |
+
as explained in the parameters section above.
|
| 1332 |
+
The length of the last axis transformed will be ``s[-1]//2+1``,
|
| 1333 |
+
while the remaining transformed axes will have lengths according to
|
| 1334 |
+
`s`, or unchanged from the input.
|
| 1335 |
+
|
| 1336 |
+
Raises
|
| 1337 |
+
------
|
| 1338 |
+
ValueError
|
| 1339 |
+
If `s` and `axes` have different length.
|
| 1340 |
+
IndexError
|
| 1341 |
+
If an element of `axes` is larger than than the number of axes of `a`.
|
| 1342 |
+
|
| 1343 |
+
See Also
|
| 1344 |
+
--------
|
| 1345 |
+
irfftn : The inverse of `rfftn`, i.e. the inverse of the n-dimensional FFT
|
| 1346 |
+
of real input.
|
| 1347 |
+
fft : The one-dimensional FFT, with definitions and conventions used.
|
| 1348 |
+
rfft : The one-dimensional FFT of real input.
|
| 1349 |
+
fftn : The n-dimensional FFT.
|
| 1350 |
+
rfft2 : The two-dimensional FFT of real input.
|
| 1351 |
+
|
| 1352 |
+
Notes
|
| 1353 |
+
-----
|
| 1354 |
+
The transform for real input is performed over the last transformation
|
| 1355 |
+
axis, as by `rfft`, then the transform over the remaining axes is
|
| 1356 |
+
performed as by `fftn`. The order of the output is as for `rfft` for the
|
| 1357 |
+
final transformation axis, and as for `fftn` for the remaining
|
| 1358 |
+
transformation axes.
|
| 1359 |
+
|
| 1360 |
+
See `fft` for details, definitions and conventions used.
|
| 1361 |
+
|
| 1362 |
+
Examples
|
| 1363 |
+
--------
|
| 1364 |
+
>>> import numpy as np
|
| 1365 |
+
>>> a = np.ones((2, 2, 2))
|
| 1366 |
+
>>> np.fft.rfftn(a)
|
| 1367 |
+
array([[[8.+0.j, 0.+0.j], # may vary
|
| 1368 |
+
[0.+0.j, 0.+0.j]],
|
| 1369 |
+
[[0.+0.j, 0.+0.j],
|
| 1370 |
+
[0.+0.j, 0.+0.j]]])
|
| 1371 |
+
|
| 1372 |
+
>>> np.fft.rfftn(a, axes=(2, 0))
|
| 1373 |
+
array([[[4.+0.j, 0.+0.j], # may vary
|
| 1374 |
+
[4.+0.j, 0.+0.j]],
|
| 1375 |
+
[[0.+0.j, 0.+0.j],
|
| 1376 |
+
[0.+0.j, 0.+0.j]]])
|
| 1377 |
+
|
| 1378 |
+
"""
|
| 1379 |
+
a = asarray(a)
|
| 1380 |
+
s, axes = _cook_nd_args(a, s, axes)
|
| 1381 |
+
a = rfft(a, s[-1], axes[-1], norm, out=out)
|
| 1382 |
+
for ii in range(len(axes)-2, -1, -1):
|
| 1383 |
+
a = fft(a, s[ii], axes[ii], norm, out=out)
|
| 1384 |
+
return a
|
| 1385 |
+
|
| 1386 |
+
|
| 1387 |
+
@array_function_dispatch(_fftn_dispatcher)
|
| 1388 |
+
def rfft2(a, s=None, axes=(-2, -1), norm=None, out=None):
|
| 1389 |
+
"""
|
| 1390 |
+
Compute the 2-dimensional FFT of a real array.
|
| 1391 |
+
|
| 1392 |
+
Parameters
|
| 1393 |
+
----------
|
| 1394 |
+
a : array
|
| 1395 |
+
Input array, taken to be real.
|
| 1396 |
+
s : sequence of ints, optional
|
| 1397 |
+
Shape of the FFT.
|
| 1398 |
+
|
| 1399 |
+
.. versionchanged:: 2.0
|
| 1400 |
+
|
| 1401 |
+
If it is ``-1``, the whole input is used (no padding/trimming).
|
| 1402 |
+
|
| 1403 |
+
.. deprecated:: 2.0
|
| 1404 |
+
|
| 1405 |
+
If `s` is not ``None``, `axes` must not be ``None`` either.
|
| 1406 |
+
|
| 1407 |
+
.. deprecated:: 2.0
|
| 1408 |
+
|
| 1409 |
+
`s` must contain only ``int`` s, not ``None`` values. ``None``
|
| 1410 |
+
values currently mean that the default value for ``n`` is used
|
| 1411 |
+
in the corresponding 1-D transform, but this behaviour is
|
| 1412 |
+
deprecated.
|
| 1413 |
+
|
| 1414 |
+
axes : sequence of ints, optional
|
| 1415 |
+
Axes over which to compute the FFT. Default: ``(-2, -1)``.
|
| 1416 |
+
|
| 1417 |
+
.. deprecated:: 2.0
|
| 1418 |
+
|
| 1419 |
+
If `s` is specified, the corresponding `axes` to be transformed
|
| 1420 |
+
must not be ``None``.
|
| 1421 |
+
|
| 1422 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 1423 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 1424 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 1425 |
+
is scaled and with what normalization factor.
|
| 1426 |
+
|
| 1427 |
+
.. versionadded:: 1.20.0
|
| 1428 |
+
|
| 1429 |
+
The "backward", "forward" values were added.
|
| 1430 |
+
|
| 1431 |
+
out : complex ndarray, optional
|
| 1432 |
+
If provided, the result will be placed in this array. It should be
|
| 1433 |
+
of the appropriate shape and dtype for the last inverse transform.
|
| 1434 |
+
incompatible with passing in all but the trivial ``s``).
|
| 1435 |
+
|
| 1436 |
+
.. versionadded:: 2.0.0
|
| 1437 |
+
|
| 1438 |
+
Returns
|
| 1439 |
+
-------
|
| 1440 |
+
out : ndarray
|
| 1441 |
+
The result of the real 2-D FFT.
|
| 1442 |
+
|
| 1443 |
+
See Also
|
| 1444 |
+
--------
|
| 1445 |
+
rfftn : Compute the N-dimensional discrete Fourier Transform for real
|
| 1446 |
+
input.
|
| 1447 |
+
|
| 1448 |
+
Notes
|
| 1449 |
+
-----
|
| 1450 |
+
This is really just `rfftn` with different default behavior.
|
| 1451 |
+
For more details see `rfftn`.
|
| 1452 |
+
|
| 1453 |
+
Examples
|
| 1454 |
+
--------
|
| 1455 |
+
>>> import numpy as np
|
| 1456 |
+
>>> a = np.mgrid[:5, :5][0]
|
| 1457 |
+
>>> np.fft.rfft2(a)
|
| 1458 |
+
array([[ 50. +0.j , 0. +0.j , 0. +0.j ],
|
| 1459 |
+
[-12.5+17.20477401j, 0. +0.j , 0. +0.j ],
|
| 1460 |
+
[-12.5 +4.0614962j , 0. +0.j , 0. +0.j ],
|
| 1461 |
+
[-12.5 -4.0614962j , 0. +0.j , 0. +0.j ],
|
| 1462 |
+
[-12.5-17.20477401j, 0. +0.j , 0. +0.j ]])
|
| 1463 |
+
"""
|
| 1464 |
+
return rfftn(a, s, axes, norm, out=out)
|
| 1465 |
+
|
| 1466 |
+
|
| 1467 |
+
@array_function_dispatch(_fftn_dispatcher)
|
| 1468 |
+
def irfftn(a, s=None, axes=None, norm=None, out=None):
|
| 1469 |
+
"""
|
| 1470 |
+
Computes the inverse of `rfftn`.
|
| 1471 |
+
|
| 1472 |
+
This function computes the inverse of the N-dimensional discrete
|
| 1473 |
+
Fourier Transform for real input over any number of axes in an
|
| 1474 |
+
M-dimensional array by means of the Fast Fourier Transform (FFT). In
|
| 1475 |
+
other words, ``irfftn(rfftn(a), a.shape) == a`` to within numerical
|
| 1476 |
+
accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,
|
| 1477 |
+
and for the same reason.)
|
| 1478 |
+
|
| 1479 |
+
The input should be ordered in the same way as is returned by `rfftn`,
|
| 1480 |
+
i.e. as for `irfft` for the final transformation axis, and as for `ifftn`
|
| 1481 |
+
along all the other axes.
|
| 1482 |
+
|
| 1483 |
+
Parameters
|
| 1484 |
+
----------
|
| 1485 |
+
a : array_like
|
| 1486 |
+
Input array.
|
| 1487 |
+
s : sequence of ints, optional
|
| 1488 |
+
Shape (length of each transformed axis) of the output
|
| 1489 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
|
| 1490 |
+
number of input points used along this axis, except for the last axis,
|
| 1491 |
+
where ``s[-1]//2+1`` points of the input are used.
|
| 1492 |
+
Along any axis, if the shape indicated by `s` is smaller than that of
|
| 1493 |
+
the input, the input is cropped. If it is larger, the input is padded
|
| 1494 |
+
with zeros.
|
| 1495 |
+
|
| 1496 |
+
.. versionchanged:: 2.0
|
| 1497 |
+
|
| 1498 |
+
If it is ``-1``, the whole input is used (no padding/trimming).
|
| 1499 |
+
|
| 1500 |
+
If `s` is not given, the shape of the input along the axes
|
| 1501 |
+
specified by axes is used. Except for the last axis which is taken to
|
| 1502 |
+
be ``2*(m-1)`` where ``m`` is the length of the input along that axis.
|
| 1503 |
+
|
| 1504 |
+
.. deprecated:: 2.0
|
| 1505 |
+
|
| 1506 |
+
If `s` is not ``None``, `axes` must not be ``None`` either.
|
| 1507 |
+
|
| 1508 |
+
.. deprecated:: 2.0
|
| 1509 |
+
|
| 1510 |
+
`s` must contain only ``int`` s, not ``None`` values. ``None``
|
| 1511 |
+
values currently mean that the default value for ``n`` is used
|
| 1512 |
+
in the corresponding 1-D transform, but this behaviour is
|
| 1513 |
+
deprecated.
|
| 1514 |
+
|
| 1515 |
+
axes : sequence of ints, optional
|
| 1516 |
+
Axes over which to compute the inverse FFT. If not given, the last
|
| 1517 |
+
`len(s)` axes are used, or all axes if `s` is also not specified.
|
| 1518 |
+
Repeated indices in `axes` means that the inverse transform over that
|
| 1519 |
+
axis is performed multiple times.
|
| 1520 |
+
|
| 1521 |
+
.. deprecated:: 2.0
|
| 1522 |
+
|
| 1523 |
+
If `s` is specified, the corresponding `axes` to be transformed
|
| 1524 |
+
must be explicitly specified too.
|
| 1525 |
+
|
| 1526 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 1527 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 1528 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 1529 |
+
is scaled and with what normalization factor.
|
| 1530 |
+
|
| 1531 |
+
.. versionadded:: 1.20.0
|
| 1532 |
+
|
| 1533 |
+
The "backward", "forward" values were added.
|
| 1534 |
+
|
| 1535 |
+
out : ndarray, optional
|
| 1536 |
+
If provided, the result will be placed in this array. It should be
|
| 1537 |
+
of the appropriate shape and dtype for the last transformation.
|
| 1538 |
+
|
| 1539 |
+
.. versionadded:: 2.0.0
|
| 1540 |
+
|
| 1541 |
+
Returns
|
| 1542 |
+
-------
|
| 1543 |
+
out : ndarray
|
| 1544 |
+
The truncated or zero-padded input, transformed along the axes
|
| 1545 |
+
indicated by `axes`, or by a combination of `s` or `a`,
|
| 1546 |
+
as explained in the parameters section above.
|
| 1547 |
+
The length of each transformed axis is as given by the corresponding
|
| 1548 |
+
element of `s`, or the length of the input in every axis except for the
|
| 1549 |
+
last one if `s` is not given. In the final transformed axis the length
|
| 1550 |
+
of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the
|
| 1551 |
+
length of the final transformed axis of the input. To get an odd
|
| 1552 |
+
number of output points in the final axis, `s` must be specified.
|
| 1553 |
+
|
| 1554 |
+
Raises
|
| 1555 |
+
------
|
| 1556 |
+
ValueError
|
| 1557 |
+
If `s` and `axes` have different length.
|
| 1558 |
+
IndexError
|
| 1559 |
+
If an element of `axes` is larger than than the number of axes of `a`.
|
| 1560 |
+
|
| 1561 |
+
See Also
|
| 1562 |
+
--------
|
| 1563 |
+
rfftn : The forward n-dimensional FFT of real input,
|
| 1564 |
+
of which `ifftn` is the inverse.
|
| 1565 |
+
fft : The one-dimensional FFT, with definitions and conventions used.
|
| 1566 |
+
irfft : The inverse of the one-dimensional FFT of real input.
|
| 1567 |
+
irfft2 : The inverse of the two-dimensional FFT of real input.
|
| 1568 |
+
|
| 1569 |
+
Notes
|
| 1570 |
+
-----
|
| 1571 |
+
See `fft` for definitions and conventions used.
|
| 1572 |
+
|
| 1573 |
+
See `rfft` for definitions and conventions used for real input.
|
| 1574 |
+
|
| 1575 |
+
The correct interpretation of the hermitian input depends on the shape of
|
| 1576 |
+
the original data, as given by `s`. This is because each input shape could
|
| 1577 |
+
correspond to either an odd or even length signal. By default, `irfftn`
|
| 1578 |
+
assumes an even output length which puts the last entry at the Nyquist
|
| 1579 |
+
frequency; aliasing with its symmetric counterpart. When performing the
|
| 1580 |
+
final complex to real transform, the last value is thus treated as purely
|
| 1581 |
+
real. To avoid losing information, the correct shape of the real input
|
| 1582 |
+
**must** be given.
|
| 1583 |
+
|
| 1584 |
+
Examples
|
| 1585 |
+
--------
|
| 1586 |
+
>>> import numpy as np
|
| 1587 |
+
>>> a = np.zeros((3, 2, 2))
|
| 1588 |
+
>>> a[0, 0, 0] = 3 * 2 * 2
|
| 1589 |
+
>>> np.fft.irfftn(a)
|
| 1590 |
+
array([[[1., 1.],
|
| 1591 |
+
[1., 1.]],
|
| 1592 |
+
[[1., 1.],
|
| 1593 |
+
[1., 1.]],
|
| 1594 |
+
[[1., 1.],
|
| 1595 |
+
[1., 1.]]])
|
| 1596 |
+
|
| 1597 |
+
"""
|
| 1598 |
+
a = asarray(a)
|
| 1599 |
+
s, axes = _cook_nd_args(a, s, axes, invreal=1)
|
| 1600 |
+
for ii in range(len(axes)-1):
|
| 1601 |
+
a = ifft(a, s[ii], axes[ii], norm)
|
| 1602 |
+
a = irfft(a, s[-1], axes[-1], norm, out=out)
|
| 1603 |
+
return a
|
| 1604 |
+
|
| 1605 |
+
|
| 1606 |
+
@array_function_dispatch(_fftn_dispatcher)
|
| 1607 |
+
def irfft2(a, s=None, axes=(-2, -1), norm=None, out=None):
|
| 1608 |
+
"""
|
| 1609 |
+
Computes the inverse of `rfft2`.
|
| 1610 |
+
|
| 1611 |
+
Parameters
|
| 1612 |
+
----------
|
| 1613 |
+
a : array_like
|
| 1614 |
+
The input array
|
| 1615 |
+
s : sequence of ints, optional
|
| 1616 |
+
Shape of the real output to the inverse FFT.
|
| 1617 |
+
|
| 1618 |
+
.. versionchanged:: 2.0
|
| 1619 |
+
|
| 1620 |
+
If it is ``-1``, the whole input is used (no padding/trimming).
|
| 1621 |
+
|
| 1622 |
+
.. deprecated:: 2.0
|
| 1623 |
+
|
| 1624 |
+
If `s` is not ``None``, `axes` must not be ``None`` either.
|
| 1625 |
+
|
| 1626 |
+
.. deprecated:: 2.0
|
| 1627 |
+
|
| 1628 |
+
`s` must contain only ``int`` s, not ``None`` values. ``None``
|
| 1629 |
+
values currently mean that the default value for ``n`` is used
|
| 1630 |
+
in the corresponding 1-D transform, but this behaviour is
|
| 1631 |
+
deprecated.
|
| 1632 |
+
|
| 1633 |
+
axes : sequence of ints, optional
|
| 1634 |
+
The axes over which to compute the inverse fft.
|
| 1635 |
+
Default: ``(-2, -1)``, the last two axes.
|
| 1636 |
+
|
| 1637 |
+
.. deprecated:: 2.0
|
| 1638 |
+
|
| 1639 |
+
If `s` is specified, the corresponding `axes` to be transformed
|
| 1640 |
+
must not be ``None``.
|
| 1641 |
+
|
| 1642 |
+
norm : {"backward", "ortho", "forward"}, optional
|
| 1643 |
+
Normalization mode (see `numpy.fft`). Default is "backward".
|
| 1644 |
+
Indicates which direction of the forward/backward pair of transforms
|
| 1645 |
+
is scaled and with what normalization factor.
|
| 1646 |
+
|
| 1647 |
+
.. versionadded:: 1.20.0
|
| 1648 |
+
|
| 1649 |
+
The "backward", "forward" values were added.
|
| 1650 |
+
|
| 1651 |
+
out : ndarray, optional
|
| 1652 |
+
If provided, the result will be placed in this array. It should be
|
| 1653 |
+
of the appropriate shape and dtype for the last transformation.
|
| 1654 |
+
|
| 1655 |
+
.. versionadded:: 2.0.0
|
| 1656 |
+
|
| 1657 |
+
Returns
|
| 1658 |
+
-------
|
| 1659 |
+
out : ndarray
|
| 1660 |
+
The result of the inverse real 2-D FFT.
|
| 1661 |
+
|
| 1662 |
+
See Also
|
| 1663 |
+
--------
|
| 1664 |
+
rfft2 : The forward two-dimensional FFT of real input,
|
| 1665 |
+
of which `irfft2` is the inverse.
|
| 1666 |
+
rfft : The one-dimensional FFT for real input.
|
| 1667 |
+
irfft : The inverse of the one-dimensional FFT of real input.
|
| 1668 |
+
irfftn : Compute the inverse of the N-dimensional FFT of real input.
|
| 1669 |
+
|
| 1670 |
+
Notes
|
| 1671 |
+
-----
|
| 1672 |
+
This is really `irfftn` with different defaults.
|
| 1673 |
+
For more details see `irfftn`.
|
| 1674 |
+
|
| 1675 |
+
Examples
|
| 1676 |
+
--------
|
| 1677 |
+
>>> import numpy as np
|
| 1678 |
+
>>> a = np.mgrid[:5, :5][0]
|
| 1679 |
+
>>> A = np.fft.rfft2(a)
|
| 1680 |
+
>>> np.fft.irfft2(A, s=a.shape)
|
| 1681 |
+
array([[0., 0., 0., 0., 0.],
|
| 1682 |
+
[1., 1., 1., 1., 1.],
|
| 1683 |
+
[2., 2., 2., 2., 2.],
|
| 1684 |
+
[3., 3., 3., 3., 3.],
|
| 1685 |
+
[4., 4., 4., 4., 4.]])
|
| 1686 |
+
"""
|
| 1687 |
+
return irfftn(a, s, axes, norm, out=None)
|
janus/lib/python3.10/site-packages/numpy/fft/_pocketfft.pyi
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Sequence
|
| 2 |
+
from typing import Literal as L, TypeAlias
|
| 3 |
+
|
| 4 |
+
from numpy import complex128, float64
|
| 5 |
+
from numpy._typing import ArrayLike, NDArray, _ArrayLikeNumber_co
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"fft",
|
| 9 |
+
"ifft",
|
| 10 |
+
"rfft",
|
| 11 |
+
"irfft",
|
| 12 |
+
"hfft",
|
| 13 |
+
"ihfft",
|
| 14 |
+
"rfftn",
|
| 15 |
+
"irfftn",
|
| 16 |
+
"rfft2",
|
| 17 |
+
"irfft2",
|
| 18 |
+
"fft2",
|
| 19 |
+
"ifft2",
|
| 20 |
+
"fftn",
|
| 21 |
+
"ifftn",
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
_NormKind: TypeAlias = L[None, "backward", "ortho", "forward"]
|
| 25 |
+
|
| 26 |
+
def fft(
|
| 27 |
+
a: ArrayLike,
|
| 28 |
+
n: None | int = ...,
|
| 29 |
+
axis: int = ...,
|
| 30 |
+
norm: _NormKind = ...,
|
| 31 |
+
out: None | NDArray[complex128] = ...,
|
| 32 |
+
) -> NDArray[complex128]: ...
|
| 33 |
+
|
| 34 |
+
def ifft(
|
| 35 |
+
a: ArrayLike,
|
| 36 |
+
n: None | int = ...,
|
| 37 |
+
axis: int = ...,
|
| 38 |
+
norm: _NormKind = ...,
|
| 39 |
+
out: None | NDArray[complex128] = ...,
|
| 40 |
+
) -> NDArray[complex128]: ...
|
| 41 |
+
|
| 42 |
+
def rfft(
|
| 43 |
+
a: ArrayLike,
|
| 44 |
+
n: None | int = ...,
|
| 45 |
+
axis: int = ...,
|
| 46 |
+
norm: _NormKind = ...,
|
| 47 |
+
out: None | NDArray[complex128] = ...,
|
| 48 |
+
) -> NDArray[complex128]: ...
|
| 49 |
+
|
| 50 |
+
def irfft(
|
| 51 |
+
a: ArrayLike,
|
| 52 |
+
n: None | int = ...,
|
| 53 |
+
axis: int = ...,
|
| 54 |
+
norm: _NormKind = ...,
|
| 55 |
+
out: None | NDArray[float64] = ...,
|
| 56 |
+
) -> NDArray[float64]: ...
|
| 57 |
+
|
| 58 |
+
# Input array must be compatible with `np.conjugate`
|
| 59 |
+
def hfft(
|
| 60 |
+
a: _ArrayLikeNumber_co,
|
| 61 |
+
n: None | int = ...,
|
| 62 |
+
axis: int = ...,
|
| 63 |
+
norm: _NormKind = ...,
|
| 64 |
+
out: None | NDArray[float64] = ...,
|
| 65 |
+
) -> NDArray[float64]: ...
|
| 66 |
+
|
| 67 |
+
def ihfft(
|
| 68 |
+
a: ArrayLike,
|
| 69 |
+
n: None | int = ...,
|
| 70 |
+
axis: int = ...,
|
| 71 |
+
norm: _NormKind = ...,
|
| 72 |
+
out: None | NDArray[complex128] = ...,
|
| 73 |
+
) -> NDArray[complex128]: ...
|
| 74 |
+
|
| 75 |
+
def fftn(
|
| 76 |
+
a: ArrayLike,
|
| 77 |
+
s: None | Sequence[int] = ...,
|
| 78 |
+
axes: None | Sequence[int] = ...,
|
| 79 |
+
norm: _NormKind = ...,
|
| 80 |
+
out: None | NDArray[complex128] = ...,
|
| 81 |
+
) -> NDArray[complex128]: ...
|
| 82 |
+
|
| 83 |
+
def ifftn(
|
| 84 |
+
a: ArrayLike,
|
| 85 |
+
s: None | Sequence[int] = ...,
|
| 86 |
+
axes: None | Sequence[int] = ...,
|
| 87 |
+
norm: _NormKind = ...,
|
| 88 |
+
out: None | NDArray[complex128] = ...,
|
| 89 |
+
) -> NDArray[complex128]: ...
|
| 90 |
+
|
| 91 |
+
def rfftn(
|
| 92 |
+
a: ArrayLike,
|
| 93 |
+
s: None | Sequence[int] = ...,
|
| 94 |
+
axes: None | Sequence[int] = ...,
|
| 95 |
+
norm: _NormKind = ...,
|
| 96 |
+
out: None | NDArray[complex128] = ...,
|
| 97 |
+
) -> NDArray[complex128]: ...
|
| 98 |
+
|
| 99 |
+
def irfftn(
|
| 100 |
+
a: ArrayLike,
|
| 101 |
+
s: None | Sequence[int] = ...,
|
| 102 |
+
axes: None | Sequence[int] = ...,
|
| 103 |
+
norm: _NormKind = ...,
|
| 104 |
+
out: None | NDArray[float64] = ...,
|
| 105 |
+
) -> NDArray[float64]: ...
|
| 106 |
+
|
| 107 |
+
def fft2(
|
| 108 |
+
a: ArrayLike,
|
| 109 |
+
s: None | Sequence[int] = ...,
|
| 110 |
+
axes: None | Sequence[int] = ...,
|
| 111 |
+
norm: _NormKind = ...,
|
| 112 |
+
out: None | NDArray[complex128] = ...,
|
| 113 |
+
) -> NDArray[complex128]: ...
|
| 114 |
+
|
| 115 |
+
def ifft2(
|
| 116 |
+
a: ArrayLike,
|
| 117 |
+
s: None | Sequence[int] = ...,
|
| 118 |
+
axes: None | Sequence[int] = ...,
|
| 119 |
+
norm: _NormKind = ...,
|
| 120 |
+
out: None | NDArray[complex128] = ...,
|
| 121 |
+
) -> NDArray[complex128]: ...
|
| 122 |
+
|
| 123 |
+
def rfft2(
|
| 124 |
+
a: ArrayLike,
|
| 125 |
+
s: None | Sequence[int] = ...,
|
| 126 |
+
axes: None | Sequence[int] = ...,
|
| 127 |
+
norm: _NormKind = ...,
|
| 128 |
+
out: None | NDArray[complex128] = ...,
|
| 129 |
+
) -> NDArray[complex128]: ...
|
| 130 |
+
|
| 131 |
+
def irfft2(
|
| 132 |
+
a: ArrayLike,
|
| 133 |
+
s: None | Sequence[int] = ...,
|
| 134 |
+
axes: None | Sequence[int] = ...,
|
| 135 |
+
norm: _NormKind = ...,
|
| 136 |
+
out: None | NDArray[float64] = ...,
|
| 137 |
+
) -> NDArray[float64]: ...
|
janus/lib/python3.10/site-packages/numpy/fft/helper.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(attr_name):
|
| 2 |
+
import warnings
|
| 3 |
+
from numpy.fft import _helper
|
| 4 |
+
ret = getattr(_helper, attr_name, None)
|
| 5 |
+
if ret is None:
|
| 6 |
+
raise AttributeError(
|
| 7 |
+
f"module 'numpy.fft.helper' has no attribute {attr_name}")
|
| 8 |
+
warnings.warn(
|
| 9 |
+
"The numpy.fft.helper has been made private and renamed to "
|
| 10 |
+
"numpy.fft._helper. All four functions exported by it (i.e. fftshift, "
|
| 11 |
+
"ifftshift, fftfreq, rfftfreq) are available from numpy.fft. "
|
| 12 |
+
f"Please use numpy.fft.{attr_name} instead.",
|
| 13 |
+
DeprecationWarning,
|
| 14 |
+
stacklevel=3
|
| 15 |
+
)
|
| 16 |
+
return ret
|
janus/lib/python3.10/site-packages/numpy/fft/tests/__init__.py
ADDED
|
File without changes
|
janus/lib/python3.10/site-packages/numpy/fft/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (166 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/fft/tests/__pycache__/test_helper.cpython-310.pyc
ADDED
|
Binary file (5.06 kB). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/fft/tests/__pycache__/test_pocketfft.cpython-310.pyc
ADDED
|
Binary file (20.4 kB). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/fft/tests/test_helper.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test functions for fftpack.helper module
|
| 2 |
+
|
| 3 |
+
Copied from fftpack.helper by Pearu Peterson, October 2005
|
| 4 |
+
|
| 5 |
+
"""
|
| 6 |
+
import numpy as np
|
| 7 |
+
from numpy.testing import assert_array_almost_equal
|
| 8 |
+
from numpy import fft, pi
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class TestFFTShift:
|
| 12 |
+
|
| 13 |
+
def test_definition(self):
|
| 14 |
+
x = [0, 1, 2, 3, 4, -4, -3, -2, -1]
|
| 15 |
+
y = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
|
| 16 |
+
assert_array_almost_equal(fft.fftshift(x), y)
|
| 17 |
+
assert_array_almost_equal(fft.ifftshift(y), x)
|
| 18 |
+
x = [0, 1, 2, 3, 4, -5, -4, -3, -2, -1]
|
| 19 |
+
y = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
|
| 20 |
+
assert_array_almost_equal(fft.fftshift(x), y)
|
| 21 |
+
assert_array_almost_equal(fft.ifftshift(y), x)
|
| 22 |
+
|
| 23 |
+
def test_inverse(self):
|
| 24 |
+
for n in [1, 4, 9, 100, 211]:
|
| 25 |
+
x = np.random.random((n,))
|
| 26 |
+
assert_array_almost_equal(fft.ifftshift(fft.fftshift(x)), x)
|
| 27 |
+
|
| 28 |
+
def test_axes_keyword(self):
|
| 29 |
+
freqs = [[0, 1, 2], [3, 4, -4], [-3, -2, -1]]
|
| 30 |
+
shifted = [[-1, -3, -2], [2, 0, 1], [-4, 3, 4]]
|
| 31 |
+
assert_array_almost_equal(fft.fftshift(freqs, axes=(0, 1)), shifted)
|
| 32 |
+
assert_array_almost_equal(fft.fftshift(freqs, axes=0),
|
| 33 |
+
fft.fftshift(freqs, axes=(0,)))
|
| 34 |
+
assert_array_almost_equal(fft.ifftshift(shifted, axes=(0, 1)), freqs)
|
| 35 |
+
assert_array_almost_equal(fft.ifftshift(shifted, axes=0),
|
| 36 |
+
fft.ifftshift(shifted, axes=(0,)))
|
| 37 |
+
|
| 38 |
+
assert_array_almost_equal(fft.fftshift(freqs), shifted)
|
| 39 |
+
assert_array_almost_equal(fft.ifftshift(shifted), freqs)
|
| 40 |
+
|
| 41 |
+
def test_uneven_dims(self):
|
| 42 |
+
""" Test 2D input, which has uneven dimension sizes """
|
| 43 |
+
freqs = [
|
| 44 |
+
[0, 1],
|
| 45 |
+
[2, 3],
|
| 46 |
+
[4, 5]
|
| 47 |
+
]
|
| 48 |
+
|
| 49 |
+
# shift in dimension 0
|
| 50 |
+
shift_dim0 = [
|
| 51 |
+
[4, 5],
|
| 52 |
+
[0, 1],
|
| 53 |
+
[2, 3]
|
| 54 |
+
]
|
| 55 |
+
assert_array_almost_equal(fft.fftshift(freqs, axes=0), shift_dim0)
|
| 56 |
+
assert_array_almost_equal(fft.ifftshift(shift_dim0, axes=0), freqs)
|
| 57 |
+
assert_array_almost_equal(fft.fftshift(freqs, axes=(0,)), shift_dim0)
|
| 58 |
+
assert_array_almost_equal(fft.ifftshift(shift_dim0, axes=[0]), freqs)
|
| 59 |
+
|
| 60 |
+
# shift in dimension 1
|
| 61 |
+
shift_dim1 = [
|
| 62 |
+
[1, 0],
|
| 63 |
+
[3, 2],
|
| 64 |
+
[5, 4]
|
| 65 |
+
]
|
| 66 |
+
assert_array_almost_equal(fft.fftshift(freqs, axes=1), shift_dim1)
|
| 67 |
+
assert_array_almost_equal(fft.ifftshift(shift_dim1, axes=1), freqs)
|
| 68 |
+
|
| 69 |
+
# shift in both dimensions
|
| 70 |
+
shift_dim_both = [
|
| 71 |
+
[5, 4],
|
| 72 |
+
[1, 0],
|
| 73 |
+
[3, 2]
|
| 74 |
+
]
|
| 75 |
+
assert_array_almost_equal(fft.fftshift(freqs, axes=(0, 1)), shift_dim_both)
|
| 76 |
+
assert_array_almost_equal(fft.ifftshift(shift_dim_both, axes=(0, 1)), freqs)
|
| 77 |
+
assert_array_almost_equal(fft.fftshift(freqs, axes=[0, 1]), shift_dim_both)
|
| 78 |
+
assert_array_almost_equal(fft.ifftshift(shift_dim_both, axes=[0, 1]), freqs)
|
| 79 |
+
|
| 80 |
+
# axes=None (default) shift in all dimensions
|
| 81 |
+
assert_array_almost_equal(fft.fftshift(freqs, axes=None), shift_dim_both)
|
| 82 |
+
assert_array_almost_equal(fft.ifftshift(shift_dim_both, axes=None), freqs)
|
| 83 |
+
assert_array_almost_equal(fft.fftshift(freqs), shift_dim_both)
|
| 84 |
+
assert_array_almost_equal(fft.ifftshift(shift_dim_both), freqs)
|
| 85 |
+
|
| 86 |
+
def test_equal_to_original(self):
|
| 87 |
+
""" Test that the new (>=v1.15) implementation (see #10073) is equal to the original (<=v1.14) """
|
| 88 |
+
from numpy._core import asarray, concatenate, arange, take
|
| 89 |
+
|
| 90 |
+
def original_fftshift(x, axes=None):
|
| 91 |
+
""" How fftshift was implemented in v1.14"""
|
| 92 |
+
tmp = asarray(x)
|
| 93 |
+
ndim = tmp.ndim
|
| 94 |
+
if axes is None:
|
| 95 |
+
axes = list(range(ndim))
|
| 96 |
+
elif isinstance(axes, int):
|
| 97 |
+
axes = (axes,)
|
| 98 |
+
y = tmp
|
| 99 |
+
for k in axes:
|
| 100 |
+
n = tmp.shape[k]
|
| 101 |
+
p2 = (n + 1) // 2
|
| 102 |
+
mylist = concatenate((arange(p2, n), arange(p2)))
|
| 103 |
+
y = take(y, mylist, k)
|
| 104 |
+
return y
|
| 105 |
+
|
| 106 |
+
def original_ifftshift(x, axes=None):
|
| 107 |
+
""" How ifftshift was implemented in v1.14 """
|
| 108 |
+
tmp = asarray(x)
|
| 109 |
+
ndim = tmp.ndim
|
| 110 |
+
if axes is None:
|
| 111 |
+
axes = list(range(ndim))
|
| 112 |
+
elif isinstance(axes, int):
|
| 113 |
+
axes = (axes,)
|
| 114 |
+
y = tmp
|
| 115 |
+
for k in axes:
|
| 116 |
+
n = tmp.shape[k]
|
| 117 |
+
p2 = n - (n + 1) // 2
|
| 118 |
+
mylist = concatenate((arange(p2, n), arange(p2)))
|
| 119 |
+
y = take(y, mylist, k)
|
| 120 |
+
return y
|
| 121 |
+
|
| 122 |
+
# create possible 2d array combinations and try all possible keywords
|
| 123 |
+
# compare output to original functions
|
| 124 |
+
for i in range(16):
|
| 125 |
+
for j in range(16):
|
| 126 |
+
for axes_keyword in [0, 1, None, (0,), (0, 1)]:
|
| 127 |
+
inp = np.random.rand(i, j)
|
| 128 |
+
|
| 129 |
+
assert_array_almost_equal(fft.fftshift(inp, axes_keyword),
|
| 130 |
+
original_fftshift(inp, axes_keyword))
|
| 131 |
+
|
| 132 |
+
assert_array_almost_equal(fft.ifftshift(inp, axes_keyword),
|
| 133 |
+
original_ifftshift(inp, axes_keyword))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class TestFFTFreq:
|
| 137 |
+
|
| 138 |
+
def test_definition(self):
|
| 139 |
+
x = [0, 1, 2, 3, 4, -4, -3, -2, -1]
|
| 140 |
+
assert_array_almost_equal(9*fft.fftfreq(9), x)
|
| 141 |
+
assert_array_almost_equal(9*pi*fft.fftfreq(9, pi), x)
|
| 142 |
+
x = [0, 1, 2, 3, 4, -5, -4, -3, -2, -1]
|
| 143 |
+
assert_array_almost_equal(10*fft.fftfreq(10), x)
|
| 144 |
+
assert_array_almost_equal(10*pi*fft.fftfreq(10, pi), x)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class TestRFFTFreq:
|
| 148 |
+
|
| 149 |
+
def test_definition(self):
|
| 150 |
+
x = [0, 1, 2, 3, 4]
|
| 151 |
+
assert_array_almost_equal(9*fft.rfftfreq(9), x)
|
| 152 |
+
assert_array_almost_equal(9*pi*fft.rfftfreq(9, pi), x)
|
| 153 |
+
x = [0, 1, 2, 3, 4, 5]
|
| 154 |
+
assert_array_almost_equal(10*fft.rfftfreq(10), x)
|
| 155 |
+
assert_array_almost_equal(10*pi*fft.rfftfreq(10, pi), x)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class TestIRFFTN:
|
| 159 |
+
|
| 160 |
+
def test_not_last_axis_success(self):
|
| 161 |
+
ar, ai = np.random.random((2, 16, 8, 32))
|
| 162 |
+
a = ar + 1j*ai
|
| 163 |
+
|
| 164 |
+
axes = (-2,)
|
| 165 |
+
|
| 166 |
+
# Should not raise error
|
| 167 |
+
fft.irfftn(a, axes=ax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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pytest
|
| 3 |
+
from numpy.random import random
|
| 4 |
+
from numpy.testing import (
|
| 5 |
+
assert_array_equal, assert_raises, assert_allclose, IS_WASM
|
| 6 |
+
)
|
| 7 |
+
import threading
|
| 8 |
+
import queue
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def fft1(x):
|
| 12 |
+
L = len(x)
|
| 13 |
+
phase = -2j * np.pi * (np.arange(L) / L)
|
| 14 |
+
phase = np.arange(L).reshape(-1, 1) * phase
|
| 15 |
+
return np.sum(x*np.exp(phase), axis=1)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TestFFTShift:
|
| 19 |
+
|
| 20 |
+
def test_fft_n(self):
|
| 21 |
+
assert_raises(ValueError, np.fft.fft, [1, 2, 3], 0)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class TestFFT1D:
|
| 25 |
+
|
| 26 |
+
def test_identity(self):
|
| 27 |
+
maxlen = 512
|
| 28 |
+
x = random(maxlen) + 1j*random(maxlen)
|
| 29 |
+
xr = random(maxlen)
|
| 30 |
+
for i in range(1, maxlen):
|
| 31 |
+
assert_allclose(np.fft.ifft(np.fft.fft(x[0:i])), x[0:i],
|
| 32 |
+
atol=1e-12)
|
| 33 |
+
assert_allclose(np.fft.irfft(np.fft.rfft(xr[0:i]), i),
|
| 34 |
+
xr[0:i], atol=1e-12)
|
| 35 |
+
|
| 36 |
+
@pytest.mark.parametrize("dtype", [np.single, np.double, np.longdouble])
|
| 37 |
+
def test_identity_long_short(self, dtype):
|
| 38 |
+
# Test with explicitly given number of points, both for n
|
| 39 |
+
# smaller and for n larger than the input size.
|
| 40 |
+
maxlen = 16
|
| 41 |
+
atol = 5 * np.spacing(np.array(1., dtype=dtype))
|
| 42 |
+
x = random(maxlen).astype(dtype) + 1j*random(maxlen).astype(dtype)
|
| 43 |
+
xx = np.concatenate([x, np.zeros_like(x)])
|
| 44 |
+
xr = random(maxlen).astype(dtype)
|
| 45 |
+
xxr = np.concatenate([xr, np.zeros_like(xr)])
|
| 46 |
+
for i in range(1, maxlen*2):
|
| 47 |
+
check_c = np.fft.ifft(np.fft.fft(x, n=i), n=i)
|
| 48 |
+
assert check_c.real.dtype == dtype
|
| 49 |
+
assert_allclose(check_c, xx[0:i], atol=atol, rtol=0)
|
| 50 |
+
check_r = np.fft.irfft(np.fft.rfft(xr, n=i), n=i)
|
| 51 |
+
assert check_r.dtype == dtype
|
| 52 |
+
assert_allclose(check_r, xxr[0:i], atol=atol, rtol=0)
|
| 53 |
+
|
| 54 |
+
@pytest.mark.parametrize("dtype", [np.single, np.double, np.longdouble])
|
| 55 |
+
def test_identity_long_short_reversed(self, dtype):
|
| 56 |
+
# Also test explicitly given number of points in reversed order.
|
| 57 |
+
maxlen = 16
|
| 58 |
+
atol = 5 * np.spacing(np.array(1., dtype=dtype))
|
| 59 |
+
x = random(maxlen).astype(dtype) + 1j*random(maxlen).astype(dtype)
|
| 60 |
+
xx = np.concatenate([x, np.zeros_like(x)])
|
| 61 |
+
for i in range(1, maxlen*2):
|
| 62 |
+
check_via_c = np.fft.fft(np.fft.ifft(x, n=i), n=i)
|
| 63 |
+
assert check_via_c.dtype == x.dtype
|
| 64 |
+
assert_allclose(check_via_c, xx[0:i], atol=atol, rtol=0)
|
| 65 |
+
# For irfft, we can neither recover the imaginary part of
|
| 66 |
+
# the first element, nor the imaginary part of the last
|
| 67 |
+
# element if npts is even. So, set to 0 for the comparison.
|
| 68 |
+
y = x.copy()
|
| 69 |
+
n = i // 2 + 1
|
| 70 |
+
y.imag[0] = 0
|
| 71 |
+
if i % 2 == 0:
|
| 72 |
+
y.imag[n-1:] = 0
|
| 73 |
+
yy = np.concatenate([y, np.zeros_like(y)])
|
| 74 |
+
check_via_r = np.fft.rfft(np.fft.irfft(x, n=i), n=i)
|
| 75 |
+
assert check_via_r.dtype == x.dtype
|
| 76 |
+
assert_allclose(check_via_r, yy[0:n], atol=atol, rtol=0)
|
| 77 |
+
|
| 78 |
+
def test_fft(self):
|
| 79 |
+
x = random(30) + 1j*random(30)
|
| 80 |
+
assert_allclose(fft1(x), np.fft.fft(x), atol=1e-6)
|
| 81 |
+
assert_allclose(fft1(x), np.fft.fft(x, norm="backward"), atol=1e-6)
|
| 82 |
+
assert_allclose(fft1(x) / np.sqrt(30),
|
| 83 |
+
np.fft.fft(x, norm="ortho"), atol=1e-6)
|
| 84 |
+
assert_allclose(fft1(x) / 30.,
|
| 85 |
+
np.fft.fft(x, norm="forward"), atol=1e-6)
|
| 86 |
+
|
| 87 |
+
@pytest.mark.parametrize("axis", (0, 1))
|
| 88 |
+
@pytest.mark.parametrize("dtype", (complex, float))
|
| 89 |
+
@pytest.mark.parametrize("transpose", (True, False))
|
| 90 |
+
def test_fft_out_argument(self, dtype, transpose, axis):
|
| 91 |
+
def zeros_like(x):
|
| 92 |
+
if transpose:
|
| 93 |
+
return np.zeros_like(x.T).T
|
| 94 |
+
else:
|
| 95 |
+
return np.zeros_like(x)
|
| 96 |
+
|
| 97 |
+
# tests below only test the out parameter
|
| 98 |
+
if dtype is complex:
|
| 99 |
+
y = random((10, 20)) + 1j*random((10, 20))
|
| 100 |
+
fft, ifft = np.fft.fft, np.fft.ifft
|
| 101 |
+
else:
|
| 102 |
+
y = random((10, 20))
|
| 103 |
+
fft, ifft = np.fft.rfft, np.fft.irfft
|
| 104 |
+
|
| 105 |
+
expected = fft(y, axis=axis)
|
| 106 |
+
out = zeros_like(expected)
|
| 107 |
+
result = fft(y, out=out, axis=axis)
|
| 108 |
+
assert result is out
|
| 109 |
+
assert_array_equal(result, expected)
|
| 110 |
+
|
| 111 |
+
expected2 = ifft(expected, axis=axis)
|
| 112 |
+
out2 = out if dtype is complex else zeros_like(expected2)
|
| 113 |
+
result2 = ifft(out, out=out2, axis=axis)
|
| 114 |
+
assert result2 is out2
|
| 115 |
+
assert_array_equal(result2, expected2)
|
| 116 |
+
|
| 117 |
+
@pytest.mark.parametrize("axis", [0, 1])
|
| 118 |
+
def test_fft_inplace_out(self, axis):
|
| 119 |
+
# Test some weirder in-place combinations
|
| 120 |
+
y = random((20, 20)) + 1j*random((20, 20))
|
| 121 |
+
# Fully in-place.
|
| 122 |
+
y1 = y.copy()
|
| 123 |
+
expected1 = np.fft.fft(y1, axis=axis)
|
| 124 |
+
result1 = np.fft.fft(y1, axis=axis, out=y1)
|
| 125 |
+
assert result1 is y1
|
| 126 |
+
assert_array_equal(result1, expected1)
|
| 127 |
+
# In-place of part of the array; rest should be unchanged.
|
| 128 |
+
y2 = y.copy()
|
| 129 |
+
out2 = y2[:10] if axis == 0 else y2[:, :10]
|
| 130 |
+
expected2 = np.fft.fft(y2, n=10, axis=axis)
|
| 131 |
+
result2 = np.fft.fft(y2, n=10, axis=axis, out=out2)
|
| 132 |
+
assert result2 is out2
|
| 133 |
+
assert_array_equal(result2, expected2)
|
| 134 |
+
if axis == 0:
|
| 135 |
+
assert_array_equal(y2[10:], y[10:])
|
| 136 |
+
else:
|
| 137 |
+
assert_array_equal(y2[:, 10:], y[:, 10:])
|
| 138 |
+
# In-place of another part of the array.
|
| 139 |
+
y3 = y.copy()
|
| 140 |
+
y3_sel = y3[5:] if axis == 0 else y3[:, 5:]
|
| 141 |
+
out3 = y3[5:15] if axis == 0 else y3[:, 5:15]
|
| 142 |
+
expected3 = np.fft.fft(y3_sel, n=10, axis=axis)
|
| 143 |
+
result3 = np.fft.fft(y3_sel, n=10, axis=axis, out=out3)
|
| 144 |
+
assert result3 is out3
|
| 145 |
+
assert_array_equal(result3, expected3)
|
| 146 |
+
if axis == 0:
|
| 147 |
+
assert_array_equal(y3[:5], y[:5])
|
| 148 |
+
assert_array_equal(y3[15:], y[15:])
|
| 149 |
+
else:
|
| 150 |
+
assert_array_equal(y3[:, :5], y[:, :5])
|
| 151 |
+
assert_array_equal(y3[:, 15:], y[:, 15:])
|
| 152 |
+
# In-place with n > nin; rest should be unchanged.
|
| 153 |
+
y4 = y.copy()
|
| 154 |
+
y4_sel = y4[:10] if axis == 0 else y4[:, :10]
|
| 155 |
+
out4 = y4[:15] if axis == 0 else y4[:, :15]
|
| 156 |
+
expected4 = np.fft.fft(y4_sel, n=15, axis=axis)
|
| 157 |
+
result4 = np.fft.fft(y4_sel, n=15, axis=axis, out=out4)
|
| 158 |
+
assert result4 is out4
|
| 159 |
+
assert_array_equal(result4, expected4)
|
| 160 |
+
if axis == 0:
|
| 161 |
+
assert_array_equal(y4[15:], y[15:])
|
| 162 |
+
else:
|
| 163 |
+
assert_array_equal(y4[:, 15:], y[:, 15:])
|
| 164 |
+
# Overwrite in a transpose.
|
| 165 |
+
y5 = y.copy()
|
| 166 |
+
out5 = y5.T
|
| 167 |
+
result5 = np.fft.fft(y5, axis=axis, out=out5)
|
| 168 |
+
assert result5 is out5
|
| 169 |
+
assert_array_equal(result5, expected1)
|
| 170 |
+
# Reverse strides.
|
| 171 |
+
y6 = y.copy()
|
| 172 |
+
out6 = y6[::-1] if axis == 0 else y6[:, ::-1]
|
| 173 |
+
result6 = np.fft.fft(y6, axis=axis, out=out6)
|
| 174 |
+
assert result6 is out6
|
| 175 |
+
assert_array_equal(result6, expected1)
|
| 176 |
+
|
| 177 |
+
def test_fft_bad_out(self):
|
| 178 |
+
x = np.arange(30.)
|
| 179 |
+
with pytest.raises(TypeError, match="must be of ArrayType"):
|
| 180 |
+
np.fft.fft(x, out="")
|
| 181 |
+
with pytest.raises(ValueError, match="has wrong shape"):
|
| 182 |
+
np.fft.fft(x, out=np.zeros_like(x).reshape(5, -1))
|
| 183 |
+
with pytest.raises(TypeError, match="Cannot cast"):
|
| 184 |
+
np.fft.fft(x, out=np.zeros_like(x, dtype=float))
|
| 185 |
+
|
| 186 |
+
@pytest.mark.parametrize('norm', (None, 'backward', 'ortho', 'forward'))
|
| 187 |
+
def test_ifft(self, norm):
|
| 188 |
+
x = random(30) + 1j*random(30)
|
| 189 |
+
assert_allclose(
|
| 190 |
+
x, np.fft.ifft(np.fft.fft(x, norm=norm), norm=norm),
|
| 191 |
+
atol=1e-6)
|
| 192 |
+
# Ensure we get the correct error message
|
| 193 |
+
with pytest.raises(ValueError,
|
| 194 |
+
match='Invalid number of FFT data points'):
|
| 195 |
+
np.fft.ifft([], norm=norm)
|
| 196 |
+
|
| 197 |
+
def test_fft2(self):
|
| 198 |
+
x = random((30, 20)) + 1j*random((30, 20))
|
| 199 |
+
assert_allclose(np.fft.fft(np.fft.fft(x, axis=1), axis=0),
|
| 200 |
+
np.fft.fft2(x), atol=1e-6)
|
| 201 |
+
assert_allclose(np.fft.fft2(x),
|
| 202 |
+
np.fft.fft2(x, norm="backward"), atol=1e-6)
|
| 203 |
+
assert_allclose(np.fft.fft2(x) / np.sqrt(30 * 20),
|
| 204 |
+
np.fft.fft2(x, norm="ortho"), atol=1e-6)
|
| 205 |
+
assert_allclose(np.fft.fft2(x) / (30. * 20.),
|
| 206 |
+
np.fft.fft2(x, norm="forward"), atol=1e-6)
|
| 207 |
+
|
| 208 |
+
def test_ifft2(self):
|
| 209 |
+
x = random((30, 20)) + 1j*random((30, 20))
|
| 210 |
+
assert_allclose(np.fft.ifft(np.fft.ifft(x, axis=1), axis=0),
|
| 211 |
+
np.fft.ifft2(x), atol=1e-6)
|
| 212 |
+
assert_allclose(np.fft.ifft2(x),
|
| 213 |
+
np.fft.ifft2(x, norm="backward"), atol=1e-6)
|
| 214 |
+
assert_allclose(np.fft.ifft2(x) * np.sqrt(30 * 20),
|
| 215 |
+
np.fft.ifft2(x, norm="ortho"), atol=1e-6)
|
| 216 |
+
assert_allclose(np.fft.ifft2(x) * (30. * 20.),
|
| 217 |
+
np.fft.ifft2(x, norm="forward"), atol=1e-6)
|
| 218 |
+
|
| 219 |
+
def test_fftn(self):
|
| 220 |
+
x = random((30, 20, 10)) + 1j*random((30, 20, 10))
|
| 221 |
+
assert_allclose(
|
| 222 |
+
np.fft.fft(np.fft.fft(np.fft.fft(x, axis=2), axis=1), axis=0),
|
| 223 |
+
np.fft.fftn(x), atol=1e-6)
|
| 224 |
+
assert_allclose(np.fft.fftn(x),
|
| 225 |
+
np.fft.fftn(x, norm="backward"), atol=1e-6)
|
| 226 |
+
assert_allclose(np.fft.fftn(x) / np.sqrt(30 * 20 * 10),
|
| 227 |
+
np.fft.fftn(x, norm="ortho"), atol=1e-6)
|
| 228 |
+
assert_allclose(np.fft.fftn(x) / (30. * 20. * 10.),
|
| 229 |
+
np.fft.fftn(x, norm="forward"), atol=1e-6)
|
| 230 |
+
|
| 231 |
+
def test_ifftn(self):
|
| 232 |
+
x = random((30, 20, 10)) + 1j*random((30, 20, 10))
|
| 233 |
+
assert_allclose(
|
| 234 |
+
np.fft.ifft(np.fft.ifft(np.fft.ifft(x, axis=2), axis=1), axis=0),
|
| 235 |
+
np.fft.ifftn(x), atol=1e-6)
|
| 236 |
+
assert_allclose(np.fft.ifftn(x),
|
| 237 |
+
np.fft.ifftn(x, norm="backward"), atol=1e-6)
|
| 238 |
+
assert_allclose(np.fft.ifftn(x) * np.sqrt(30 * 20 * 10),
|
| 239 |
+
np.fft.ifftn(x, norm="ortho"), atol=1e-6)
|
| 240 |
+
assert_allclose(np.fft.ifftn(x) * (30. * 20. * 10.),
|
| 241 |
+
np.fft.ifftn(x, norm="forward"), atol=1e-6)
|
| 242 |
+
|
| 243 |
+
def test_rfft(self):
|
| 244 |
+
x = random(30)
|
| 245 |
+
for n in [x.size, 2*x.size]:
|
| 246 |
+
for norm in [None, 'backward', 'ortho', 'forward']:
|
| 247 |
+
assert_allclose(
|
| 248 |
+
np.fft.fft(x, n=n, norm=norm)[:(n//2 + 1)],
|
| 249 |
+
np.fft.rfft(x, n=n, norm=norm), atol=1e-6)
|
| 250 |
+
assert_allclose(
|
| 251 |
+
np.fft.rfft(x, n=n),
|
| 252 |
+
np.fft.rfft(x, n=n, norm="backward"), atol=1e-6)
|
| 253 |
+
assert_allclose(
|
| 254 |
+
np.fft.rfft(x, n=n) / np.sqrt(n),
|
| 255 |
+
np.fft.rfft(x, n=n, norm="ortho"), atol=1e-6)
|
| 256 |
+
assert_allclose(
|
| 257 |
+
np.fft.rfft(x, n=n) / n,
|
| 258 |
+
np.fft.rfft(x, n=n, norm="forward"), atol=1e-6)
|
| 259 |
+
|
| 260 |
+
def test_rfft_even(self):
|
| 261 |
+
x = np.arange(8)
|
| 262 |
+
n = 4
|
| 263 |
+
y = np.fft.rfft(x, n)
|
| 264 |
+
assert_allclose(y, np.fft.fft(x[:n])[:n//2 + 1], rtol=1e-14)
|
| 265 |
+
|
| 266 |
+
def test_rfft_odd(self):
|
| 267 |
+
x = np.array([1, 0, 2, 3, -3])
|
| 268 |
+
y = np.fft.rfft(x)
|
| 269 |
+
assert_allclose(y, np.fft.fft(x)[:3], rtol=1e-14)
|
| 270 |
+
|
| 271 |
+
def test_irfft(self):
|
| 272 |
+
x = random(30)
|
| 273 |
+
assert_allclose(x, np.fft.irfft(np.fft.rfft(x)), atol=1e-6)
|
| 274 |
+
assert_allclose(x, np.fft.irfft(np.fft.rfft(x, norm="backward"),
|
| 275 |
+
norm="backward"), atol=1e-6)
|
| 276 |
+
assert_allclose(x, np.fft.irfft(np.fft.rfft(x, norm="ortho"),
|
| 277 |
+
norm="ortho"), atol=1e-6)
|
| 278 |
+
assert_allclose(x, np.fft.irfft(np.fft.rfft(x, norm="forward"),
|
| 279 |
+
norm="forward"), atol=1e-6)
|
| 280 |
+
|
| 281 |
+
def test_rfft2(self):
|
| 282 |
+
x = random((30, 20))
|
| 283 |
+
assert_allclose(np.fft.fft2(x)[:, :11], np.fft.rfft2(x), atol=1e-6)
|
| 284 |
+
assert_allclose(np.fft.rfft2(x),
|
| 285 |
+
np.fft.rfft2(x, norm="backward"), atol=1e-6)
|
| 286 |
+
assert_allclose(np.fft.rfft2(x) / np.sqrt(30 * 20),
|
| 287 |
+
np.fft.rfft2(x, norm="ortho"), atol=1e-6)
|
| 288 |
+
assert_allclose(np.fft.rfft2(x) / (30. * 20.),
|
| 289 |
+
np.fft.rfft2(x, norm="forward"), atol=1e-6)
|
| 290 |
+
|
| 291 |
+
def test_irfft2(self):
|
| 292 |
+
x = random((30, 20))
|
| 293 |
+
assert_allclose(x, np.fft.irfft2(np.fft.rfft2(x)), atol=1e-6)
|
| 294 |
+
assert_allclose(x, np.fft.irfft2(np.fft.rfft2(x, norm="backward"),
|
| 295 |
+
norm="backward"), atol=1e-6)
|
| 296 |
+
assert_allclose(x, np.fft.irfft2(np.fft.rfft2(x, norm="ortho"),
|
| 297 |
+
norm="ortho"), atol=1e-6)
|
| 298 |
+
assert_allclose(x, np.fft.irfft2(np.fft.rfft2(x, norm="forward"),
|
| 299 |
+
norm="forward"), atol=1e-6)
|
| 300 |
+
|
| 301 |
+
def test_rfftn(self):
|
| 302 |
+
x = random((30, 20, 10))
|
| 303 |
+
assert_allclose(np.fft.fftn(x)[:, :, :6], np.fft.rfftn(x), atol=1e-6)
|
| 304 |
+
assert_allclose(np.fft.rfftn(x),
|
| 305 |
+
np.fft.rfftn(x, norm="backward"), atol=1e-6)
|
| 306 |
+
assert_allclose(np.fft.rfftn(x) / np.sqrt(30 * 20 * 10),
|
| 307 |
+
np.fft.rfftn(x, norm="ortho"), atol=1e-6)
|
| 308 |
+
assert_allclose(np.fft.rfftn(x) / (30. * 20. * 10.),
|
| 309 |
+
np.fft.rfftn(x, norm="forward"), atol=1e-6)
|
| 310 |
+
# Regression test for gh-27159
|
| 311 |
+
x = np.ones((2, 3))
|
| 312 |
+
result = np.fft.rfftn(x, axes=(0, 0, 1), s=(10, 20, 40))
|
| 313 |
+
assert result.shape == (10, 21)
|
| 314 |
+
expected = np.fft.fft(np.fft.fft(np.fft.rfft(x, axis=1, n=40),
|
| 315 |
+
axis=0, n=20), axis=0, n=10)
|
| 316 |
+
assert expected.shape == (10, 21)
|
| 317 |
+
assert_allclose(result, expected, atol=1e-6)
|
| 318 |
+
|
| 319 |
+
def test_irfftn(self):
|
| 320 |
+
x = random((30, 20, 10))
|
| 321 |
+
assert_allclose(x, np.fft.irfftn(np.fft.rfftn(x)), atol=1e-6)
|
| 322 |
+
assert_allclose(x, np.fft.irfftn(np.fft.rfftn(x, norm="backward"),
|
| 323 |
+
norm="backward"), atol=1e-6)
|
| 324 |
+
assert_allclose(x, np.fft.irfftn(np.fft.rfftn(x, norm="ortho"),
|
| 325 |
+
norm="ortho"), atol=1e-6)
|
| 326 |
+
assert_allclose(x, np.fft.irfftn(np.fft.rfftn(x, norm="forward"),
|
| 327 |
+
norm="forward"), atol=1e-6)
|
| 328 |
+
|
| 329 |
+
def test_hfft(self):
|
| 330 |
+
x = random(14) + 1j*random(14)
|
| 331 |
+
x_herm = np.concatenate((random(1), x, random(1)))
|
| 332 |
+
x = np.concatenate((x_herm, x[::-1].conj()))
|
| 333 |
+
assert_allclose(np.fft.fft(x), np.fft.hfft(x_herm), atol=1e-6)
|
| 334 |
+
assert_allclose(np.fft.hfft(x_herm),
|
| 335 |
+
np.fft.hfft(x_herm, norm="backward"), atol=1e-6)
|
| 336 |
+
assert_allclose(np.fft.hfft(x_herm) / np.sqrt(30),
|
| 337 |
+
np.fft.hfft(x_herm, norm="ortho"), atol=1e-6)
|
| 338 |
+
assert_allclose(np.fft.hfft(x_herm) / 30.,
|
| 339 |
+
np.fft.hfft(x_herm, norm="forward"), atol=1e-6)
|
| 340 |
+
|
| 341 |
+
def test_ihfft(self):
|
| 342 |
+
x = random(14) + 1j*random(14)
|
| 343 |
+
x_herm = np.concatenate((random(1), x, random(1)))
|
| 344 |
+
x = np.concatenate((x_herm, x[::-1].conj()))
|
| 345 |
+
assert_allclose(x_herm, np.fft.ihfft(np.fft.hfft(x_herm)), atol=1e-6)
|
| 346 |
+
assert_allclose(x_herm, np.fft.ihfft(np.fft.hfft(x_herm,
|
| 347 |
+
norm="backward"), norm="backward"), atol=1e-6)
|
| 348 |
+
assert_allclose(x_herm, np.fft.ihfft(np.fft.hfft(x_herm,
|
| 349 |
+
norm="ortho"), norm="ortho"), atol=1e-6)
|
| 350 |
+
assert_allclose(x_herm, np.fft.ihfft(np.fft.hfft(x_herm,
|
| 351 |
+
norm="forward"), norm="forward"), atol=1e-6)
|
| 352 |
+
|
| 353 |
+
@pytest.mark.parametrize("op", [np.fft.fftn, np.fft.ifftn,
|
| 354 |
+
np.fft.rfftn, np.fft.irfftn])
|
| 355 |
+
def test_axes(self, op):
|
| 356 |
+
x = random((30, 20, 10))
|
| 357 |
+
axes = [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
|
| 358 |
+
for a in axes:
|
| 359 |
+
op_tr = op(np.transpose(x, a))
|
| 360 |
+
tr_op = np.transpose(op(x, axes=a), a)
|
| 361 |
+
assert_allclose(op_tr, tr_op, atol=1e-6)
|
| 362 |
+
|
| 363 |
+
@pytest.mark.parametrize("op", [np.fft.fftn, np.fft.ifftn,
|
| 364 |
+
np.fft.fft2, np.fft.ifft2])
|
| 365 |
+
def test_s_negative_1(self, op):
|
| 366 |
+
x = np.arange(100).reshape(10, 10)
|
| 367 |
+
# should use the whole input array along the first axis
|
| 368 |
+
assert op(x, s=(-1, 5), axes=(0, 1)).shape == (10, 5)
|
| 369 |
+
|
| 370 |
+
@pytest.mark.parametrize("op", [np.fft.fftn, np.fft.ifftn,
|
| 371 |
+
np.fft.rfftn, np.fft.irfftn])
|
| 372 |
+
def test_s_axes_none(self, op):
|
| 373 |
+
x = np.arange(100).reshape(10, 10)
|
| 374 |
+
with pytest.warns(match='`axes` should not be `None` if `s`'):
|
| 375 |
+
op(x, s=(-1, 5))
|
| 376 |
+
|
| 377 |
+
@pytest.mark.parametrize("op", [np.fft.fft2, np.fft.ifft2])
|
| 378 |
+
def test_s_axes_none_2D(self, op):
|
| 379 |
+
x = np.arange(100).reshape(10, 10)
|
| 380 |
+
with pytest.warns(match='`axes` should not be `None` if `s`'):
|
| 381 |
+
op(x, s=(-1, 5), axes=None)
|
| 382 |
+
|
| 383 |
+
@pytest.mark.parametrize("op", [np.fft.fftn, np.fft.ifftn,
|
| 384 |
+
np.fft.rfftn, np.fft.irfftn,
|
| 385 |
+
np.fft.fft2, np.fft.ifft2])
|
| 386 |
+
def test_s_contains_none(self, op):
|
| 387 |
+
x = random((30, 20, 10))
|
| 388 |
+
with pytest.warns(match='array containing `None` values to `s`'):
|
| 389 |
+
op(x, s=(10, None, 10), axes=(0, 1, 2))
|
| 390 |
+
|
| 391 |
+
def test_all_1d_norm_preserving(self):
|
| 392 |
+
# verify that round-trip transforms are norm-preserving
|
| 393 |
+
x = random(30)
|
| 394 |
+
x_norm = np.linalg.norm(x)
|
| 395 |
+
n = x.size * 2
|
| 396 |
+
func_pairs = [(np.fft.fft, np.fft.ifft),
|
| 397 |
+
(np.fft.rfft, np.fft.irfft),
|
| 398 |
+
# hfft: order so the first function takes x.size samples
|
| 399 |
+
# (necessary for comparison to x_norm above)
|
| 400 |
+
(np.fft.ihfft, np.fft.hfft),
|
| 401 |
+
]
|
| 402 |
+
for forw, back in func_pairs:
|
| 403 |
+
for n in [x.size, 2*x.size]:
|
| 404 |
+
for norm in [None, 'backward', 'ortho', 'forward']:
|
| 405 |
+
tmp = forw(x, n=n, norm=norm)
|
| 406 |
+
tmp = back(tmp, n=n, norm=norm)
|
| 407 |
+
assert_allclose(x_norm,
|
| 408 |
+
np.linalg.norm(tmp), atol=1e-6)
|
| 409 |
+
|
| 410 |
+
@pytest.mark.parametrize("axes", [(0, 1), (0, 2), None])
|
| 411 |
+
@pytest.mark.parametrize("dtype", (complex, float))
|
| 412 |
+
@pytest.mark.parametrize("transpose", (True, False))
|
| 413 |
+
def test_fftn_out_argument(self, dtype, transpose, axes):
|
| 414 |
+
def zeros_like(x):
|
| 415 |
+
if transpose:
|
| 416 |
+
return np.zeros_like(x.T).T
|
| 417 |
+
else:
|
| 418 |
+
return np.zeros_like(x)
|
| 419 |
+
|
| 420 |
+
# tests below only test the out parameter
|
| 421 |
+
if dtype is complex:
|
| 422 |
+
x = random((10, 5, 6)) + 1j*random((10, 5, 6))
|
| 423 |
+
fft, ifft = np.fft.fftn, np.fft.ifftn
|
| 424 |
+
else:
|
| 425 |
+
x = random((10, 5, 6))
|
| 426 |
+
fft, ifft = np.fft.rfftn, np.fft.irfftn
|
| 427 |
+
|
| 428 |
+
expected = fft(x, axes=axes)
|
| 429 |
+
out = zeros_like(expected)
|
| 430 |
+
result = fft(x, out=out, axes=axes)
|
| 431 |
+
assert result is out
|
| 432 |
+
assert_array_equal(result, expected)
|
| 433 |
+
|
| 434 |
+
expected2 = ifft(expected, axes=axes)
|
| 435 |
+
out2 = out if dtype is complex else zeros_like(expected2)
|
| 436 |
+
result2 = ifft(out, out=out2, axes=axes)
|
| 437 |
+
assert result2 is out2
|
| 438 |
+
assert_array_equal(result2, expected2)
|
| 439 |
+
|
| 440 |
+
@pytest.mark.parametrize("fft", [np.fft.fftn, np.fft.ifftn, np.fft.rfftn])
|
| 441 |
+
def test_fftn_out_and_s_interaction(self, fft):
|
| 442 |
+
# With s, shape varies, so generally one cannot pass in out.
|
| 443 |
+
if fft is np.fft.rfftn:
|
| 444 |
+
x = random((10, 5, 6))
|
| 445 |
+
else:
|
| 446 |
+
x = random((10, 5, 6)) + 1j*random((10, 5, 6))
|
| 447 |
+
with pytest.raises(ValueError, match="has wrong shape"):
|
| 448 |
+
fft(x, out=np.zeros_like(x), s=(3, 3, 3), axes=(0, 1, 2))
|
| 449 |
+
# Except on the first axis done (which is the last of axes).
|
| 450 |
+
s = (10, 5, 5)
|
| 451 |
+
expected = fft(x, s=s, axes=(0, 1, 2))
|
| 452 |
+
out = np.zeros_like(expected)
|
| 453 |
+
result = fft(x, s=s, axes=(0, 1, 2), out=out)
|
| 454 |
+
assert result is out
|
| 455 |
+
assert_array_equal(result, expected)
|
| 456 |
+
|
| 457 |
+
@pytest.mark.parametrize("s", [(9, 5, 5), (3, 3, 3)])
|
| 458 |
+
def test_irfftn_out_and_s_interaction(self, s):
|
| 459 |
+
# Since for irfftn, the output is real and thus cannot be used for
|
| 460 |
+
# intermediate steps, it should always work.
|
| 461 |
+
x = random((9, 5, 6, 2)) + 1j*random((9, 5, 6, 2))
|
| 462 |
+
expected = np.fft.irfftn(x, s=s, axes=(0, 1, 2))
|
| 463 |
+
out = np.zeros_like(expected)
|
| 464 |
+
result = np.fft.irfftn(x, s=s, axes=(0, 1, 2), out=out)
|
| 465 |
+
assert result is out
|
| 466 |
+
assert_array_equal(result, expected)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
@pytest.mark.parametrize(
|
| 470 |
+
"dtype",
|
| 471 |
+
[np.float32, np.float64, np.complex64, np.complex128])
|
| 472 |
+
@pytest.mark.parametrize("order", ["F", 'non-contiguous'])
|
| 473 |
+
@pytest.mark.parametrize(
|
| 474 |
+
"fft",
|
| 475 |
+
[np.fft.fft, np.fft.fft2, np.fft.fftn,
|
| 476 |
+
np.fft.ifft, np.fft.ifft2, np.fft.ifftn])
|
| 477 |
+
def test_fft_with_order(dtype, order, fft):
|
| 478 |
+
# Check that FFT/IFFT produces identical results for C, Fortran and
|
| 479 |
+
# non contiguous arrays
|
| 480 |
+
rng = np.random.RandomState(42)
|
| 481 |
+
X = rng.rand(8, 7, 13).astype(dtype, copy=False)
|
| 482 |
+
# See discussion in pull/14178
|
| 483 |
+
_tol = 8.0 * np.sqrt(np.log2(X.size)) * np.finfo(X.dtype).eps
|
| 484 |
+
if order == 'F':
|
| 485 |
+
Y = np.asfortranarray(X)
|
| 486 |
+
else:
|
| 487 |
+
# Make a non contiguous array
|
| 488 |
+
Y = X[::-1]
|
| 489 |
+
X = np.ascontiguousarray(X[::-1])
|
| 490 |
+
|
| 491 |
+
if fft.__name__.endswith('fft'):
|
| 492 |
+
for axis in range(3):
|
| 493 |
+
X_res = fft(X, axis=axis)
|
| 494 |
+
Y_res = fft(Y, axis=axis)
|
| 495 |
+
assert_allclose(X_res, Y_res, atol=_tol, rtol=_tol)
|
| 496 |
+
elif fft.__name__.endswith(('fft2', 'fftn')):
|
| 497 |
+
axes = [(0, 1), (1, 2), (0, 2)]
|
| 498 |
+
if fft.__name__.endswith('fftn'):
|
| 499 |
+
axes.extend([(0,), (1,), (2,), None])
|
| 500 |
+
for ax in axes:
|
| 501 |
+
X_res = fft(X, axes=ax)
|
| 502 |
+
Y_res = fft(Y, axes=ax)
|
| 503 |
+
assert_allclose(X_res, Y_res, atol=_tol, rtol=_tol)
|
| 504 |
+
else:
|
| 505 |
+
raise ValueError
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
@pytest.mark.parametrize("order", ["F", "C"])
|
| 509 |
+
@pytest.mark.parametrize("n", [None, 7, 12])
|
| 510 |
+
def test_fft_output_order(order, n):
|
| 511 |
+
rng = np.random.RandomState(42)
|
| 512 |
+
x = rng.rand(10)
|
| 513 |
+
x = np.asarray(x, dtype=np.complex64, order=order)
|
| 514 |
+
res = np.fft.fft(x, n=n)
|
| 515 |
+
assert res.flags.c_contiguous == x.flags.c_contiguous
|
| 516 |
+
assert res.flags.f_contiguous == x.flags.f_contiguous
|
| 517 |
+
|
| 518 |
+
@pytest.mark.skipif(IS_WASM, reason="Cannot start thread")
|
| 519 |
+
class TestFFTThreadSafe:
|
| 520 |
+
threads = 16
|
| 521 |
+
input_shape = (800, 200)
|
| 522 |
+
|
| 523 |
+
def _test_mtsame(self, func, *args):
|
| 524 |
+
def worker(args, q):
|
| 525 |
+
q.put(func(*args))
|
| 526 |
+
|
| 527 |
+
q = queue.Queue()
|
| 528 |
+
expected = func(*args)
|
| 529 |
+
|
| 530 |
+
# Spin off a bunch of threads to call the same function simultaneously
|
| 531 |
+
t = [threading.Thread(target=worker, args=(args, q))
|
| 532 |
+
for i in range(self.threads)]
|
| 533 |
+
[x.start() for x in t]
|
| 534 |
+
|
| 535 |
+
[x.join() for x in t]
|
| 536 |
+
# Make sure all threads returned the correct value
|
| 537 |
+
for i in range(self.threads):
|
| 538 |
+
assert_array_equal(q.get(timeout=5), expected,
|
| 539 |
+
'Function returned wrong value in multithreaded context')
|
| 540 |
+
|
| 541 |
+
def test_fft(self):
|
| 542 |
+
a = np.ones(self.input_shape) * 1+0j
|
| 543 |
+
self._test_mtsame(np.fft.fft, a)
|
| 544 |
+
|
| 545 |
+
def test_ifft(self):
|
| 546 |
+
a = np.ones(self.input_shape) * 1+0j
|
| 547 |
+
self._test_mtsame(np.fft.ifft, a)
|
| 548 |
+
|
| 549 |
+
def test_rfft(self):
|
| 550 |
+
a = np.ones(self.input_shape)
|
| 551 |
+
self._test_mtsame(np.fft.rfft, a)
|
| 552 |
+
|
| 553 |
+
def test_irfft(self):
|
| 554 |
+
a = np.ones(self.input_shape) * 1+0j
|
| 555 |
+
self._test_mtsame(np.fft.irfft, a)
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
def test_irfft_with_n_1_regression():
|
| 559 |
+
# Regression test for gh-25661
|
| 560 |
+
x = np.arange(10)
|
| 561 |
+
np.fft.irfft(x, n=1)
|
| 562 |
+
np.fft.hfft(x, n=1)
|
| 563 |
+
np.fft.irfft(np.array([0], complex), n=10)
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def test_irfft_with_n_large_regression():
|
| 567 |
+
# Regression test for gh-25679
|
| 568 |
+
x = np.arange(5) * (1 + 1j)
|
| 569 |
+
result = np.fft.hfft(x, n=10)
|
| 570 |
+
expected = np.array([20., 9.91628173, -11.8819096, 7.1048486,
|
| 571 |
+
-6.62459848, 4., -3.37540152, -0.16057669,
|
| 572 |
+
1.8819096, -20.86055364])
|
| 573 |
+
assert_allclose(result, expected)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
@pytest.mark.parametrize("fft", [
|
| 577 |
+
np.fft.fft, np.fft.ifft, np.fft.rfft, np.fft.irfft
|
| 578 |
+
])
|
| 579 |
+
@pytest.mark.parametrize("data", [
|
| 580 |
+
np.array([False, True, False]),
|
| 581 |
+
np.arange(10, dtype=np.uint8),
|
| 582 |
+
np.arange(5, dtype=np.int16),
|
| 583 |
+
])
|
| 584 |
+
def test_fft_with_integer_or_bool_input(data, fft):
|
| 585 |
+
# Regression test for gh-25819
|
| 586 |
+
result = fft(data)
|
| 587 |
+
float_data = data.astype(np.result_type(data, 1.))
|
| 588 |
+
expected = fft(float_data)
|
| 589 |
+
assert_array_equal(result, expected)
|
janus/lib/python3.10/site-packages/numpy/lib/_arraypad_impl.py
ADDED
|
@@ -0,0 +1,891 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The arraypad module contains a group of functions to pad values onto the edges
|
| 3 |
+
of an n-dimensional array.
|
| 4 |
+
|
| 5 |
+
"""
|
| 6 |
+
import numpy as np
|
| 7 |
+
from numpy._core.overrides import array_function_dispatch
|
| 8 |
+
from numpy.lib._index_tricks_impl import ndindex
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
__all__ = ['pad']
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
###############################################################################
|
| 15 |
+
# Private utility functions.
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _round_if_needed(arr, dtype):
|
| 19 |
+
"""
|
| 20 |
+
Rounds arr inplace if destination dtype is integer.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
arr : ndarray
|
| 25 |
+
Input array.
|
| 26 |
+
dtype : dtype
|
| 27 |
+
The dtype of the destination array.
|
| 28 |
+
"""
|
| 29 |
+
if np.issubdtype(dtype, np.integer):
|
| 30 |
+
arr.round(out=arr)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _slice_at_axis(sl, axis):
|
| 34 |
+
"""
|
| 35 |
+
Construct tuple of slices to slice an array in the given dimension.
|
| 36 |
+
|
| 37 |
+
Parameters
|
| 38 |
+
----------
|
| 39 |
+
sl : slice
|
| 40 |
+
The slice for the given dimension.
|
| 41 |
+
axis : int
|
| 42 |
+
The axis to which `sl` is applied. All other dimensions are left
|
| 43 |
+
"unsliced".
|
| 44 |
+
|
| 45 |
+
Returns
|
| 46 |
+
-------
|
| 47 |
+
sl : tuple of slices
|
| 48 |
+
A tuple with slices matching `shape` in length.
|
| 49 |
+
|
| 50 |
+
Examples
|
| 51 |
+
--------
|
| 52 |
+
>>> np._slice_at_axis(slice(None, 3, -1), 1)
|
| 53 |
+
(slice(None, None, None), slice(None, 3, -1), (...,))
|
| 54 |
+
"""
|
| 55 |
+
return (slice(None),) * axis + (sl,) + (...,)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _view_roi(array, original_area_slice, axis):
|
| 59 |
+
"""
|
| 60 |
+
Get a view of the current region of interest during iterative padding.
|
| 61 |
+
|
| 62 |
+
When padding multiple dimensions iteratively corner values are
|
| 63 |
+
unnecessarily overwritten multiple times. This function reduces the
|
| 64 |
+
working area for the first dimensions so that corners are excluded.
|
| 65 |
+
|
| 66 |
+
Parameters
|
| 67 |
+
----------
|
| 68 |
+
array : ndarray
|
| 69 |
+
The array with the region of interest.
|
| 70 |
+
original_area_slice : tuple of slices
|
| 71 |
+
Denotes the area with original values of the unpadded array.
|
| 72 |
+
axis : int
|
| 73 |
+
The currently padded dimension assuming that `axis` is padded before
|
| 74 |
+
`axis` + 1.
|
| 75 |
+
|
| 76 |
+
Returns
|
| 77 |
+
-------
|
| 78 |
+
roi : ndarray
|
| 79 |
+
The region of interest of the original `array`.
|
| 80 |
+
"""
|
| 81 |
+
axis += 1
|
| 82 |
+
sl = (slice(None),) * axis + original_area_slice[axis:]
|
| 83 |
+
return array[sl]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _pad_simple(array, pad_width, fill_value=None):
|
| 87 |
+
"""
|
| 88 |
+
Pad array on all sides with either a single value or undefined values.
|
| 89 |
+
|
| 90 |
+
Parameters
|
| 91 |
+
----------
|
| 92 |
+
array : ndarray
|
| 93 |
+
Array to grow.
|
| 94 |
+
pad_width : sequence of tuple[int, int]
|
| 95 |
+
Pad width on both sides for each dimension in `arr`.
|
| 96 |
+
fill_value : scalar, optional
|
| 97 |
+
If provided the padded area is filled with this value, otherwise
|
| 98 |
+
the pad area left undefined.
|
| 99 |
+
|
| 100 |
+
Returns
|
| 101 |
+
-------
|
| 102 |
+
padded : ndarray
|
| 103 |
+
The padded array with the same dtype as`array`. Its order will default
|
| 104 |
+
to C-style if `array` is not F-contiguous.
|
| 105 |
+
original_area_slice : tuple
|
| 106 |
+
A tuple of slices pointing to the area of the original array.
|
| 107 |
+
"""
|
| 108 |
+
# Allocate grown array
|
| 109 |
+
new_shape = tuple(
|
| 110 |
+
left + size + right
|
| 111 |
+
for size, (left, right) in zip(array.shape, pad_width)
|
| 112 |
+
)
|
| 113 |
+
order = 'F' if array.flags.fnc else 'C' # Fortran and not also C-order
|
| 114 |
+
padded = np.empty(new_shape, dtype=array.dtype, order=order)
|
| 115 |
+
|
| 116 |
+
if fill_value is not None:
|
| 117 |
+
padded.fill(fill_value)
|
| 118 |
+
|
| 119 |
+
# Copy old array into correct space
|
| 120 |
+
original_area_slice = tuple(
|
| 121 |
+
slice(left, left + size)
|
| 122 |
+
for size, (left, right) in zip(array.shape, pad_width)
|
| 123 |
+
)
|
| 124 |
+
padded[original_area_slice] = array
|
| 125 |
+
|
| 126 |
+
return padded, original_area_slice
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _set_pad_area(padded, axis, width_pair, value_pair):
|
| 130 |
+
"""
|
| 131 |
+
Set empty-padded area in given dimension.
|
| 132 |
+
|
| 133 |
+
Parameters
|
| 134 |
+
----------
|
| 135 |
+
padded : ndarray
|
| 136 |
+
Array with the pad area which is modified inplace.
|
| 137 |
+
axis : int
|
| 138 |
+
Dimension with the pad area to set.
|
| 139 |
+
width_pair : (int, int)
|
| 140 |
+
Pair of widths that mark the pad area on both sides in the given
|
| 141 |
+
dimension.
|
| 142 |
+
value_pair : tuple of scalars or ndarrays
|
| 143 |
+
Values inserted into the pad area on each side. It must match or be
|
| 144 |
+
broadcastable to the shape of `arr`.
|
| 145 |
+
"""
|
| 146 |
+
left_slice = _slice_at_axis(slice(None, width_pair[0]), axis)
|
| 147 |
+
padded[left_slice] = value_pair[0]
|
| 148 |
+
|
| 149 |
+
right_slice = _slice_at_axis(
|
| 150 |
+
slice(padded.shape[axis] - width_pair[1], None), axis)
|
| 151 |
+
padded[right_slice] = value_pair[1]
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _get_edges(padded, axis, width_pair):
|
| 155 |
+
"""
|
| 156 |
+
Retrieve edge values from empty-padded array in given dimension.
|
| 157 |
+
|
| 158 |
+
Parameters
|
| 159 |
+
----------
|
| 160 |
+
padded : ndarray
|
| 161 |
+
Empty-padded array.
|
| 162 |
+
axis : int
|
| 163 |
+
Dimension in which the edges are considered.
|
| 164 |
+
width_pair : (int, int)
|
| 165 |
+
Pair of widths that mark the pad area on both sides in the given
|
| 166 |
+
dimension.
|
| 167 |
+
|
| 168 |
+
Returns
|
| 169 |
+
-------
|
| 170 |
+
left_edge, right_edge : ndarray
|
| 171 |
+
Edge values of the valid area in `padded` in the given dimension. Its
|
| 172 |
+
shape will always match `padded` except for the dimension given by
|
| 173 |
+
`axis` which will have a length of 1.
|
| 174 |
+
"""
|
| 175 |
+
left_index = width_pair[0]
|
| 176 |
+
left_slice = _slice_at_axis(slice(left_index, left_index + 1), axis)
|
| 177 |
+
left_edge = padded[left_slice]
|
| 178 |
+
|
| 179 |
+
right_index = padded.shape[axis] - width_pair[1]
|
| 180 |
+
right_slice = _slice_at_axis(slice(right_index - 1, right_index), axis)
|
| 181 |
+
right_edge = padded[right_slice]
|
| 182 |
+
|
| 183 |
+
return left_edge, right_edge
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _get_linear_ramps(padded, axis, width_pair, end_value_pair):
|
| 187 |
+
"""
|
| 188 |
+
Construct linear ramps for empty-padded array in given dimension.
|
| 189 |
+
|
| 190 |
+
Parameters
|
| 191 |
+
----------
|
| 192 |
+
padded : ndarray
|
| 193 |
+
Empty-padded array.
|
| 194 |
+
axis : int
|
| 195 |
+
Dimension in which the ramps are constructed.
|
| 196 |
+
width_pair : (int, int)
|
| 197 |
+
Pair of widths that mark the pad area on both sides in the given
|
| 198 |
+
dimension.
|
| 199 |
+
end_value_pair : (scalar, scalar)
|
| 200 |
+
End values for the linear ramps which form the edge of the fully padded
|
| 201 |
+
array. These values are included in the linear ramps.
|
| 202 |
+
|
| 203 |
+
Returns
|
| 204 |
+
-------
|
| 205 |
+
left_ramp, right_ramp : ndarray
|
| 206 |
+
Linear ramps to set on both sides of `padded`.
|
| 207 |
+
"""
|
| 208 |
+
edge_pair = _get_edges(padded, axis, width_pair)
|
| 209 |
+
|
| 210 |
+
left_ramp, right_ramp = (
|
| 211 |
+
np.linspace(
|
| 212 |
+
start=end_value,
|
| 213 |
+
stop=edge.squeeze(axis), # Dimension is replaced by linspace
|
| 214 |
+
num=width,
|
| 215 |
+
endpoint=False,
|
| 216 |
+
dtype=padded.dtype,
|
| 217 |
+
axis=axis
|
| 218 |
+
)
|
| 219 |
+
for end_value, edge, width in zip(
|
| 220 |
+
end_value_pair, edge_pair, width_pair
|
| 221 |
+
)
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
# Reverse linear space in appropriate dimension
|
| 225 |
+
right_ramp = right_ramp[_slice_at_axis(slice(None, None, -1), axis)]
|
| 226 |
+
|
| 227 |
+
return left_ramp, right_ramp
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def _get_stats(padded, axis, width_pair, length_pair, stat_func):
|
| 231 |
+
"""
|
| 232 |
+
Calculate statistic for the empty-padded array in given dimension.
|
| 233 |
+
|
| 234 |
+
Parameters
|
| 235 |
+
----------
|
| 236 |
+
padded : ndarray
|
| 237 |
+
Empty-padded array.
|
| 238 |
+
axis : int
|
| 239 |
+
Dimension in which the statistic is calculated.
|
| 240 |
+
width_pair : (int, int)
|
| 241 |
+
Pair of widths that mark the pad area on both sides in the given
|
| 242 |
+
dimension.
|
| 243 |
+
length_pair : 2-element sequence of None or int
|
| 244 |
+
Gives the number of values in valid area from each side that is
|
| 245 |
+
taken into account when calculating the statistic. If None the entire
|
| 246 |
+
valid area in `padded` is considered.
|
| 247 |
+
stat_func : function
|
| 248 |
+
Function to compute statistic. The expected signature is
|
| 249 |
+
``stat_func(x: ndarray, axis: int, keepdims: bool) -> ndarray``.
|
| 250 |
+
|
| 251 |
+
Returns
|
| 252 |
+
-------
|
| 253 |
+
left_stat, right_stat : ndarray
|
| 254 |
+
Calculated statistic for both sides of `padded`.
|
| 255 |
+
"""
|
| 256 |
+
# Calculate indices of the edges of the area with original values
|
| 257 |
+
left_index = width_pair[0]
|
| 258 |
+
right_index = padded.shape[axis] - width_pair[1]
|
| 259 |
+
# as well as its length
|
| 260 |
+
max_length = right_index - left_index
|
| 261 |
+
|
| 262 |
+
# Limit stat_lengths to max_length
|
| 263 |
+
left_length, right_length = length_pair
|
| 264 |
+
if left_length is None or max_length < left_length:
|
| 265 |
+
left_length = max_length
|
| 266 |
+
if right_length is None or max_length < right_length:
|
| 267 |
+
right_length = max_length
|
| 268 |
+
|
| 269 |
+
if (left_length == 0 or right_length == 0) \
|
| 270 |
+
and stat_func in {np.amax, np.amin}:
|
| 271 |
+
# amax and amin can't operate on an empty array,
|
| 272 |
+
# raise a more descriptive warning here instead of the default one
|
| 273 |
+
raise ValueError("stat_length of 0 yields no value for padding")
|
| 274 |
+
|
| 275 |
+
# Calculate statistic for the left side
|
| 276 |
+
left_slice = _slice_at_axis(
|
| 277 |
+
slice(left_index, left_index + left_length), axis)
|
| 278 |
+
left_chunk = padded[left_slice]
|
| 279 |
+
left_stat = stat_func(left_chunk, axis=axis, keepdims=True)
|
| 280 |
+
_round_if_needed(left_stat, padded.dtype)
|
| 281 |
+
|
| 282 |
+
if left_length == right_length == max_length:
|
| 283 |
+
# return early as right_stat must be identical to left_stat
|
| 284 |
+
return left_stat, left_stat
|
| 285 |
+
|
| 286 |
+
# Calculate statistic for the right side
|
| 287 |
+
right_slice = _slice_at_axis(
|
| 288 |
+
slice(right_index - right_length, right_index), axis)
|
| 289 |
+
right_chunk = padded[right_slice]
|
| 290 |
+
right_stat = stat_func(right_chunk, axis=axis, keepdims=True)
|
| 291 |
+
_round_if_needed(right_stat, padded.dtype)
|
| 292 |
+
|
| 293 |
+
return left_stat, right_stat
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _set_reflect_both(padded, axis, width_pair, method,
|
| 297 |
+
original_period, include_edge=False):
|
| 298 |
+
"""
|
| 299 |
+
Pad `axis` of `arr` with reflection.
|
| 300 |
+
|
| 301 |
+
Parameters
|
| 302 |
+
----------
|
| 303 |
+
padded : ndarray
|
| 304 |
+
Input array of arbitrary shape.
|
| 305 |
+
axis : int
|
| 306 |
+
Axis along which to pad `arr`.
|
| 307 |
+
width_pair : (int, int)
|
| 308 |
+
Pair of widths that mark the pad area on both sides in the given
|
| 309 |
+
dimension.
|
| 310 |
+
method : str
|
| 311 |
+
Controls method of reflection; options are 'even' or 'odd'.
|
| 312 |
+
original_period : int
|
| 313 |
+
Original length of data on `axis` of `arr`.
|
| 314 |
+
include_edge : bool
|
| 315 |
+
If true, edge value is included in reflection, otherwise the edge
|
| 316 |
+
value forms the symmetric axis to the reflection.
|
| 317 |
+
|
| 318 |
+
Returns
|
| 319 |
+
-------
|
| 320 |
+
pad_amt : tuple of ints, length 2
|
| 321 |
+
New index positions of padding to do along the `axis`. If these are
|
| 322 |
+
both 0, padding is done in this dimension.
|
| 323 |
+
"""
|
| 324 |
+
left_pad, right_pad = width_pair
|
| 325 |
+
old_length = padded.shape[axis] - right_pad - left_pad
|
| 326 |
+
|
| 327 |
+
if include_edge:
|
| 328 |
+
# Avoid wrapping with only a subset of the original area
|
| 329 |
+
# by ensuring period can only be a multiple of the original
|
| 330 |
+
# area's length.
|
| 331 |
+
old_length = old_length // original_period * original_period
|
| 332 |
+
# Edge is included, we need to offset the pad amount by 1
|
| 333 |
+
edge_offset = 1
|
| 334 |
+
else:
|
| 335 |
+
# Avoid wrapping with only a subset of the original area
|
| 336 |
+
# by ensuring period can only be a multiple of the original
|
| 337 |
+
# area's length.
|
| 338 |
+
old_length = ((old_length - 1) // (original_period - 1)
|
| 339 |
+
* (original_period - 1) + 1)
|
| 340 |
+
edge_offset = 0 # Edge is not included, no need to offset pad amount
|
| 341 |
+
old_length -= 1 # but must be omitted from the chunk
|
| 342 |
+
|
| 343 |
+
if left_pad > 0:
|
| 344 |
+
# Pad with reflected values on left side:
|
| 345 |
+
# First limit chunk size which can't be larger than pad area
|
| 346 |
+
chunk_length = min(old_length, left_pad)
|
| 347 |
+
# Slice right to left, stop on or next to edge, start relative to stop
|
| 348 |
+
stop = left_pad - edge_offset
|
| 349 |
+
start = stop + chunk_length
|
| 350 |
+
left_slice = _slice_at_axis(slice(start, stop, -1), axis)
|
| 351 |
+
left_chunk = padded[left_slice]
|
| 352 |
+
|
| 353 |
+
if method == "odd":
|
| 354 |
+
# Negate chunk and align with edge
|
| 355 |
+
edge_slice = _slice_at_axis(slice(left_pad, left_pad + 1), axis)
|
| 356 |
+
left_chunk = 2 * padded[edge_slice] - left_chunk
|
| 357 |
+
|
| 358 |
+
# Insert chunk into padded area
|
| 359 |
+
start = left_pad - chunk_length
|
| 360 |
+
stop = left_pad
|
| 361 |
+
pad_area = _slice_at_axis(slice(start, stop), axis)
|
| 362 |
+
padded[pad_area] = left_chunk
|
| 363 |
+
# Adjust pointer to left edge for next iteration
|
| 364 |
+
left_pad -= chunk_length
|
| 365 |
+
|
| 366 |
+
if right_pad > 0:
|
| 367 |
+
# Pad with reflected values on right side:
|
| 368 |
+
# First limit chunk size which can't be larger than pad area
|
| 369 |
+
chunk_length = min(old_length, right_pad)
|
| 370 |
+
# Slice right to left, start on or next to edge, stop relative to start
|
| 371 |
+
start = -right_pad + edge_offset - 2
|
| 372 |
+
stop = start - chunk_length
|
| 373 |
+
right_slice = _slice_at_axis(slice(start, stop, -1), axis)
|
| 374 |
+
right_chunk = padded[right_slice]
|
| 375 |
+
|
| 376 |
+
if method == "odd":
|
| 377 |
+
# Negate chunk and align with edge
|
| 378 |
+
edge_slice = _slice_at_axis(
|
| 379 |
+
slice(-right_pad - 1, -right_pad), axis)
|
| 380 |
+
right_chunk = 2 * padded[edge_slice] - right_chunk
|
| 381 |
+
|
| 382 |
+
# Insert chunk into padded area
|
| 383 |
+
start = padded.shape[axis] - right_pad
|
| 384 |
+
stop = start + chunk_length
|
| 385 |
+
pad_area = _slice_at_axis(slice(start, stop), axis)
|
| 386 |
+
padded[pad_area] = right_chunk
|
| 387 |
+
# Adjust pointer to right edge for next iteration
|
| 388 |
+
right_pad -= chunk_length
|
| 389 |
+
|
| 390 |
+
return left_pad, right_pad
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def _set_wrap_both(padded, axis, width_pair, original_period):
|
| 394 |
+
"""
|
| 395 |
+
Pad `axis` of `arr` with wrapped values.
|
| 396 |
+
|
| 397 |
+
Parameters
|
| 398 |
+
----------
|
| 399 |
+
padded : ndarray
|
| 400 |
+
Input array of arbitrary shape.
|
| 401 |
+
axis : int
|
| 402 |
+
Axis along which to pad `arr`.
|
| 403 |
+
width_pair : (int, int)
|
| 404 |
+
Pair of widths that mark the pad area on both sides in the given
|
| 405 |
+
dimension.
|
| 406 |
+
original_period : int
|
| 407 |
+
Original length of data on `axis` of `arr`.
|
| 408 |
+
|
| 409 |
+
Returns
|
| 410 |
+
-------
|
| 411 |
+
pad_amt : tuple of ints, length 2
|
| 412 |
+
New index positions of padding to do along the `axis`. If these are
|
| 413 |
+
both 0, padding is done in this dimension.
|
| 414 |
+
"""
|
| 415 |
+
left_pad, right_pad = width_pair
|
| 416 |
+
period = padded.shape[axis] - right_pad - left_pad
|
| 417 |
+
# Avoid wrapping with only a subset of the original area by ensuring period
|
| 418 |
+
# can only be a multiple of the original area's length.
|
| 419 |
+
period = period // original_period * original_period
|
| 420 |
+
|
| 421 |
+
# If the current dimension of `arr` doesn't contain enough valid values
|
| 422 |
+
# (not part of the undefined pad area) we need to pad multiple times.
|
| 423 |
+
# Each time the pad area shrinks on both sides which is communicated with
|
| 424 |
+
# these variables.
|
| 425 |
+
new_left_pad = 0
|
| 426 |
+
new_right_pad = 0
|
| 427 |
+
|
| 428 |
+
if left_pad > 0:
|
| 429 |
+
# Pad with wrapped values on left side
|
| 430 |
+
# First slice chunk from left side of the non-pad area.
|
| 431 |
+
# Use min(period, left_pad) to ensure that chunk is not larger than
|
| 432 |
+
# pad area.
|
| 433 |
+
slice_end = left_pad + period
|
| 434 |
+
slice_start = slice_end - min(period, left_pad)
|
| 435 |
+
right_slice = _slice_at_axis(slice(slice_start, slice_end), axis)
|
| 436 |
+
right_chunk = padded[right_slice]
|
| 437 |
+
|
| 438 |
+
if left_pad > period:
|
| 439 |
+
# Chunk is smaller than pad area
|
| 440 |
+
pad_area = _slice_at_axis(slice(left_pad - period, left_pad), axis)
|
| 441 |
+
new_left_pad = left_pad - period
|
| 442 |
+
else:
|
| 443 |
+
# Chunk matches pad area
|
| 444 |
+
pad_area = _slice_at_axis(slice(None, left_pad), axis)
|
| 445 |
+
padded[pad_area] = right_chunk
|
| 446 |
+
|
| 447 |
+
if right_pad > 0:
|
| 448 |
+
# Pad with wrapped values on right side
|
| 449 |
+
# First slice chunk from right side of the non-pad area.
|
| 450 |
+
# Use min(period, right_pad) to ensure that chunk is not larger than
|
| 451 |
+
# pad area.
|
| 452 |
+
slice_start = -right_pad - period
|
| 453 |
+
slice_end = slice_start + min(period, right_pad)
|
| 454 |
+
left_slice = _slice_at_axis(slice(slice_start, slice_end), axis)
|
| 455 |
+
left_chunk = padded[left_slice]
|
| 456 |
+
|
| 457 |
+
if right_pad > period:
|
| 458 |
+
# Chunk is smaller than pad area
|
| 459 |
+
pad_area = _slice_at_axis(
|
| 460 |
+
slice(-right_pad, -right_pad + period), axis)
|
| 461 |
+
new_right_pad = right_pad - period
|
| 462 |
+
else:
|
| 463 |
+
# Chunk matches pad area
|
| 464 |
+
pad_area = _slice_at_axis(slice(-right_pad, None), axis)
|
| 465 |
+
padded[pad_area] = left_chunk
|
| 466 |
+
|
| 467 |
+
return new_left_pad, new_right_pad
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def _as_pairs(x, ndim, as_index=False):
|
| 471 |
+
"""
|
| 472 |
+
Broadcast `x` to an array with the shape (`ndim`, 2).
|
| 473 |
+
|
| 474 |
+
A helper function for `pad` that prepares and validates arguments like
|
| 475 |
+
`pad_width` for iteration in pairs.
|
| 476 |
+
|
| 477 |
+
Parameters
|
| 478 |
+
----------
|
| 479 |
+
x : {None, scalar, array-like}
|
| 480 |
+
The object to broadcast to the shape (`ndim`, 2).
|
| 481 |
+
ndim : int
|
| 482 |
+
Number of pairs the broadcasted `x` will have.
|
| 483 |
+
as_index : bool, optional
|
| 484 |
+
If `x` is not None, try to round each element of `x` to an integer
|
| 485 |
+
(dtype `np.intp`) and ensure every element is positive.
|
| 486 |
+
|
| 487 |
+
Returns
|
| 488 |
+
-------
|
| 489 |
+
pairs : nested iterables, shape (`ndim`, 2)
|
| 490 |
+
The broadcasted version of `x`.
|
| 491 |
+
|
| 492 |
+
Raises
|
| 493 |
+
------
|
| 494 |
+
ValueError
|
| 495 |
+
If `as_index` is True and `x` contains negative elements.
|
| 496 |
+
Or if `x` is not broadcastable to the shape (`ndim`, 2).
|
| 497 |
+
"""
|
| 498 |
+
if x is None:
|
| 499 |
+
# Pass through None as a special case, otherwise np.round(x) fails
|
| 500 |
+
# with an AttributeError
|
| 501 |
+
return ((None, None),) * ndim
|
| 502 |
+
|
| 503 |
+
x = np.array(x)
|
| 504 |
+
if as_index:
|
| 505 |
+
x = np.round(x).astype(np.intp, copy=False)
|
| 506 |
+
|
| 507 |
+
if x.ndim < 3:
|
| 508 |
+
# Optimization: Possibly use faster paths for cases where `x` has
|
| 509 |
+
# only 1 or 2 elements. `np.broadcast_to` could handle these as well
|
| 510 |
+
# but is currently slower
|
| 511 |
+
|
| 512 |
+
if x.size == 1:
|
| 513 |
+
# x was supplied as a single value
|
| 514 |
+
x = x.ravel() # Ensure x[0] works for x.ndim == 0, 1, 2
|
| 515 |
+
if as_index and x < 0:
|
| 516 |
+
raise ValueError("index can't contain negative values")
|
| 517 |
+
return ((x[0], x[0]),) * ndim
|
| 518 |
+
|
| 519 |
+
if x.size == 2 and x.shape != (2, 1):
|
| 520 |
+
# x was supplied with a single value for each side
|
| 521 |
+
# but except case when each dimension has a single value
|
| 522 |
+
# which should be broadcasted to a pair,
|
| 523 |
+
# e.g. [[1], [2]] -> [[1, 1], [2, 2]] not [[1, 2], [1, 2]]
|
| 524 |
+
x = x.ravel() # Ensure x[0], x[1] works
|
| 525 |
+
if as_index and (x[0] < 0 or x[1] < 0):
|
| 526 |
+
raise ValueError("index can't contain negative values")
|
| 527 |
+
return ((x[0], x[1]),) * ndim
|
| 528 |
+
|
| 529 |
+
if as_index and x.min() < 0:
|
| 530 |
+
raise ValueError("index can't contain negative values")
|
| 531 |
+
|
| 532 |
+
# Converting the array with `tolist` seems to improve performance
|
| 533 |
+
# when iterating and indexing the result (see usage in `pad`)
|
| 534 |
+
return np.broadcast_to(x, (ndim, 2)).tolist()
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def _pad_dispatcher(array, pad_width, mode=None, **kwargs):
|
| 538 |
+
return (array,)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
###############################################################################
|
| 542 |
+
# Public functions
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
@array_function_dispatch(_pad_dispatcher, module='numpy')
|
| 546 |
+
def pad(array, pad_width, mode='constant', **kwargs):
|
| 547 |
+
"""
|
| 548 |
+
Pad an array.
|
| 549 |
+
|
| 550 |
+
Parameters
|
| 551 |
+
----------
|
| 552 |
+
array : array_like of rank N
|
| 553 |
+
The array to pad.
|
| 554 |
+
pad_width : {sequence, array_like, int}
|
| 555 |
+
Number of values padded to the edges of each axis.
|
| 556 |
+
``((before_1, after_1), ... (before_N, after_N))`` unique pad widths
|
| 557 |
+
for each axis.
|
| 558 |
+
``(before, after)`` or ``((before, after),)`` yields same before
|
| 559 |
+
and after pad for each axis.
|
| 560 |
+
``(pad,)`` or ``int`` is a shortcut for before = after = pad width
|
| 561 |
+
for all axes.
|
| 562 |
+
mode : str or function, optional
|
| 563 |
+
One of the following string values or a user supplied function.
|
| 564 |
+
|
| 565 |
+
'constant' (default)
|
| 566 |
+
Pads with a constant value.
|
| 567 |
+
'edge'
|
| 568 |
+
Pads with the edge values of array.
|
| 569 |
+
'linear_ramp'
|
| 570 |
+
Pads with the linear ramp between end_value and the
|
| 571 |
+
array edge value.
|
| 572 |
+
'maximum'
|
| 573 |
+
Pads with the maximum value of all or part of the
|
| 574 |
+
vector along each axis.
|
| 575 |
+
'mean'
|
| 576 |
+
Pads with the mean value of all or part of the
|
| 577 |
+
vector along each axis.
|
| 578 |
+
'median'
|
| 579 |
+
Pads with the median value of all or part of the
|
| 580 |
+
vector along each axis.
|
| 581 |
+
'minimum'
|
| 582 |
+
Pads with the minimum value of all or part of the
|
| 583 |
+
vector along each axis.
|
| 584 |
+
'reflect'
|
| 585 |
+
Pads with the reflection of the vector mirrored on
|
| 586 |
+
the first and last values of the vector along each
|
| 587 |
+
axis.
|
| 588 |
+
'symmetric'
|
| 589 |
+
Pads with the reflection of the vector mirrored
|
| 590 |
+
along the edge of the array.
|
| 591 |
+
'wrap'
|
| 592 |
+
Pads with the wrap of the vector along the axis.
|
| 593 |
+
The first values are used to pad the end and the
|
| 594 |
+
end values are used to pad the beginning.
|
| 595 |
+
'empty'
|
| 596 |
+
Pads with undefined values.
|
| 597 |
+
|
| 598 |
+
<function>
|
| 599 |
+
Padding function, see Notes.
|
| 600 |
+
stat_length : sequence or int, optional
|
| 601 |
+
Used in 'maximum', 'mean', 'median', and 'minimum'. Number of
|
| 602 |
+
values at edge of each axis used to calculate the statistic value.
|
| 603 |
+
|
| 604 |
+
``((before_1, after_1), ... (before_N, after_N))`` unique statistic
|
| 605 |
+
lengths for each axis.
|
| 606 |
+
|
| 607 |
+
``(before, after)`` or ``((before, after),)`` yields same before
|
| 608 |
+
and after statistic lengths for each axis.
|
| 609 |
+
|
| 610 |
+
``(stat_length,)`` or ``int`` is a shortcut for
|
| 611 |
+
``before = after = statistic`` length for all axes.
|
| 612 |
+
|
| 613 |
+
Default is ``None``, to use the entire axis.
|
| 614 |
+
constant_values : sequence or scalar, optional
|
| 615 |
+
Used in 'constant'. The values to set the padded values for each
|
| 616 |
+
axis.
|
| 617 |
+
|
| 618 |
+
``((before_1, after_1), ... (before_N, after_N))`` unique pad constants
|
| 619 |
+
for each axis.
|
| 620 |
+
|
| 621 |
+
``(before, after)`` or ``((before, after),)`` yields same before
|
| 622 |
+
and after constants for each axis.
|
| 623 |
+
|
| 624 |
+
``(constant,)`` or ``constant`` is a shortcut for
|
| 625 |
+
``before = after = constant`` for all axes.
|
| 626 |
+
|
| 627 |
+
Default is 0.
|
| 628 |
+
end_values : sequence or scalar, optional
|
| 629 |
+
Used in 'linear_ramp'. The values used for the ending value of the
|
| 630 |
+
linear_ramp and that will form the edge of the padded array.
|
| 631 |
+
|
| 632 |
+
``((before_1, after_1), ... (before_N, after_N))`` unique end values
|
| 633 |
+
for each axis.
|
| 634 |
+
|
| 635 |
+
``(before, after)`` or ``((before, after),)`` yields same before
|
| 636 |
+
and after end values for each axis.
|
| 637 |
+
|
| 638 |
+
``(constant,)`` or ``constant`` is a shortcut for
|
| 639 |
+
``before = after = constant`` for all axes.
|
| 640 |
+
|
| 641 |
+
Default is 0.
|
| 642 |
+
reflect_type : {'even', 'odd'}, optional
|
| 643 |
+
Used in 'reflect', and 'symmetric'. The 'even' style is the
|
| 644 |
+
default with an unaltered reflection around the edge value. For
|
| 645 |
+
the 'odd' style, the extended part of the array is created by
|
| 646 |
+
subtracting the reflected values from two times the edge value.
|
| 647 |
+
|
| 648 |
+
Returns
|
| 649 |
+
-------
|
| 650 |
+
pad : ndarray
|
| 651 |
+
Padded array of rank equal to `array` with shape increased
|
| 652 |
+
according to `pad_width`.
|
| 653 |
+
|
| 654 |
+
Notes
|
| 655 |
+
-----
|
| 656 |
+
For an array with rank greater than 1, some of the padding of later
|
| 657 |
+
axes is calculated from padding of previous axes. This is easiest to
|
| 658 |
+
think about with a rank 2 array where the corners of the padded array
|
| 659 |
+
are calculated by using padded values from the first axis.
|
| 660 |
+
|
| 661 |
+
The padding function, if used, should modify a rank 1 array in-place. It
|
| 662 |
+
has the following signature::
|
| 663 |
+
|
| 664 |
+
padding_func(vector, iaxis_pad_width, iaxis, kwargs)
|
| 665 |
+
|
| 666 |
+
where
|
| 667 |
+
|
| 668 |
+
vector : ndarray
|
| 669 |
+
A rank 1 array already padded with zeros. Padded values are
|
| 670 |
+
vector[:iaxis_pad_width[0]] and vector[-iaxis_pad_width[1]:].
|
| 671 |
+
iaxis_pad_width : tuple
|
| 672 |
+
A 2-tuple of ints, iaxis_pad_width[0] represents the number of
|
| 673 |
+
values padded at the beginning of vector where
|
| 674 |
+
iaxis_pad_width[1] represents the number of values padded at
|
| 675 |
+
the end of vector.
|
| 676 |
+
iaxis : int
|
| 677 |
+
The axis currently being calculated.
|
| 678 |
+
kwargs : dict
|
| 679 |
+
Any keyword arguments the function requires.
|
| 680 |
+
|
| 681 |
+
Examples
|
| 682 |
+
--------
|
| 683 |
+
>>> import numpy as np
|
| 684 |
+
>>> a = [1, 2, 3, 4, 5]
|
| 685 |
+
>>> np.pad(a, (2, 3), 'constant', constant_values=(4, 6))
|
| 686 |
+
array([4, 4, 1, ..., 6, 6, 6])
|
| 687 |
+
|
| 688 |
+
>>> np.pad(a, (2, 3), 'edge')
|
| 689 |
+
array([1, 1, 1, ..., 5, 5, 5])
|
| 690 |
+
|
| 691 |
+
>>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4))
|
| 692 |
+
array([ 5, 3, 1, 2, 3, 4, 5, 2, -1, -4])
|
| 693 |
+
|
| 694 |
+
>>> np.pad(a, (2,), 'maximum')
|
| 695 |
+
array([5, 5, 1, 2, 3, 4, 5, 5, 5])
|
| 696 |
+
|
| 697 |
+
>>> np.pad(a, (2,), 'mean')
|
| 698 |
+
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
|
| 699 |
+
|
| 700 |
+
>>> np.pad(a, (2,), 'median')
|
| 701 |
+
array([3, 3, 1, 2, 3, 4, 5, 3, 3])
|
| 702 |
+
|
| 703 |
+
>>> a = [[1, 2], [3, 4]]
|
| 704 |
+
>>> np.pad(a, ((3, 2), (2, 3)), 'minimum')
|
| 705 |
+
array([[1, 1, 1, 2, 1, 1, 1],
|
| 706 |
+
[1, 1, 1, 2, 1, 1, 1],
|
| 707 |
+
[1, 1, 1, 2, 1, 1, 1],
|
| 708 |
+
[1, 1, 1, 2, 1, 1, 1],
|
| 709 |
+
[3, 3, 3, 4, 3, 3, 3],
|
| 710 |
+
[1, 1, 1, 2, 1, 1, 1],
|
| 711 |
+
[1, 1, 1, 2, 1, 1, 1]])
|
| 712 |
+
|
| 713 |
+
>>> a = [1, 2, 3, 4, 5]
|
| 714 |
+
>>> np.pad(a, (2, 3), 'reflect')
|
| 715 |
+
array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2])
|
| 716 |
+
|
| 717 |
+
>>> np.pad(a, (2, 3), 'reflect', reflect_type='odd')
|
| 718 |
+
array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8])
|
| 719 |
+
|
| 720 |
+
>>> np.pad(a, (2, 3), 'symmetric')
|
| 721 |
+
array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3])
|
| 722 |
+
|
| 723 |
+
>>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd')
|
| 724 |
+
array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7])
|
| 725 |
+
|
| 726 |
+
>>> np.pad(a, (2, 3), 'wrap')
|
| 727 |
+
array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3])
|
| 728 |
+
|
| 729 |
+
>>> def pad_with(vector, pad_width, iaxis, kwargs):
|
| 730 |
+
... pad_value = kwargs.get('padder', 10)
|
| 731 |
+
... vector[:pad_width[0]] = pad_value
|
| 732 |
+
... vector[-pad_width[1]:] = pad_value
|
| 733 |
+
>>> a = np.arange(6)
|
| 734 |
+
>>> a = a.reshape((2, 3))
|
| 735 |
+
>>> np.pad(a, 2, pad_with)
|
| 736 |
+
array([[10, 10, 10, 10, 10, 10, 10],
|
| 737 |
+
[10, 10, 10, 10, 10, 10, 10],
|
| 738 |
+
[10, 10, 0, 1, 2, 10, 10],
|
| 739 |
+
[10, 10, 3, 4, 5, 10, 10],
|
| 740 |
+
[10, 10, 10, 10, 10, 10, 10],
|
| 741 |
+
[10, 10, 10, 10, 10, 10, 10]])
|
| 742 |
+
>>> np.pad(a, 2, pad_with, padder=100)
|
| 743 |
+
array([[100, 100, 100, 100, 100, 100, 100],
|
| 744 |
+
[100, 100, 100, 100, 100, 100, 100],
|
| 745 |
+
[100, 100, 0, 1, 2, 100, 100],
|
| 746 |
+
[100, 100, 3, 4, 5, 100, 100],
|
| 747 |
+
[100, 100, 100, 100, 100, 100, 100],
|
| 748 |
+
[100, 100, 100, 100, 100, 100, 100]])
|
| 749 |
+
"""
|
| 750 |
+
array = np.asarray(array)
|
| 751 |
+
pad_width = np.asarray(pad_width)
|
| 752 |
+
|
| 753 |
+
if not pad_width.dtype.kind == 'i':
|
| 754 |
+
raise TypeError('`pad_width` must be of integral type.')
|
| 755 |
+
|
| 756 |
+
# Broadcast to shape (array.ndim, 2)
|
| 757 |
+
pad_width = _as_pairs(pad_width, array.ndim, as_index=True)
|
| 758 |
+
|
| 759 |
+
if callable(mode):
|
| 760 |
+
# Old behavior: Use user-supplied function with np.apply_along_axis
|
| 761 |
+
function = mode
|
| 762 |
+
# Create a new zero padded array
|
| 763 |
+
padded, _ = _pad_simple(array, pad_width, fill_value=0)
|
| 764 |
+
# And apply along each axis
|
| 765 |
+
|
| 766 |
+
for axis in range(padded.ndim):
|
| 767 |
+
# Iterate using ndindex as in apply_along_axis, but assuming that
|
| 768 |
+
# function operates inplace on the padded array.
|
| 769 |
+
|
| 770 |
+
# view with the iteration axis at the end
|
| 771 |
+
view = np.moveaxis(padded, axis, -1)
|
| 772 |
+
|
| 773 |
+
# compute indices for the iteration axes, and append a trailing
|
| 774 |
+
# ellipsis to prevent 0d arrays decaying to scalars (gh-8642)
|
| 775 |
+
inds = ndindex(view.shape[:-1])
|
| 776 |
+
inds = (ind + (Ellipsis,) for ind in inds)
|
| 777 |
+
for ind in inds:
|
| 778 |
+
function(view[ind], pad_width[axis], axis, kwargs)
|
| 779 |
+
|
| 780 |
+
return padded
|
| 781 |
+
|
| 782 |
+
# Make sure that no unsupported keywords were passed for the current mode
|
| 783 |
+
allowed_kwargs = {
|
| 784 |
+
'empty': [], 'edge': [], 'wrap': [],
|
| 785 |
+
'constant': ['constant_values'],
|
| 786 |
+
'linear_ramp': ['end_values'],
|
| 787 |
+
'maximum': ['stat_length'],
|
| 788 |
+
'mean': ['stat_length'],
|
| 789 |
+
'median': ['stat_length'],
|
| 790 |
+
'minimum': ['stat_length'],
|
| 791 |
+
'reflect': ['reflect_type'],
|
| 792 |
+
'symmetric': ['reflect_type'],
|
| 793 |
+
}
|
| 794 |
+
try:
|
| 795 |
+
unsupported_kwargs = set(kwargs) - set(allowed_kwargs[mode])
|
| 796 |
+
except KeyError:
|
| 797 |
+
raise ValueError("mode '{}' is not supported".format(mode)) from None
|
| 798 |
+
if unsupported_kwargs:
|
| 799 |
+
raise ValueError("unsupported keyword arguments for mode '{}': {}"
|
| 800 |
+
.format(mode, unsupported_kwargs))
|
| 801 |
+
|
| 802 |
+
stat_functions = {"maximum": np.amax, "minimum": np.amin,
|
| 803 |
+
"mean": np.mean, "median": np.median}
|
| 804 |
+
|
| 805 |
+
# Create array with final shape and original values
|
| 806 |
+
# (padded area is undefined)
|
| 807 |
+
padded, original_area_slice = _pad_simple(array, pad_width)
|
| 808 |
+
# And prepare iteration over all dimensions
|
| 809 |
+
# (zipping may be more readable than using enumerate)
|
| 810 |
+
axes = range(padded.ndim)
|
| 811 |
+
|
| 812 |
+
if mode == "constant":
|
| 813 |
+
values = kwargs.get("constant_values", 0)
|
| 814 |
+
values = _as_pairs(values, padded.ndim)
|
| 815 |
+
for axis, width_pair, value_pair in zip(axes, pad_width, values):
|
| 816 |
+
roi = _view_roi(padded, original_area_slice, axis)
|
| 817 |
+
_set_pad_area(roi, axis, width_pair, value_pair)
|
| 818 |
+
|
| 819 |
+
elif mode == "empty":
|
| 820 |
+
pass # Do nothing as _pad_simple already returned the correct result
|
| 821 |
+
|
| 822 |
+
elif array.size == 0:
|
| 823 |
+
# Only modes "constant" and "empty" can extend empty axes, all other
|
| 824 |
+
# modes depend on `array` not being empty
|
| 825 |
+
# -> ensure every empty axis is only "padded with 0"
|
| 826 |
+
for axis, width_pair in zip(axes, pad_width):
|
| 827 |
+
if array.shape[axis] == 0 and any(width_pair):
|
| 828 |
+
raise ValueError(
|
| 829 |
+
"can't extend empty axis {} using modes other than "
|
| 830 |
+
"'constant' or 'empty'".format(axis)
|
| 831 |
+
)
|
| 832 |
+
# passed, don't need to do anything more as _pad_simple already
|
| 833 |
+
# returned the correct result
|
| 834 |
+
|
| 835 |
+
elif mode == "edge":
|
| 836 |
+
for axis, width_pair in zip(axes, pad_width):
|
| 837 |
+
roi = _view_roi(padded, original_area_slice, axis)
|
| 838 |
+
edge_pair = _get_edges(roi, axis, width_pair)
|
| 839 |
+
_set_pad_area(roi, axis, width_pair, edge_pair)
|
| 840 |
+
|
| 841 |
+
elif mode == "linear_ramp":
|
| 842 |
+
end_values = kwargs.get("end_values", 0)
|
| 843 |
+
end_values = _as_pairs(end_values, padded.ndim)
|
| 844 |
+
for axis, width_pair, value_pair in zip(axes, pad_width, end_values):
|
| 845 |
+
roi = _view_roi(padded, original_area_slice, axis)
|
| 846 |
+
ramp_pair = _get_linear_ramps(roi, axis, width_pair, value_pair)
|
| 847 |
+
_set_pad_area(roi, axis, width_pair, ramp_pair)
|
| 848 |
+
|
| 849 |
+
elif mode in stat_functions:
|
| 850 |
+
func = stat_functions[mode]
|
| 851 |
+
length = kwargs.get("stat_length", None)
|
| 852 |
+
length = _as_pairs(length, padded.ndim, as_index=True)
|
| 853 |
+
for axis, width_pair, length_pair in zip(axes, pad_width, length):
|
| 854 |
+
roi = _view_roi(padded, original_area_slice, axis)
|
| 855 |
+
stat_pair = _get_stats(roi, axis, width_pair, length_pair, func)
|
| 856 |
+
_set_pad_area(roi, axis, width_pair, stat_pair)
|
| 857 |
+
|
| 858 |
+
elif mode in {"reflect", "symmetric"}:
|
| 859 |
+
method = kwargs.get("reflect_type", "even")
|
| 860 |
+
include_edge = mode == "symmetric"
|
| 861 |
+
for axis, (left_index, right_index) in zip(axes, pad_width):
|
| 862 |
+
if array.shape[axis] == 1 and (left_index > 0 or right_index > 0):
|
| 863 |
+
# Extending singleton dimension for 'reflect' is legacy
|
| 864 |
+
# behavior; it really should raise an error.
|
| 865 |
+
edge_pair = _get_edges(padded, axis, (left_index, right_index))
|
| 866 |
+
_set_pad_area(
|
| 867 |
+
padded, axis, (left_index, right_index), edge_pair)
|
| 868 |
+
continue
|
| 869 |
+
|
| 870 |
+
roi = _view_roi(padded, original_area_slice, axis)
|
| 871 |
+
while left_index > 0 or right_index > 0:
|
| 872 |
+
# Iteratively pad until dimension is filled with reflected
|
| 873 |
+
# values. This is necessary if the pad area is larger than
|
| 874 |
+
# the length of the original values in the current dimension.
|
| 875 |
+
left_index, right_index = _set_reflect_both(
|
| 876 |
+
roi, axis, (left_index, right_index),
|
| 877 |
+
method, array.shape[axis], include_edge
|
| 878 |
+
)
|
| 879 |
+
|
| 880 |
+
elif mode == "wrap":
|
| 881 |
+
for axis, (left_index, right_index) in zip(axes, pad_width):
|
| 882 |
+
roi = _view_roi(padded, original_area_slice, axis)
|
| 883 |
+
original_period = padded.shape[axis] - right_index - left_index
|
| 884 |
+
while left_index > 0 or right_index > 0:
|
| 885 |
+
# Iteratively pad until dimension is filled with wrapped
|
| 886 |
+
# values. This is necessary if the pad area is larger than
|
| 887 |
+
# the length of the original values in the current dimension.
|
| 888 |
+
left_index, right_index = _set_wrap_both(
|
| 889 |
+
roi, axis, (left_index, right_index), original_period)
|
| 890 |
+
|
| 891 |
+
return padded
|
janus/lib/python3.10/site-packages/numpy/lib/stride_tricks.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ._stride_tricks_impl import (
|
| 2 |
+
__doc__, as_strided, sliding_window_view
|
| 3 |
+
)
|
janus/lib/python3.10/site-packages/numpy/linalg/__init__.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
``numpy.linalg``
|
| 3 |
+
================
|
| 4 |
+
|
| 5 |
+
The NumPy linear algebra functions rely on BLAS and LAPACK to provide efficient
|
| 6 |
+
low level implementations of standard linear algebra algorithms. Those
|
| 7 |
+
libraries may be provided by NumPy itself using C versions of a subset of their
|
| 8 |
+
reference implementations but, when possible, highly optimized libraries that
|
| 9 |
+
take advantage of specialized processor functionality are preferred. Examples
|
| 10 |
+
of such libraries are OpenBLAS, MKL (TM), and ATLAS. Because those libraries
|
| 11 |
+
are multithreaded and processor dependent, environmental variables and external
|
| 12 |
+
packages such as threadpoolctl may be needed to control the number of threads
|
| 13 |
+
or specify the processor architecture.
|
| 14 |
+
|
| 15 |
+
- OpenBLAS: https://www.openblas.net/
|
| 16 |
+
- threadpoolctl: https://github.com/joblib/threadpoolctl
|
| 17 |
+
|
| 18 |
+
Please note that the most-used linear algebra functions in NumPy are present in
|
| 19 |
+
the main ``numpy`` namespace rather than in ``numpy.linalg``. There are:
|
| 20 |
+
``dot``, ``vdot``, ``inner``, ``outer``, ``matmul``, ``tensordot``, ``einsum``,
|
| 21 |
+
``einsum_path`` and ``kron``.
|
| 22 |
+
|
| 23 |
+
Functions present in numpy.linalg are listed below.
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
Matrix and vector products
|
| 27 |
+
--------------------------
|
| 28 |
+
|
| 29 |
+
cross
|
| 30 |
+
multi_dot
|
| 31 |
+
matrix_power
|
| 32 |
+
tensordot
|
| 33 |
+
matmul
|
| 34 |
+
|
| 35 |
+
Decompositions
|
| 36 |
+
--------------
|
| 37 |
+
|
| 38 |
+
cholesky
|
| 39 |
+
outer
|
| 40 |
+
qr
|
| 41 |
+
svd
|
| 42 |
+
svdvals
|
| 43 |
+
|
| 44 |
+
Matrix eigenvalues
|
| 45 |
+
------------------
|
| 46 |
+
|
| 47 |
+
eig
|
| 48 |
+
eigh
|
| 49 |
+
eigvals
|
| 50 |
+
eigvalsh
|
| 51 |
+
|
| 52 |
+
Norms and other numbers
|
| 53 |
+
-----------------------
|
| 54 |
+
|
| 55 |
+
norm
|
| 56 |
+
matrix_norm
|
| 57 |
+
vector_norm
|
| 58 |
+
cond
|
| 59 |
+
det
|
| 60 |
+
matrix_rank
|
| 61 |
+
slogdet
|
| 62 |
+
trace (Array API compatible)
|
| 63 |
+
|
| 64 |
+
Solving equations and inverting matrices
|
| 65 |
+
----------------------------------------
|
| 66 |
+
|
| 67 |
+
solve
|
| 68 |
+
tensorsolve
|
| 69 |
+
lstsq
|
| 70 |
+
inv
|
| 71 |
+
pinv
|
| 72 |
+
tensorinv
|
| 73 |
+
|
| 74 |
+
Other matrix operations
|
| 75 |
+
-----------------------
|
| 76 |
+
|
| 77 |
+
diagonal (Array API compatible)
|
| 78 |
+
matrix_transpose (Array API compatible)
|
| 79 |
+
|
| 80 |
+
Exceptions
|
| 81 |
+
----------
|
| 82 |
+
|
| 83 |
+
LinAlgError
|
| 84 |
+
|
| 85 |
+
"""
|
| 86 |
+
# To get sub-modules
|
| 87 |
+
from . import linalg # deprecated in NumPy 2.0
|
| 88 |
+
from . import _linalg
|
| 89 |
+
from ._linalg import *
|
| 90 |
+
|
| 91 |
+
__all__ = _linalg.__all__.copy()
|
| 92 |
+
|
| 93 |
+
from numpy._pytesttester import PytestTester
|
| 94 |
+
test = PytestTester(__name__)
|
| 95 |
+
del PytestTester
|
janus/lib/python3.10/site-packages/numpy/linalg/__init__.pyi
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from numpy._core.fromnumeric import matrix_transpose
|
| 2 |
+
from numpy._core.numeric import tensordot, vecdot
|
| 3 |
+
|
| 4 |
+
from ._linalg import (
|
| 5 |
+
matrix_power,
|
| 6 |
+
solve,
|
| 7 |
+
tensorsolve,
|
| 8 |
+
tensorinv,
|
| 9 |
+
inv,
|
| 10 |
+
cholesky,
|
| 11 |
+
outer,
|
| 12 |
+
eigvals,
|
| 13 |
+
eigvalsh,
|
| 14 |
+
pinv,
|
| 15 |
+
slogdet,
|
| 16 |
+
det,
|
| 17 |
+
svd,
|
| 18 |
+
svdvals,
|
| 19 |
+
eig,
|
| 20 |
+
eigh,
|
| 21 |
+
lstsq,
|
| 22 |
+
norm,
|
| 23 |
+
matrix_norm,
|
| 24 |
+
vector_norm,
|
| 25 |
+
qr,
|
| 26 |
+
cond,
|
| 27 |
+
matrix_rank,
|
| 28 |
+
multi_dot,
|
| 29 |
+
matmul,
|
| 30 |
+
trace,
|
| 31 |
+
diagonal,
|
| 32 |
+
cross,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
__all__ = [
|
| 36 |
+
"matrix_power",
|
| 37 |
+
"solve",
|
| 38 |
+
"tensorsolve",
|
| 39 |
+
"tensorinv",
|
| 40 |
+
"inv",
|
| 41 |
+
"cholesky",
|
| 42 |
+
"eigvals",
|
| 43 |
+
"eigvalsh",
|
| 44 |
+
"pinv",
|
| 45 |
+
"slogdet",
|
| 46 |
+
"det",
|
| 47 |
+
"svd",
|
| 48 |
+
"svdvals",
|
| 49 |
+
"eig",
|
| 50 |
+
"eigh",
|
| 51 |
+
"lstsq",
|
| 52 |
+
"norm",
|
| 53 |
+
"qr",
|
| 54 |
+
"cond",
|
| 55 |
+
"matrix_rank",
|
| 56 |
+
"LinAlgError",
|
| 57 |
+
"multi_dot",
|
| 58 |
+
"trace",
|
| 59 |
+
"diagonal",
|
| 60 |
+
"cross",
|
| 61 |
+
"outer",
|
| 62 |
+
"tensordot",
|
| 63 |
+
"matmul",
|
| 64 |
+
"matrix_transpose",
|
| 65 |
+
"matrix_norm",
|
| 66 |
+
"vector_norm",
|
| 67 |
+
"vecdot",
|
| 68 |
+
]
|
| 69 |
+
|
| 70 |
+
class LinAlgError(ValueError): ...
|
janus/lib/python3.10/site-packages/numpy/linalg/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (2.24 kB). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/linalg/__pycache__/linalg.cpython-310.pyc
ADDED
|
Binary file (740 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/linalg/_linalg.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
janus/lib/python3.10/site-packages/numpy/linalg/_linalg.pyi
ADDED
|
@@ -0,0 +1,463 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Iterable
|
| 2 |
+
from typing import (
|
| 3 |
+
Literal as L,
|
| 4 |
+
overload,
|
| 5 |
+
TypeAlias,
|
| 6 |
+
TypeVar,
|
| 7 |
+
Any,
|
| 8 |
+
SupportsIndex,
|
| 9 |
+
SupportsInt,
|
| 10 |
+
NamedTuple,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from numpy import (
|
| 15 |
+
# re-exports
|
| 16 |
+
vecdot,
|
| 17 |
+
|
| 18 |
+
# other
|
| 19 |
+
generic,
|
| 20 |
+
floating,
|
| 21 |
+
complexfloating,
|
| 22 |
+
signedinteger,
|
| 23 |
+
unsignedinteger,
|
| 24 |
+
timedelta64,
|
| 25 |
+
object_,
|
| 26 |
+
int32,
|
| 27 |
+
float64,
|
| 28 |
+
complex128,
|
| 29 |
+
)
|
| 30 |
+
from numpy.linalg import LinAlgError
|
| 31 |
+
from numpy._core.fromnumeric import matrix_transpose
|
| 32 |
+
from numpy._core.numeric import tensordot
|
| 33 |
+
from numpy._typing import (
|
| 34 |
+
NDArray,
|
| 35 |
+
ArrayLike,
|
| 36 |
+
DTypeLike,
|
| 37 |
+
_ArrayLikeUnknown,
|
| 38 |
+
_ArrayLikeBool_co,
|
| 39 |
+
_ArrayLikeInt_co,
|
| 40 |
+
_ArrayLikeUInt_co,
|
| 41 |
+
_ArrayLikeFloat_co,
|
| 42 |
+
_ArrayLikeComplex_co,
|
| 43 |
+
_ArrayLikeTD64_co,
|
| 44 |
+
_ArrayLikeObject_co,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
__all__ = [
|
| 48 |
+
"matrix_power",
|
| 49 |
+
"solve",
|
| 50 |
+
"tensorsolve",
|
| 51 |
+
"tensorinv",
|
| 52 |
+
"inv",
|
| 53 |
+
"cholesky",
|
| 54 |
+
"eigvals",
|
| 55 |
+
"eigvalsh",
|
| 56 |
+
"pinv",
|
| 57 |
+
"slogdet",
|
| 58 |
+
"det",
|
| 59 |
+
"svd",
|
| 60 |
+
"svdvals",
|
| 61 |
+
"eig",
|
| 62 |
+
"eigh",
|
| 63 |
+
"lstsq",
|
| 64 |
+
"norm",
|
| 65 |
+
"qr",
|
| 66 |
+
"cond",
|
| 67 |
+
"matrix_rank",
|
| 68 |
+
"LinAlgError",
|
| 69 |
+
"multi_dot",
|
| 70 |
+
"trace",
|
| 71 |
+
"diagonal",
|
| 72 |
+
"cross",
|
| 73 |
+
"outer",
|
| 74 |
+
"tensordot",
|
| 75 |
+
"matmul",
|
| 76 |
+
"matrix_transpose",
|
| 77 |
+
"matrix_norm",
|
| 78 |
+
"vector_norm",
|
| 79 |
+
"vecdot",
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
_T = TypeVar("_T")
|
| 83 |
+
_ArrayType = TypeVar("_ArrayType", bound=NDArray[Any])
|
| 84 |
+
_SCT2 = TypeVar("_SCT2", bound=generic, covariant=True)
|
| 85 |
+
|
| 86 |
+
_2Tuple: TypeAlias = tuple[_T, _T]
|
| 87 |
+
_ModeKind: TypeAlias = L["reduced", "complete", "r", "raw"]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class EigResult(NamedTuple):
|
| 91 |
+
eigenvalues: NDArray[Any]
|
| 92 |
+
eigenvectors: NDArray[Any]
|
| 93 |
+
|
| 94 |
+
class EighResult(NamedTuple):
|
| 95 |
+
eigenvalues: NDArray[Any]
|
| 96 |
+
eigenvectors: NDArray[Any]
|
| 97 |
+
|
| 98 |
+
class QRResult(NamedTuple):
|
| 99 |
+
Q: NDArray[Any]
|
| 100 |
+
R: NDArray[Any]
|
| 101 |
+
|
| 102 |
+
class SlogdetResult(NamedTuple):
|
| 103 |
+
# TODO: `sign` and `logabsdet` are scalars for input 2D arrays and
|
| 104 |
+
# a `(x.ndim - 2)`` dimensionl arrays otherwise
|
| 105 |
+
sign: Any
|
| 106 |
+
logabsdet: Any
|
| 107 |
+
|
| 108 |
+
class SVDResult(NamedTuple):
|
| 109 |
+
U: NDArray[Any]
|
| 110 |
+
S: NDArray[Any]
|
| 111 |
+
Vh: NDArray[Any]
|
| 112 |
+
|
| 113 |
+
@overload
|
| 114 |
+
def tensorsolve(
|
| 115 |
+
a: _ArrayLikeInt_co,
|
| 116 |
+
b: _ArrayLikeInt_co,
|
| 117 |
+
axes: None | Iterable[int] =...,
|
| 118 |
+
) -> NDArray[float64]: ...
|
| 119 |
+
@overload
|
| 120 |
+
def tensorsolve(
|
| 121 |
+
a: _ArrayLikeFloat_co,
|
| 122 |
+
b: _ArrayLikeFloat_co,
|
| 123 |
+
axes: None | Iterable[int] =...,
|
| 124 |
+
) -> NDArray[floating[Any]]: ...
|
| 125 |
+
@overload
|
| 126 |
+
def tensorsolve(
|
| 127 |
+
a: _ArrayLikeComplex_co,
|
| 128 |
+
b: _ArrayLikeComplex_co,
|
| 129 |
+
axes: None | Iterable[int] =...,
|
| 130 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
| 131 |
+
|
| 132 |
+
@overload
|
| 133 |
+
def solve(
|
| 134 |
+
a: _ArrayLikeInt_co,
|
| 135 |
+
b: _ArrayLikeInt_co,
|
| 136 |
+
) -> NDArray[float64]: ...
|
| 137 |
+
@overload
|
| 138 |
+
def solve(
|
| 139 |
+
a: _ArrayLikeFloat_co,
|
| 140 |
+
b: _ArrayLikeFloat_co,
|
| 141 |
+
) -> NDArray[floating[Any]]: ...
|
| 142 |
+
@overload
|
| 143 |
+
def solve(
|
| 144 |
+
a: _ArrayLikeComplex_co,
|
| 145 |
+
b: _ArrayLikeComplex_co,
|
| 146 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
| 147 |
+
|
| 148 |
+
@overload
|
| 149 |
+
def tensorinv(
|
| 150 |
+
a: _ArrayLikeInt_co,
|
| 151 |
+
ind: int = ...,
|
| 152 |
+
) -> NDArray[float64]: ...
|
| 153 |
+
@overload
|
| 154 |
+
def tensorinv(
|
| 155 |
+
a: _ArrayLikeFloat_co,
|
| 156 |
+
ind: int = ...,
|
| 157 |
+
) -> NDArray[floating[Any]]: ...
|
| 158 |
+
@overload
|
| 159 |
+
def tensorinv(
|
| 160 |
+
a: _ArrayLikeComplex_co,
|
| 161 |
+
ind: int = ...,
|
| 162 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
| 163 |
+
|
| 164 |
+
@overload
|
| 165 |
+
def inv(a: _ArrayLikeInt_co) -> NDArray[float64]: ...
|
| 166 |
+
@overload
|
| 167 |
+
def inv(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...
|
| 168 |
+
@overload
|
| 169 |
+
def inv(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
|
| 170 |
+
|
| 171 |
+
# TODO: The supported input and output dtypes are dependent on the value of `n`.
|
| 172 |
+
# For example: `n < 0` always casts integer types to float64
|
| 173 |
+
def matrix_power(
|
| 174 |
+
a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
|
| 175 |
+
n: SupportsIndex,
|
| 176 |
+
) -> NDArray[Any]: ...
|
| 177 |
+
|
| 178 |
+
@overload
|
| 179 |
+
def cholesky(a: _ArrayLikeInt_co) -> NDArray[float64]: ...
|
| 180 |
+
@overload
|
| 181 |
+
def cholesky(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...
|
| 182 |
+
@overload
|
| 183 |
+
def cholesky(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
|
| 184 |
+
|
| 185 |
+
@overload
|
| 186 |
+
def outer(x1: _ArrayLikeUnknown, x2: _ArrayLikeUnknown) -> NDArray[Any]: ...
|
| 187 |
+
@overload
|
| 188 |
+
def outer(x1: _ArrayLikeBool_co, x2: _ArrayLikeBool_co) -> NDArray[np.bool]: ...
|
| 189 |
+
@overload
|
| 190 |
+
def outer(x1: _ArrayLikeUInt_co, x2: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ...
|
| 191 |
+
@overload
|
| 192 |
+
def outer(x1: _ArrayLikeInt_co, x2: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
|
| 193 |
+
@overload
|
| 194 |
+
def outer(x1: _ArrayLikeFloat_co, x2: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...
|
| 195 |
+
@overload
|
| 196 |
+
def outer(
|
| 197 |
+
x1: _ArrayLikeComplex_co,
|
| 198 |
+
x2: _ArrayLikeComplex_co,
|
| 199 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
| 200 |
+
@overload
|
| 201 |
+
def outer(
|
| 202 |
+
x1: _ArrayLikeTD64_co,
|
| 203 |
+
x2: _ArrayLikeTD64_co,
|
| 204 |
+
out: None = ...,
|
| 205 |
+
) -> NDArray[timedelta64]: ...
|
| 206 |
+
@overload
|
| 207 |
+
def outer(x1: _ArrayLikeObject_co, x2: _ArrayLikeObject_co) -> NDArray[object_]: ...
|
| 208 |
+
@overload
|
| 209 |
+
def outer(
|
| 210 |
+
x1: _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeObject_co,
|
| 211 |
+
x2: _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeObject_co,
|
| 212 |
+
) -> _ArrayType: ...
|
| 213 |
+
|
| 214 |
+
@overload
|
| 215 |
+
def qr(a: _ArrayLikeInt_co, mode: _ModeKind = ...) -> QRResult: ...
|
| 216 |
+
@overload
|
| 217 |
+
def qr(a: _ArrayLikeFloat_co, mode: _ModeKind = ...) -> QRResult: ...
|
| 218 |
+
@overload
|
| 219 |
+
def qr(a: _ArrayLikeComplex_co, mode: _ModeKind = ...) -> QRResult: ...
|
| 220 |
+
|
| 221 |
+
@overload
|
| 222 |
+
def eigvals(a: _ArrayLikeInt_co) -> NDArray[float64] | NDArray[complex128]: ...
|
| 223 |
+
@overload
|
| 224 |
+
def eigvals(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]] | NDArray[complexfloating[Any, Any]]: ...
|
| 225 |
+
@overload
|
| 226 |
+
def eigvals(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
|
| 227 |
+
|
| 228 |
+
@overload
|
| 229 |
+
def eigvalsh(a: _ArrayLikeInt_co, UPLO: L["L", "U", "l", "u"] = ...) -> NDArray[float64]: ...
|
| 230 |
+
@overload
|
| 231 |
+
def eigvalsh(a: _ArrayLikeComplex_co, UPLO: L["L", "U", "l", "u"] = ...) -> NDArray[floating[Any]]: ...
|
| 232 |
+
|
| 233 |
+
@overload
|
| 234 |
+
def eig(a: _ArrayLikeInt_co) -> EigResult: ...
|
| 235 |
+
@overload
|
| 236 |
+
def eig(a: _ArrayLikeFloat_co) -> EigResult: ...
|
| 237 |
+
@overload
|
| 238 |
+
def eig(a: _ArrayLikeComplex_co) -> EigResult: ...
|
| 239 |
+
|
| 240 |
+
@overload
|
| 241 |
+
def eigh(
|
| 242 |
+
a: _ArrayLikeInt_co,
|
| 243 |
+
UPLO: L["L", "U", "l", "u"] = ...,
|
| 244 |
+
) -> EighResult: ...
|
| 245 |
+
@overload
|
| 246 |
+
def eigh(
|
| 247 |
+
a: _ArrayLikeFloat_co,
|
| 248 |
+
UPLO: L["L", "U", "l", "u"] = ...,
|
| 249 |
+
) -> EighResult: ...
|
| 250 |
+
@overload
|
| 251 |
+
def eigh(
|
| 252 |
+
a: _ArrayLikeComplex_co,
|
| 253 |
+
UPLO: L["L", "U", "l", "u"] = ...,
|
| 254 |
+
) -> EighResult: ...
|
| 255 |
+
|
| 256 |
+
@overload
|
| 257 |
+
def svd(
|
| 258 |
+
a: _ArrayLikeInt_co,
|
| 259 |
+
full_matrices: bool = ...,
|
| 260 |
+
compute_uv: L[True] = ...,
|
| 261 |
+
hermitian: bool = ...,
|
| 262 |
+
) -> SVDResult: ...
|
| 263 |
+
@overload
|
| 264 |
+
def svd(
|
| 265 |
+
a: _ArrayLikeFloat_co,
|
| 266 |
+
full_matrices: bool = ...,
|
| 267 |
+
compute_uv: L[True] = ...,
|
| 268 |
+
hermitian: bool = ...,
|
| 269 |
+
) -> SVDResult: ...
|
| 270 |
+
@overload
|
| 271 |
+
def svd(
|
| 272 |
+
a: _ArrayLikeComplex_co,
|
| 273 |
+
full_matrices: bool = ...,
|
| 274 |
+
compute_uv: L[True] = ...,
|
| 275 |
+
hermitian: bool = ...,
|
| 276 |
+
) -> SVDResult: ...
|
| 277 |
+
@overload
|
| 278 |
+
def svd(
|
| 279 |
+
a: _ArrayLikeInt_co,
|
| 280 |
+
full_matrices: bool = ...,
|
| 281 |
+
compute_uv: L[False] = ...,
|
| 282 |
+
hermitian: bool = ...,
|
| 283 |
+
) -> NDArray[float64]: ...
|
| 284 |
+
@overload
|
| 285 |
+
def svd(
|
| 286 |
+
a: _ArrayLikeComplex_co,
|
| 287 |
+
full_matrices: bool = ...,
|
| 288 |
+
compute_uv: L[False] = ...,
|
| 289 |
+
hermitian: bool = ...,
|
| 290 |
+
) -> NDArray[floating[Any]]: ...
|
| 291 |
+
|
| 292 |
+
def svdvals(
|
| 293 |
+
x: _ArrayLikeInt_co | _ArrayLikeFloat_co | _ArrayLikeComplex_co
|
| 294 |
+
) -> NDArray[floating[Any]]: ...
|
| 295 |
+
|
| 296 |
+
# TODO: Returns a scalar for 2D arrays and
|
| 297 |
+
# a `(x.ndim - 2)`` dimensionl array otherwise
|
| 298 |
+
def cond(x: _ArrayLikeComplex_co, p: None | float | L["fro", "nuc"] = ...) -> Any: ...
|
| 299 |
+
|
| 300 |
+
# TODO: Returns `int` for <2D arrays and `intp` otherwise
|
| 301 |
+
def matrix_rank(
|
| 302 |
+
A: _ArrayLikeComplex_co,
|
| 303 |
+
tol: None | _ArrayLikeFloat_co = ...,
|
| 304 |
+
hermitian: bool = ...,
|
| 305 |
+
*,
|
| 306 |
+
rtol: None | _ArrayLikeFloat_co = ...,
|
| 307 |
+
) -> Any: ...
|
| 308 |
+
|
| 309 |
+
@overload
|
| 310 |
+
def pinv(
|
| 311 |
+
a: _ArrayLikeInt_co,
|
| 312 |
+
rcond: _ArrayLikeFloat_co = ...,
|
| 313 |
+
hermitian: bool = ...,
|
| 314 |
+
) -> NDArray[float64]: ...
|
| 315 |
+
@overload
|
| 316 |
+
def pinv(
|
| 317 |
+
a: _ArrayLikeFloat_co,
|
| 318 |
+
rcond: _ArrayLikeFloat_co = ...,
|
| 319 |
+
hermitian: bool = ...,
|
| 320 |
+
) -> NDArray[floating[Any]]: ...
|
| 321 |
+
@overload
|
| 322 |
+
def pinv(
|
| 323 |
+
a: _ArrayLikeComplex_co,
|
| 324 |
+
rcond: _ArrayLikeFloat_co = ...,
|
| 325 |
+
hermitian: bool = ...,
|
| 326 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
| 327 |
+
|
| 328 |
+
# TODO: Returns a 2-tuple of scalars for 2D arrays and
|
| 329 |
+
# a 2-tuple of `(a.ndim - 2)`` dimensionl arrays otherwise
|
| 330 |
+
def slogdet(a: _ArrayLikeComplex_co) -> SlogdetResult: ...
|
| 331 |
+
|
| 332 |
+
# TODO: Returns a 2-tuple of scalars for 2D arrays and
|
| 333 |
+
# a 2-tuple of `(a.ndim - 2)`` dimensionl arrays otherwise
|
| 334 |
+
def det(a: _ArrayLikeComplex_co) -> Any: ...
|
| 335 |
+
|
| 336 |
+
@overload
|
| 337 |
+
def lstsq(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, rcond: None | float = ...) -> tuple[
|
| 338 |
+
NDArray[float64],
|
| 339 |
+
NDArray[float64],
|
| 340 |
+
int32,
|
| 341 |
+
NDArray[float64],
|
| 342 |
+
]: ...
|
| 343 |
+
@overload
|
| 344 |
+
def lstsq(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, rcond: None | float = ...) -> tuple[
|
| 345 |
+
NDArray[floating[Any]],
|
| 346 |
+
NDArray[floating[Any]],
|
| 347 |
+
int32,
|
| 348 |
+
NDArray[floating[Any]],
|
| 349 |
+
]: ...
|
| 350 |
+
@overload
|
| 351 |
+
def lstsq(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, rcond: None | float = ...) -> tuple[
|
| 352 |
+
NDArray[complexfloating[Any, Any]],
|
| 353 |
+
NDArray[floating[Any]],
|
| 354 |
+
int32,
|
| 355 |
+
NDArray[floating[Any]],
|
| 356 |
+
]: ...
|
| 357 |
+
|
| 358 |
+
@overload
|
| 359 |
+
def norm(
|
| 360 |
+
x: ArrayLike,
|
| 361 |
+
ord: None | float | L["fro", "nuc"] = ...,
|
| 362 |
+
axis: None = ...,
|
| 363 |
+
keepdims: bool = ...,
|
| 364 |
+
) -> floating[Any]: ...
|
| 365 |
+
@overload
|
| 366 |
+
def norm(
|
| 367 |
+
x: ArrayLike,
|
| 368 |
+
ord: None | float | L["fro", "nuc"] = ...,
|
| 369 |
+
axis: SupportsInt | SupportsIndex | tuple[int, ...] = ...,
|
| 370 |
+
keepdims: bool = ...,
|
| 371 |
+
) -> Any: ...
|
| 372 |
+
|
| 373 |
+
@overload
|
| 374 |
+
def matrix_norm(
|
| 375 |
+
x: ArrayLike,
|
| 376 |
+
ord: None | float | L["fro", "nuc"] = ...,
|
| 377 |
+
keepdims: bool = ...,
|
| 378 |
+
) -> floating[Any]: ...
|
| 379 |
+
@overload
|
| 380 |
+
def matrix_norm(
|
| 381 |
+
x: ArrayLike,
|
| 382 |
+
ord: None | float | L["fro", "nuc"] = ...,
|
| 383 |
+
keepdims: bool = ...,
|
| 384 |
+
) -> Any: ...
|
| 385 |
+
|
| 386 |
+
@overload
|
| 387 |
+
def vector_norm(
|
| 388 |
+
x: ArrayLike,
|
| 389 |
+
axis: None = ...,
|
| 390 |
+
ord: None | float = ...,
|
| 391 |
+
keepdims: bool = ...,
|
| 392 |
+
) -> floating[Any]: ...
|
| 393 |
+
@overload
|
| 394 |
+
def vector_norm(
|
| 395 |
+
x: ArrayLike,
|
| 396 |
+
axis: SupportsInt | SupportsIndex | tuple[int, ...] = ...,
|
| 397 |
+
ord: None | float = ...,
|
| 398 |
+
keepdims: bool = ...,
|
| 399 |
+
) -> Any: ...
|
| 400 |
+
|
| 401 |
+
# TODO: Returns a scalar or array
|
| 402 |
+
def multi_dot(
|
| 403 |
+
arrays: Iterable[_ArrayLikeComplex_co | _ArrayLikeObject_co | _ArrayLikeTD64_co],
|
| 404 |
+
*,
|
| 405 |
+
out: None | NDArray[Any] = ...,
|
| 406 |
+
) -> Any: ...
|
| 407 |
+
|
| 408 |
+
def diagonal(
|
| 409 |
+
x: ArrayLike, # >= 2D array
|
| 410 |
+
offset: SupportsIndex = ...,
|
| 411 |
+
) -> NDArray[Any]: ...
|
| 412 |
+
|
| 413 |
+
def trace(
|
| 414 |
+
x: ArrayLike, # >= 2D array
|
| 415 |
+
offset: SupportsIndex = ...,
|
| 416 |
+
dtype: DTypeLike = ...,
|
| 417 |
+
) -> Any: ...
|
| 418 |
+
|
| 419 |
+
@overload
|
| 420 |
+
def cross(
|
| 421 |
+
a: _ArrayLikeUInt_co,
|
| 422 |
+
b: _ArrayLikeUInt_co,
|
| 423 |
+
axis: int = ...,
|
| 424 |
+
) -> NDArray[unsignedinteger[Any]]: ...
|
| 425 |
+
@overload
|
| 426 |
+
def cross(
|
| 427 |
+
a: _ArrayLikeInt_co,
|
| 428 |
+
b: _ArrayLikeInt_co,
|
| 429 |
+
axis: int = ...,
|
| 430 |
+
) -> NDArray[signedinteger[Any]]: ...
|
| 431 |
+
@overload
|
| 432 |
+
def cross(
|
| 433 |
+
a: _ArrayLikeFloat_co,
|
| 434 |
+
b: _ArrayLikeFloat_co,
|
| 435 |
+
axis: int = ...,
|
| 436 |
+
) -> NDArray[floating[Any]]: ...
|
| 437 |
+
@overload
|
| 438 |
+
def cross(
|
| 439 |
+
a: _ArrayLikeComplex_co,
|
| 440 |
+
b: _ArrayLikeComplex_co,
|
| 441 |
+
axis: int = ...,
|
| 442 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
| 443 |
+
|
| 444 |
+
@overload
|
| 445 |
+
def matmul(
|
| 446 |
+
x1: _ArrayLikeInt_co,
|
| 447 |
+
x2: _ArrayLikeInt_co,
|
| 448 |
+
) -> NDArray[signedinteger[Any]]: ...
|
| 449 |
+
@overload
|
| 450 |
+
def matmul(
|
| 451 |
+
x1: _ArrayLikeUInt_co,
|
| 452 |
+
x2: _ArrayLikeUInt_co,
|
| 453 |
+
) -> NDArray[unsignedinteger[Any]]: ...
|
| 454 |
+
@overload
|
| 455 |
+
def matmul(
|
| 456 |
+
x1: _ArrayLikeFloat_co,
|
| 457 |
+
x2: _ArrayLikeFloat_co,
|
| 458 |
+
) -> NDArray[floating[Any]]: ...
|
| 459 |
+
@overload
|
| 460 |
+
def matmul(
|
| 461 |
+
x1: _ArrayLikeComplex_co,
|
| 462 |
+
x2: _ArrayLikeComplex_co,
|
| 463 |
+
) -> NDArray[complexfloating[Any, Any]]: ...
|
janus/lib/python3.10/site-packages/numpy/linalg/lapack_lite.cpython-310-x86_64-linux-gnu.so
ADDED
|
Binary file (30 kB). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/linalg/linalg.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(attr_name):
|
| 2 |
+
import warnings
|
| 3 |
+
from numpy.linalg import _linalg
|
| 4 |
+
ret = getattr(_linalg, attr_name, None)
|
| 5 |
+
if ret is None:
|
| 6 |
+
raise AttributeError(
|
| 7 |
+
f"module 'numpy.linalg.linalg' has no attribute {attr_name}")
|
| 8 |
+
warnings.warn(
|
| 9 |
+
"The numpy.linalg.linalg has been made private and renamed to "
|
| 10 |
+
"numpy.linalg._linalg. All public functions exported by it are "
|
| 11 |
+
f"available from numpy.linalg. Please use numpy.linalg.{attr_name} "
|
| 12 |
+
"instead.",
|
| 13 |
+
DeprecationWarning,
|
| 14 |
+
stacklevel=3
|
| 15 |
+
)
|
| 16 |
+
return ret
|
janus/lib/python3.10/site-packages/numpy/linalg/tests/__init__.py
ADDED
|
File without changes
|
janus/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (169 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_deprecations.cpython-310.pyc
ADDED
|
Binary file (810 Bytes). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_linalg.cpython-310.pyc
ADDED
|
Binary file (70.2 kB). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/linalg/tests/__pycache__/test_regression.cpython-310.pyc
ADDED
|
Binary file (5.83 kB). View file
|
|
|
janus/lib/python3.10/site-packages/numpy/linalg/tests/test_deprecations.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Test deprecation and future warnings.
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numpy.testing import assert_warns
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_qr_mode_full_future_warning():
|
| 9 |
+
"""Check mode='full' FutureWarning.
|
| 10 |
+
|
| 11 |
+
In numpy 1.8 the mode options 'full' and 'economic' in linalg.qr were
|
| 12 |
+
deprecated. The release date will probably be sometime in the summer
|
| 13 |
+
of 2013.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
a = np.eye(2)
|
| 17 |
+
assert_warns(DeprecationWarning, np.linalg.qr, a, mode='full')
|
| 18 |
+
assert_warns(DeprecationWarning, np.linalg.qr, a, mode='f')
|
| 19 |
+
assert_warns(DeprecationWarning, np.linalg.qr, a, mode='economic')
|
| 20 |
+
assert_warns(DeprecationWarning, np.linalg.qr, a, mode='e')
|
janus/lib/python3.10/site-packages/numpy/linalg/tests/test_linalg.py
ADDED
|
@@ -0,0 +1,2386 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" Test functions for linalg module
|
| 2 |
+
|
| 3 |
+
"""
|
| 4 |
+
import os
|
| 5 |
+
import sys
|
| 6 |
+
import itertools
|
| 7 |
+
import threading
|
| 8 |
+
import traceback
|
| 9 |
+
import textwrap
|
| 10 |
+
import subprocess
|
| 11 |
+
import pytest
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
from numpy import array, single, double, csingle, cdouble, dot, identity, matmul
|
| 15 |
+
from numpy._core import swapaxes
|
| 16 |
+
from numpy.exceptions import AxisError
|
| 17 |
+
from numpy import multiply, atleast_2d, inf, asarray
|
| 18 |
+
from numpy import linalg
|
| 19 |
+
from numpy.linalg import matrix_power, norm, matrix_rank, multi_dot, LinAlgError
|
| 20 |
+
from numpy.linalg._linalg import _multi_dot_matrix_chain_order
|
| 21 |
+
from numpy.testing import (
|
| 22 |
+
assert_, assert_equal, assert_raises, assert_array_equal,
|
| 23 |
+
assert_almost_equal, assert_allclose, suppress_warnings,
|
| 24 |
+
assert_raises_regex, HAS_LAPACK64, IS_WASM
|
| 25 |
+
)
|
| 26 |
+
try:
|
| 27 |
+
import numpy.linalg.lapack_lite
|
| 28 |
+
except ImportError:
|
| 29 |
+
# May be broken when numpy was built without BLAS/LAPACK present
|
| 30 |
+
# If so, ensure we don't break the whole test suite - the `lapack_lite`
|
| 31 |
+
# submodule should be removed, it's only used in two tests in this file.
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def consistent_subclass(out, in_):
|
| 36 |
+
# For ndarray subclass input, our output should have the same subclass
|
| 37 |
+
# (non-ndarray input gets converted to ndarray).
|
| 38 |
+
return type(out) is (type(in_) if isinstance(in_, np.ndarray)
|
| 39 |
+
else np.ndarray)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
old_assert_almost_equal = assert_almost_equal
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def assert_almost_equal(a, b, single_decimal=6, double_decimal=12, **kw):
|
| 46 |
+
if asarray(a).dtype.type in (single, csingle):
|
| 47 |
+
decimal = single_decimal
|
| 48 |
+
else:
|
| 49 |
+
decimal = double_decimal
|
| 50 |
+
old_assert_almost_equal(a, b, decimal=decimal, **kw)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_real_dtype(dtype):
|
| 54 |
+
return {single: single, double: double,
|
| 55 |
+
csingle: single, cdouble: double}[dtype]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def get_complex_dtype(dtype):
|
| 59 |
+
return {single: csingle, double: cdouble,
|
| 60 |
+
csingle: csingle, cdouble: cdouble}[dtype]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def get_rtol(dtype):
|
| 64 |
+
# Choose a safe rtol
|
| 65 |
+
if dtype in (single, csingle):
|
| 66 |
+
return 1e-5
|
| 67 |
+
else:
|
| 68 |
+
return 1e-11
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# used to categorize tests
|
| 72 |
+
all_tags = {
|
| 73 |
+
'square', 'nonsquare', 'hermitian', # mutually exclusive
|
| 74 |
+
'generalized', 'size-0', 'strided' # optional additions
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class LinalgCase:
|
| 79 |
+
def __init__(self, name, a, b, tags=set()):
|
| 80 |
+
"""
|
| 81 |
+
A bundle of arguments to be passed to a test case, with an identifying
|
| 82 |
+
name, the operands a and b, and a set of tags to filter the tests
|
| 83 |
+
"""
|
| 84 |
+
assert_(isinstance(name, str))
|
| 85 |
+
self.name = name
|
| 86 |
+
self.a = a
|
| 87 |
+
self.b = b
|
| 88 |
+
self.tags = frozenset(tags) # prevent shared tags
|
| 89 |
+
|
| 90 |
+
def check(self, do):
|
| 91 |
+
"""
|
| 92 |
+
Run the function `do` on this test case, expanding arguments
|
| 93 |
+
"""
|
| 94 |
+
do(self.a, self.b, tags=self.tags)
|
| 95 |
+
|
| 96 |
+
def __repr__(self):
|
| 97 |
+
return f'<LinalgCase: {self.name}>'
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def apply_tag(tag, cases):
|
| 101 |
+
"""
|
| 102 |
+
Add the given tag (a string) to each of the cases (a list of LinalgCase
|
| 103 |
+
objects)
|
| 104 |
+
"""
|
| 105 |
+
assert tag in all_tags, "Invalid tag"
|
| 106 |
+
for case in cases:
|
| 107 |
+
case.tags = case.tags | {tag}
|
| 108 |
+
return cases
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
#
|
| 112 |
+
# Base test cases
|
| 113 |
+
#
|
| 114 |
+
|
| 115 |
+
np.random.seed(1234)
|
| 116 |
+
|
| 117 |
+
CASES = []
|
| 118 |
+
|
| 119 |
+
# square test cases
|
| 120 |
+
CASES += apply_tag('square', [
|
| 121 |
+
LinalgCase("single",
|
| 122 |
+
array([[1., 2.], [3., 4.]], dtype=single),
|
| 123 |
+
array([2., 1.], dtype=single)),
|
| 124 |
+
LinalgCase("double",
|
| 125 |
+
array([[1., 2.], [3., 4.]], dtype=double),
|
| 126 |
+
array([2., 1.], dtype=double)),
|
| 127 |
+
LinalgCase("double_2",
|
| 128 |
+
array([[1., 2.], [3., 4.]], dtype=double),
|
| 129 |
+
array([[2., 1., 4.], [3., 4., 6.]], dtype=double)),
|
| 130 |
+
LinalgCase("csingle",
|
| 131 |
+
array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=csingle),
|
| 132 |
+
array([2. + 1j, 1. + 2j], dtype=csingle)),
|
| 133 |
+
LinalgCase("cdouble",
|
| 134 |
+
array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=cdouble),
|
| 135 |
+
array([2. + 1j, 1. + 2j], dtype=cdouble)),
|
| 136 |
+
LinalgCase("cdouble_2",
|
| 137 |
+
array([[1. + 2j, 2 + 3j], [3 + 4j, 4 + 5j]], dtype=cdouble),
|
| 138 |
+
array([[2. + 1j, 1. + 2j, 1 + 3j], [1 - 2j, 1 - 3j, 1 - 6j]], dtype=cdouble)),
|
| 139 |
+
LinalgCase("0x0",
|
| 140 |
+
np.empty((0, 0), dtype=double),
|
| 141 |
+
np.empty((0,), dtype=double),
|
| 142 |
+
tags={'size-0'}),
|
| 143 |
+
LinalgCase("8x8",
|
| 144 |
+
np.random.rand(8, 8),
|
| 145 |
+
np.random.rand(8)),
|
| 146 |
+
LinalgCase("1x1",
|
| 147 |
+
np.random.rand(1, 1),
|
| 148 |
+
np.random.rand(1)),
|
| 149 |
+
LinalgCase("nonarray",
|
| 150 |
+
[[1, 2], [3, 4]],
|
| 151 |
+
[2, 1]),
|
| 152 |
+
])
|
| 153 |
+
|
| 154 |
+
# non-square test-cases
|
| 155 |
+
CASES += apply_tag('nonsquare', [
|
| 156 |
+
LinalgCase("single_nsq_1",
|
| 157 |
+
array([[1., 2., 3.], [3., 4., 6.]], dtype=single),
|
| 158 |
+
array([2., 1.], dtype=single)),
|
| 159 |
+
LinalgCase("single_nsq_2",
|
| 160 |
+
array([[1., 2.], [3., 4.], [5., 6.]], dtype=single),
|
| 161 |
+
array([2., 1., 3.], dtype=single)),
|
| 162 |
+
LinalgCase("double_nsq_1",
|
| 163 |
+
array([[1., 2., 3.], [3., 4., 6.]], dtype=double),
|
| 164 |
+
array([2., 1.], dtype=double)),
|
| 165 |
+
LinalgCase("double_nsq_2",
|
| 166 |
+
array([[1., 2.], [3., 4.], [5., 6.]], dtype=double),
|
| 167 |
+
array([2., 1., 3.], dtype=double)),
|
| 168 |
+
LinalgCase("csingle_nsq_1",
|
| 169 |
+
array(
|
| 170 |
+
[[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=csingle),
|
| 171 |
+
array([2. + 1j, 1. + 2j], dtype=csingle)),
|
| 172 |
+
LinalgCase("csingle_nsq_2",
|
| 173 |
+
array(
|
| 174 |
+
[[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=csingle),
|
| 175 |
+
array([2. + 1j, 1. + 2j, 3. - 3j], dtype=csingle)),
|
| 176 |
+
LinalgCase("cdouble_nsq_1",
|
| 177 |
+
array(
|
| 178 |
+
[[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=cdouble),
|
| 179 |
+
array([2. + 1j, 1. + 2j], dtype=cdouble)),
|
| 180 |
+
LinalgCase("cdouble_nsq_2",
|
| 181 |
+
array(
|
| 182 |
+
[[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=cdouble),
|
| 183 |
+
array([2. + 1j, 1. + 2j, 3. - 3j], dtype=cdouble)),
|
| 184 |
+
LinalgCase("cdouble_nsq_1_2",
|
| 185 |
+
array(
|
| 186 |
+
[[1. + 1j, 2. + 2j, 3. - 3j], [3. - 5j, 4. + 9j, 6. + 2j]], dtype=cdouble),
|
| 187 |
+
array([[2. + 1j, 1. + 2j], [1 - 1j, 2 - 2j]], dtype=cdouble)),
|
| 188 |
+
LinalgCase("cdouble_nsq_2_2",
|
| 189 |
+
array(
|
| 190 |
+
[[1. + 1j, 2. + 2j], [3. - 3j, 4. - 9j], [5. - 4j, 6. + 8j]], dtype=cdouble),
|
| 191 |
+
array([[2. + 1j, 1. + 2j], [1 - 1j, 2 - 2j], [1 - 1j, 2 - 2j]], dtype=cdouble)),
|
| 192 |
+
LinalgCase("8x11",
|
| 193 |
+
np.random.rand(8, 11),
|
| 194 |
+
np.random.rand(8)),
|
| 195 |
+
LinalgCase("1x5",
|
| 196 |
+
np.random.rand(1, 5),
|
| 197 |
+
np.random.rand(1)),
|
| 198 |
+
LinalgCase("5x1",
|
| 199 |
+
np.random.rand(5, 1),
|
| 200 |
+
np.random.rand(5)),
|
| 201 |
+
LinalgCase("0x4",
|
| 202 |
+
np.random.rand(0, 4),
|
| 203 |
+
np.random.rand(0),
|
| 204 |
+
tags={'size-0'}),
|
| 205 |
+
LinalgCase("4x0",
|
| 206 |
+
np.random.rand(4, 0),
|
| 207 |
+
np.random.rand(4),
|
| 208 |
+
tags={'size-0'}),
|
| 209 |
+
])
|
| 210 |
+
|
| 211 |
+
# hermitian test-cases
|
| 212 |
+
CASES += apply_tag('hermitian', [
|
| 213 |
+
LinalgCase("hsingle",
|
| 214 |
+
array([[1., 2.], [2., 1.]], dtype=single),
|
| 215 |
+
None),
|
| 216 |
+
LinalgCase("hdouble",
|
| 217 |
+
array([[1., 2.], [2., 1.]], dtype=double),
|
| 218 |
+
None),
|
| 219 |
+
LinalgCase("hcsingle",
|
| 220 |
+
array([[1., 2 + 3j], [2 - 3j, 1]], dtype=csingle),
|
| 221 |
+
None),
|
| 222 |
+
LinalgCase("hcdouble",
|
| 223 |
+
array([[1., 2 + 3j], [2 - 3j, 1]], dtype=cdouble),
|
| 224 |
+
None),
|
| 225 |
+
LinalgCase("hempty",
|
| 226 |
+
np.empty((0, 0), dtype=double),
|
| 227 |
+
None,
|
| 228 |
+
tags={'size-0'}),
|
| 229 |
+
LinalgCase("hnonarray",
|
| 230 |
+
[[1, 2], [2, 1]],
|
| 231 |
+
None),
|
| 232 |
+
LinalgCase("matrix_b_only",
|
| 233 |
+
array([[1., 2.], [2., 1.]]),
|
| 234 |
+
None),
|
| 235 |
+
LinalgCase("hmatrix_1x1",
|
| 236 |
+
np.random.rand(1, 1),
|
| 237 |
+
None),
|
| 238 |
+
])
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
#
|
| 242 |
+
# Gufunc test cases
|
| 243 |
+
#
|
| 244 |
+
def _make_generalized_cases():
|
| 245 |
+
new_cases = []
|
| 246 |
+
|
| 247 |
+
for case in CASES:
|
| 248 |
+
if not isinstance(case.a, np.ndarray):
|
| 249 |
+
continue
|
| 250 |
+
|
| 251 |
+
a = np.array([case.a, 2 * case.a, 3 * case.a])
|
| 252 |
+
if case.b is None:
|
| 253 |
+
b = None
|
| 254 |
+
elif case.b.ndim == 1:
|
| 255 |
+
b = case.b
|
| 256 |
+
else:
|
| 257 |
+
b = np.array([case.b, 7 * case.b, 6 * case.b])
|
| 258 |
+
new_case = LinalgCase(case.name + "_tile3", a, b,
|
| 259 |
+
tags=case.tags | {'generalized'})
|
| 260 |
+
new_cases.append(new_case)
|
| 261 |
+
|
| 262 |
+
a = np.array([case.a] * 2 * 3).reshape((3, 2) + case.a.shape)
|
| 263 |
+
if case.b is None:
|
| 264 |
+
b = None
|
| 265 |
+
elif case.b.ndim == 1:
|
| 266 |
+
b = np.array([case.b] * 2 * 3 * a.shape[-1])\
|
| 267 |
+
.reshape((3, 2) + case.a.shape[-2:])
|
| 268 |
+
else:
|
| 269 |
+
b = np.array([case.b] * 2 * 3).reshape((3, 2) + case.b.shape)
|
| 270 |
+
new_case = LinalgCase(case.name + "_tile213", a, b,
|
| 271 |
+
tags=case.tags | {'generalized'})
|
| 272 |
+
new_cases.append(new_case)
|
| 273 |
+
|
| 274 |
+
return new_cases
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
CASES += _make_generalized_cases()
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
#
|
| 281 |
+
# Generate stride combination variations of the above
|
| 282 |
+
#
|
| 283 |
+
def _stride_comb_iter(x):
|
| 284 |
+
"""
|
| 285 |
+
Generate cartesian product of strides for all axes
|
| 286 |
+
"""
|
| 287 |
+
|
| 288 |
+
if not isinstance(x, np.ndarray):
|
| 289 |
+
yield x, "nop"
|
| 290 |
+
return
|
| 291 |
+
|
| 292 |
+
stride_set = [(1,)] * x.ndim
|
| 293 |
+
stride_set[-1] = (1, 3, -4)
|
| 294 |
+
if x.ndim > 1:
|
| 295 |
+
stride_set[-2] = (1, 3, -4)
|
| 296 |
+
if x.ndim > 2:
|
| 297 |
+
stride_set[-3] = (1, -4)
|
| 298 |
+
|
| 299 |
+
for repeats in itertools.product(*tuple(stride_set)):
|
| 300 |
+
new_shape = [abs(a * b) for a, b in zip(x.shape, repeats)]
|
| 301 |
+
slices = tuple([slice(None, None, repeat) for repeat in repeats])
|
| 302 |
+
|
| 303 |
+
# new array with different strides, but same data
|
| 304 |
+
xi = np.empty(new_shape, dtype=x.dtype)
|
| 305 |
+
xi.view(np.uint32).fill(0xdeadbeef)
|
| 306 |
+
xi = xi[slices]
|
| 307 |
+
xi[...] = x
|
| 308 |
+
xi = xi.view(x.__class__)
|
| 309 |
+
assert_(np.all(xi == x))
|
| 310 |
+
yield xi, "stride_" + "_".join(["%+d" % j for j in repeats])
|
| 311 |
+
|
| 312 |
+
# generate also zero strides if possible
|
| 313 |
+
if x.ndim >= 1 and x.shape[-1] == 1:
|
| 314 |
+
s = list(x.strides)
|
| 315 |
+
s[-1] = 0
|
| 316 |
+
xi = np.lib.stride_tricks.as_strided(x, strides=s)
|
| 317 |
+
yield xi, "stride_xxx_0"
|
| 318 |
+
if x.ndim >= 2 and x.shape[-2] == 1:
|
| 319 |
+
s = list(x.strides)
|
| 320 |
+
s[-2] = 0
|
| 321 |
+
xi = np.lib.stride_tricks.as_strided(x, strides=s)
|
| 322 |
+
yield xi, "stride_xxx_0_x"
|
| 323 |
+
if x.ndim >= 2 and x.shape[:-2] == (1, 1):
|
| 324 |
+
s = list(x.strides)
|
| 325 |
+
s[-1] = 0
|
| 326 |
+
s[-2] = 0
|
| 327 |
+
xi = np.lib.stride_tricks.as_strided(x, strides=s)
|
| 328 |
+
yield xi, "stride_xxx_0_0"
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _make_strided_cases():
|
| 332 |
+
new_cases = []
|
| 333 |
+
for case in CASES:
|
| 334 |
+
for a, a_label in _stride_comb_iter(case.a):
|
| 335 |
+
for b, b_label in _stride_comb_iter(case.b):
|
| 336 |
+
new_case = LinalgCase(case.name + "_" + a_label + "_" + b_label, a, b,
|
| 337 |
+
tags=case.tags | {'strided'})
|
| 338 |
+
new_cases.append(new_case)
|
| 339 |
+
return new_cases
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
CASES += _make_strided_cases()
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
#
|
| 346 |
+
# Test different routines against the above cases
|
| 347 |
+
#
|
| 348 |
+
class LinalgTestCase:
|
| 349 |
+
TEST_CASES = CASES
|
| 350 |
+
|
| 351 |
+
def check_cases(self, require=set(), exclude=set()):
|
| 352 |
+
"""
|
| 353 |
+
Run func on each of the cases with all of the tags in require, and none
|
| 354 |
+
of the tags in exclude
|
| 355 |
+
"""
|
| 356 |
+
for case in self.TEST_CASES:
|
| 357 |
+
# filter by require and exclude
|
| 358 |
+
if case.tags & require != require:
|
| 359 |
+
continue
|
| 360 |
+
if case.tags & exclude:
|
| 361 |
+
continue
|
| 362 |
+
|
| 363 |
+
try:
|
| 364 |
+
case.check(self.do)
|
| 365 |
+
except Exception as e:
|
| 366 |
+
msg = f'In test case: {case!r}\n\n'
|
| 367 |
+
msg += traceback.format_exc()
|
| 368 |
+
raise AssertionError(msg) from e
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class LinalgSquareTestCase(LinalgTestCase):
|
| 372 |
+
|
| 373 |
+
def test_sq_cases(self):
|
| 374 |
+
self.check_cases(require={'square'},
|
| 375 |
+
exclude={'generalized', 'size-0'})
|
| 376 |
+
|
| 377 |
+
def test_empty_sq_cases(self):
|
| 378 |
+
self.check_cases(require={'square', 'size-0'},
|
| 379 |
+
exclude={'generalized'})
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
class LinalgNonsquareTestCase(LinalgTestCase):
|
| 383 |
+
|
| 384 |
+
def test_nonsq_cases(self):
|
| 385 |
+
self.check_cases(require={'nonsquare'},
|
| 386 |
+
exclude={'generalized', 'size-0'})
|
| 387 |
+
|
| 388 |
+
def test_empty_nonsq_cases(self):
|
| 389 |
+
self.check_cases(require={'nonsquare', 'size-0'},
|
| 390 |
+
exclude={'generalized'})
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class HermitianTestCase(LinalgTestCase):
|
| 394 |
+
|
| 395 |
+
def test_herm_cases(self):
|
| 396 |
+
self.check_cases(require={'hermitian'},
|
| 397 |
+
exclude={'generalized', 'size-0'})
|
| 398 |
+
|
| 399 |
+
def test_empty_herm_cases(self):
|
| 400 |
+
self.check_cases(require={'hermitian', 'size-0'},
|
| 401 |
+
exclude={'generalized'})
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class LinalgGeneralizedSquareTestCase(LinalgTestCase):
|
| 405 |
+
|
| 406 |
+
@pytest.mark.slow
|
| 407 |
+
def test_generalized_sq_cases(self):
|
| 408 |
+
self.check_cases(require={'generalized', 'square'},
|
| 409 |
+
exclude={'size-0'})
|
| 410 |
+
|
| 411 |
+
@pytest.mark.slow
|
| 412 |
+
def test_generalized_empty_sq_cases(self):
|
| 413 |
+
self.check_cases(require={'generalized', 'square', 'size-0'})
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
class LinalgGeneralizedNonsquareTestCase(LinalgTestCase):
|
| 417 |
+
|
| 418 |
+
@pytest.mark.slow
|
| 419 |
+
def test_generalized_nonsq_cases(self):
|
| 420 |
+
self.check_cases(require={'generalized', 'nonsquare'},
|
| 421 |
+
exclude={'size-0'})
|
| 422 |
+
|
| 423 |
+
@pytest.mark.slow
|
| 424 |
+
def test_generalized_empty_nonsq_cases(self):
|
| 425 |
+
self.check_cases(require={'generalized', 'nonsquare', 'size-0'})
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
class HermitianGeneralizedTestCase(LinalgTestCase):
|
| 429 |
+
|
| 430 |
+
@pytest.mark.slow
|
| 431 |
+
def test_generalized_herm_cases(self):
|
| 432 |
+
self.check_cases(require={'generalized', 'hermitian'},
|
| 433 |
+
exclude={'size-0'})
|
| 434 |
+
|
| 435 |
+
@pytest.mark.slow
|
| 436 |
+
def test_generalized_empty_herm_cases(self):
|
| 437 |
+
self.check_cases(require={'generalized', 'hermitian', 'size-0'},
|
| 438 |
+
exclude={'none'})
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def identity_like_generalized(a):
|
| 442 |
+
a = asarray(a)
|
| 443 |
+
if a.ndim >= 3:
|
| 444 |
+
r = np.empty(a.shape, dtype=a.dtype)
|
| 445 |
+
r[...] = identity(a.shape[-2])
|
| 446 |
+
return r
|
| 447 |
+
else:
|
| 448 |
+
return identity(a.shape[0])
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
class SolveCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
|
| 452 |
+
# kept apart from TestSolve for use for testing with matrices.
|
| 453 |
+
def do(self, a, b, tags):
|
| 454 |
+
x = linalg.solve(a, b)
|
| 455 |
+
if np.array(b).ndim == 1:
|
| 456 |
+
# When a is (..., M, M) and b is (M,), it is the same as when b is
|
| 457 |
+
# (M, 1), except the result has shape (..., M)
|
| 458 |
+
adotx = matmul(a, x[..., None])[..., 0]
|
| 459 |
+
assert_almost_equal(np.broadcast_to(b, adotx.shape), adotx)
|
| 460 |
+
else:
|
| 461 |
+
adotx = matmul(a, x)
|
| 462 |
+
assert_almost_equal(b, adotx)
|
| 463 |
+
assert_(consistent_subclass(x, b))
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
class TestSolve(SolveCases):
|
| 467 |
+
@pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
|
| 468 |
+
def test_types(self, dtype):
|
| 469 |
+
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
|
| 470 |
+
assert_equal(linalg.solve(x, x).dtype, dtype)
|
| 471 |
+
|
| 472 |
+
def test_1_d(self):
|
| 473 |
+
class ArraySubclass(np.ndarray):
|
| 474 |
+
pass
|
| 475 |
+
a = np.arange(8).reshape(2, 2, 2)
|
| 476 |
+
b = np.arange(2).view(ArraySubclass)
|
| 477 |
+
result = linalg.solve(a, b)
|
| 478 |
+
assert result.shape == (2, 2)
|
| 479 |
+
|
| 480 |
+
# If b is anything other than 1-D it should be treated as a stack of
|
| 481 |
+
# matrices
|
| 482 |
+
b = np.arange(4).reshape(2, 2).view(ArraySubclass)
|
| 483 |
+
result = linalg.solve(a, b)
|
| 484 |
+
assert result.shape == (2, 2, 2)
|
| 485 |
+
|
| 486 |
+
b = np.arange(2).reshape(1, 2).view(ArraySubclass)
|
| 487 |
+
assert_raises(ValueError, linalg.solve, a, b)
|
| 488 |
+
|
| 489 |
+
def test_0_size(self):
|
| 490 |
+
class ArraySubclass(np.ndarray):
|
| 491 |
+
pass
|
| 492 |
+
# Test system of 0x0 matrices
|
| 493 |
+
a = np.arange(8).reshape(2, 2, 2)
|
| 494 |
+
b = np.arange(6).reshape(1, 2, 3).view(ArraySubclass)
|
| 495 |
+
|
| 496 |
+
expected = linalg.solve(a, b)[:, 0:0, :]
|
| 497 |
+
result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, :])
|
| 498 |
+
assert_array_equal(result, expected)
|
| 499 |
+
assert_(isinstance(result, ArraySubclass))
|
| 500 |
+
|
| 501 |
+
# Test errors for non-square and only b's dimension being 0
|
| 502 |
+
assert_raises(linalg.LinAlgError, linalg.solve, a[:, 0:0, 0:1], b)
|
| 503 |
+
assert_raises(ValueError, linalg.solve, a, b[:, 0:0, :])
|
| 504 |
+
|
| 505 |
+
# Test broadcasting error
|
| 506 |
+
b = np.arange(6).reshape(1, 3, 2) # broadcasting error
|
| 507 |
+
assert_raises(ValueError, linalg.solve, a, b)
|
| 508 |
+
assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
|
| 509 |
+
|
| 510 |
+
# Test zero "single equations" with 0x0 matrices.
|
| 511 |
+
b = np.arange(2).view(ArraySubclass)
|
| 512 |
+
expected = linalg.solve(a, b)[:, 0:0]
|
| 513 |
+
result = linalg.solve(a[:, 0:0, 0:0], b[0:0])
|
| 514 |
+
assert_array_equal(result, expected)
|
| 515 |
+
assert_(isinstance(result, ArraySubclass))
|
| 516 |
+
|
| 517 |
+
b = np.arange(3).reshape(1, 3)
|
| 518 |
+
assert_raises(ValueError, linalg.solve, a, b)
|
| 519 |
+
assert_raises(ValueError, linalg.solve, a[0:0], b[0:0])
|
| 520 |
+
assert_raises(ValueError, linalg.solve, a[:, 0:0, 0:0], b)
|
| 521 |
+
|
| 522 |
+
def test_0_size_k(self):
|
| 523 |
+
# test zero multiple equation (K=0) case.
|
| 524 |
+
class ArraySubclass(np.ndarray):
|
| 525 |
+
pass
|
| 526 |
+
a = np.arange(4).reshape(1, 2, 2)
|
| 527 |
+
b = np.arange(6).reshape(3, 2, 1).view(ArraySubclass)
|
| 528 |
+
|
| 529 |
+
expected = linalg.solve(a, b)[:, :, 0:0]
|
| 530 |
+
result = linalg.solve(a, b[:, :, 0:0])
|
| 531 |
+
assert_array_equal(result, expected)
|
| 532 |
+
assert_(isinstance(result, ArraySubclass))
|
| 533 |
+
|
| 534 |
+
# test both zero.
|
| 535 |
+
expected = linalg.solve(a, b)[:, 0:0, 0:0]
|
| 536 |
+
result = linalg.solve(a[:, 0:0, 0:0], b[:, 0:0, 0:0])
|
| 537 |
+
assert_array_equal(result, expected)
|
| 538 |
+
assert_(isinstance(result, ArraySubclass))
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
class InvCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
|
| 542 |
+
|
| 543 |
+
def do(self, a, b, tags):
|
| 544 |
+
a_inv = linalg.inv(a)
|
| 545 |
+
assert_almost_equal(matmul(a, a_inv),
|
| 546 |
+
identity_like_generalized(a))
|
| 547 |
+
assert_(consistent_subclass(a_inv, a))
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
class TestInv(InvCases):
|
| 551 |
+
@pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
|
| 552 |
+
def test_types(self, dtype):
|
| 553 |
+
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
|
| 554 |
+
assert_equal(linalg.inv(x).dtype, dtype)
|
| 555 |
+
|
| 556 |
+
def test_0_size(self):
|
| 557 |
+
# Check that all kinds of 0-sized arrays work
|
| 558 |
+
class ArraySubclass(np.ndarray):
|
| 559 |
+
pass
|
| 560 |
+
a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
|
| 561 |
+
res = linalg.inv(a)
|
| 562 |
+
assert_(res.dtype.type is np.float64)
|
| 563 |
+
assert_equal(a.shape, res.shape)
|
| 564 |
+
assert_(isinstance(res, ArraySubclass))
|
| 565 |
+
|
| 566 |
+
a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
|
| 567 |
+
res = linalg.inv(a)
|
| 568 |
+
assert_(res.dtype.type is np.complex64)
|
| 569 |
+
assert_equal(a.shape, res.shape)
|
| 570 |
+
assert_(isinstance(res, ArraySubclass))
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
class EigvalsCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
|
| 574 |
+
|
| 575 |
+
def do(self, a, b, tags):
|
| 576 |
+
ev = linalg.eigvals(a)
|
| 577 |
+
evalues, evectors = linalg.eig(a)
|
| 578 |
+
assert_almost_equal(ev, evalues)
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
class TestEigvals(EigvalsCases):
|
| 582 |
+
@pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
|
| 583 |
+
def test_types(self, dtype):
|
| 584 |
+
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
|
| 585 |
+
assert_equal(linalg.eigvals(x).dtype, dtype)
|
| 586 |
+
x = np.array([[1, 0.5], [-1, 1]], dtype=dtype)
|
| 587 |
+
assert_equal(linalg.eigvals(x).dtype, get_complex_dtype(dtype))
|
| 588 |
+
|
| 589 |
+
def test_0_size(self):
|
| 590 |
+
# Check that all kinds of 0-sized arrays work
|
| 591 |
+
class ArraySubclass(np.ndarray):
|
| 592 |
+
pass
|
| 593 |
+
a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
|
| 594 |
+
res = linalg.eigvals(a)
|
| 595 |
+
assert_(res.dtype.type is np.float64)
|
| 596 |
+
assert_equal((0, 1), res.shape)
|
| 597 |
+
# This is just for documentation, it might make sense to change:
|
| 598 |
+
assert_(isinstance(res, np.ndarray))
|
| 599 |
+
|
| 600 |
+
a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
|
| 601 |
+
res = linalg.eigvals(a)
|
| 602 |
+
assert_(res.dtype.type is np.complex64)
|
| 603 |
+
assert_equal((0,), res.shape)
|
| 604 |
+
# This is just for documentation, it might make sense to change:
|
| 605 |
+
assert_(isinstance(res, np.ndarray))
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
class EigCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
|
| 609 |
+
|
| 610 |
+
def do(self, a, b, tags):
|
| 611 |
+
res = linalg.eig(a)
|
| 612 |
+
eigenvalues, eigenvectors = res.eigenvalues, res.eigenvectors
|
| 613 |
+
assert_allclose(matmul(a, eigenvectors),
|
| 614 |
+
np.asarray(eigenvectors) * np.asarray(eigenvalues)[..., None, :],
|
| 615 |
+
rtol=get_rtol(eigenvalues.dtype))
|
| 616 |
+
assert_(consistent_subclass(eigenvectors, a))
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class TestEig(EigCases):
|
| 620 |
+
@pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
|
| 621 |
+
def test_types(self, dtype):
|
| 622 |
+
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
|
| 623 |
+
w, v = np.linalg.eig(x)
|
| 624 |
+
assert_equal(w.dtype, dtype)
|
| 625 |
+
assert_equal(v.dtype, dtype)
|
| 626 |
+
|
| 627 |
+
x = np.array([[1, 0.5], [-1, 1]], dtype=dtype)
|
| 628 |
+
w, v = np.linalg.eig(x)
|
| 629 |
+
assert_equal(w.dtype, get_complex_dtype(dtype))
|
| 630 |
+
assert_equal(v.dtype, get_complex_dtype(dtype))
|
| 631 |
+
|
| 632 |
+
def test_0_size(self):
|
| 633 |
+
# Check that all kinds of 0-sized arrays work
|
| 634 |
+
class ArraySubclass(np.ndarray):
|
| 635 |
+
pass
|
| 636 |
+
a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
|
| 637 |
+
res, res_v = linalg.eig(a)
|
| 638 |
+
assert_(res_v.dtype.type is np.float64)
|
| 639 |
+
assert_(res.dtype.type is np.float64)
|
| 640 |
+
assert_equal(a.shape, res_v.shape)
|
| 641 |
+
assert_equal((0, 1), res.shape)
|
| 642 |
+
# This is just for documentation, it might make sense to change:
|
| 643 |
+
assert_(isinstance(a, np.ndarray))
|
| 644 |
+
|
| 645 |
+
a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
|
| 646 |
+
res, res_v = linalg.eig(a)
|
| 647 |
+
assert_(res_v.dtype.type is np.complex64)
|
| 648 |
+
assert_(res.dtype.type is np.complex64)
|
| 649 |
+
assert_equal(a.shape, res_v.shape)
|
| 650 |
+
assert_equal((0,), res.shape)
|
| 651 |
+
# This is just for documentation, it might make sense to change:
|
| 652 |
+
assert_(isinstance(a, np.ndarray))
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
class SVDBaseTests:
|
| 656 |
+
hermitian = False
|
| 657 |
+
|
| 658 |
+
@pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
|
| 659 |
+
def test_types(self, dtype):
|
| 660 |
+
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
|
| 661 |
+
res = linalg.svd(x)
|
| 662 |
+
U, S, Vh = res.U, res.S, res.Vh
|
| 663 |
+
assert_equal(U.dtype, dtype)
|
| 664 |
+
assert_equal(S.dtype, get_real_dtype(dtype))
|
| 665 |
+
assert_equal(Vh.dtype, dtype)
|
| 666 |
+
s = linalg.svd(x, compute_uv=False, hermitian=self.hermitian)
|
| 667 |
+
assert_equal(s.dtype, get_real_dtype(dtype))
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
class SVDCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
|
| 671 |
+
|
| 672 |
+
def do(self, a, b, tags):
|
| 673 |
+
u, s, vt = linalg.svd(a, False)
|
| 674 |
+
assert_allclose(a, matmul(np.asarray(u) * np.asarray(s)[..., None, :],
|
| 675 |
+
np.asarray(vt)),
|
| 676 |
+
rtol=get_rtol(u.dtype))
|
| 677 |
+
assert_(consistent_subclass(u, a))
|
| 678 |
+
assert_(consistent_subclass(vt, a))
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
class TestSVD(SVDCases, SVDBaseTests):
|
| 682 |
+
def test_empty_identity(self):
|
| 683 |
+
""" Empty input should put an identity matrix in u or vh """
|
| 684 |
+
x = np.empty((4, 0))
|
| 685 |
+
u, s, vh = linalg.svd(x, compute_uv=True, hermitian=self.hermitian)
|
| 686 |
+
assert_equal(u.shape, (4, 4))
|
| 687 |
+
assert_equal(vh.shape, (0, 0))
|
| 688 |
+
assert_equal(u, np.eye(4))
|
| 689 |
+
|
| 690 |
+
x = np.empty((0, 4))
|
| 691 |
+
u, s, vh = linalg.svd(x, compute_uv=True, hermitian=self.hermitian)
|
| 692 |
+
assert_equal(u.shape, (0, 0))
|
| 693 |
+
assert_equal(vh.shape, (4, 4))
|
| 694 |
+
assert_equal(vh, np.eye(4))
|
| 695 |
+
|
| 696 |
+
def test_svdvals(self):
|
| 697 |
+
x = np.array([[1, 0.5], [0.5, 1]])
|
| 698 |
+
s_from_svd = linalg.svd(x, compute_uv=False, hermitian=self.hermitian)
|
| 699 |
+
s_from_svdvals = linalg.svdvals(x)
|
| 700 |
+
assert_almost_equal(s_from_svd, s_from_svdvals)
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
class SVDHermitianCases(HermitianTestCase, HermitianGeneralizedTestCase):
|
| 704 |
+
|
| 705 |
+
def do(self, a, b, tags):
|
| 706 |
+
u, s, vt = linalg.svd(a, False, hermitian=True)
|
| 707 |
+
assert_allclose(a, matmul(np.asarray(u) * np.asarray(s)[..., None, :],
|
| 708 |
+
np.asarray(vt)),
|
| 709 |
+
rtol=get_rtol(u.dtype))
|
| 710 |
+
def hermitian(mat):
|
| 711 |
+
axes = list(range(mat.ndim))
|
| 712 |
+
axes[-1], axes[-2] = axes[-2], axes[-1]
|
| 713 |
+
return np.conj(np.transpose(mat, axes=axes))
|
| 714 |
+
|
| 715 |
+
assert_almost_equal(np.matmul(u, hermitian(u)), np.broadcast_to(np.eye(u.shape[-1]), u.shape))
|
| 716 |
+
assert_almost_equal(np.matmul(vt, hermitian(vt)), np.broadcast_to(np.eye(vt.shape[-1]), vt.shape))
|
| 717 |
+
assert_equal(np.sort(s)[..., ::-1], s)
|
| 718 |
+
assert_(consistent_subclass(u, a))
|
| 719 |
+
assert_(consistent_subclass(vt, a))
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
class TestSVDHermitian(SVDHermitianCases, SVDBaseTests):
|
| 723 |
+
hermitian = True
|
| 724 |
+
|
| 725 |
+
|
| 726 |
+
class CondCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
|
| 727 |
+
# cond(x, p) for p in (None, 2, -2)
|
| 728 |
+
|
| 729 |
+
def do(self, a, b, tags):
|
| 730 |
+
c = asarray(a) # a might be a matrix
|
| 731 |
+
if 'size-0' in tags:
|
| 732 |
+
assert_raises(LinAlgError, linalg.cond, c)
|
| 733 |
+
return
|
| 734 |
+
|
| 735 |
+
# +-2 norms
|
| 736 |
+
s = linalg.svd(c, compute_uv=False)
|
| 737 |
+
assert_almost_equal(
|
| 738 |
+
linalg.cond(a), s[..., 0] / s[..., -1],
|
| 739 |
+
single_decimal=5, double_decimal=11)
|
| 740 |
+
assert_almost_equal(
|
| 741 |
+
linalg.cond(a, 2), s[..., 0] / s[..., -1],
|
| 742 |
+
single_decimal=5, double_decimal=11)
|
| 743 |
+
assert_almost_equal(
|
| 744 |
+
linalg.cond(a, -2), s[..., -1] / s[..., 0],
|
| 745 |
+
single_decimal=5, double_decimal=11)
|
| 746 |
+
|
| 747 |
+
# Other norms
|
| 748 |
+
cinv = np.linalg.inv(c)
|
| 749 |
+
assert_almost_equal(
|
| 750 |
+
linalg.cond(a, 1),
|
| 751 |
+
abs(c).sum(-2).max(-1) * abs(cinv).sum(-2).max(-1),
|
| 752 |
+
single_decimal=5, double_decimal=11)
|
| 753 |
+
assert_almost_equal(
|
| 754 |
+
linalg.cond(a, -1),
|
| 755 |
+
abs(c).sum(-2).min(-1) * abs(cinv).sum(-2).min(-1),
|
| 756 |
+
single_decimal=5, double_decimal=11)
|
| 757 |
+
assert_almost_equal(
|
| 758 |
+
linalg.cond(a, np.inf),
|
| 759 |
+
abs(c).sum(-1).max(-1) * abs(cinv).sum(-1).max(-1),
|
| 760 |
+
single_decimal=5, double_decimal=11)
|
| 761 |
+
assert_almost_equal(
|
| 762 |
+
linalg.cond(a, -np.inf),
|
| 763 |
+
abs(c).sum(-1).min(-1) * abs(cinv).sum(-1).min(-1),
|
| 764 |
+
single_decimal=5, double_decimal=11)
|
| 765 |
+
assert_almost_equal(
|
| 766 |
+
linalg.cond(a, 'fro'),
|
| 767 |
+
np.sqrt((abs(c)**2).sum(-1).sum(-1)
|
| 768 |
+
* (abs(cinv)**2).sum(-1).sum(-1)),
|
| 769 |
+
single_decimal=5, double_decimal=11)
|
| 770 |
+
|
| 771 |
+
|
| 772 |
+
class TestCond(CondCases):
|
| 773 |
+
def test_basic_nonsvd(self):
|
| 774 |
+
# Smoketest the non-svd norms
|
| 775 |
+
A = array([[1., 0, 1], [0, -2., 0], [0, 0, 3.]])
|
| 776 |
+
assert_almost_equal(linalg.cond(A, inf), 4)
|
| 777 |
+
assert_almost_equal(linalg.cond(A, -inf), 2/3)
|
| 778 |
+
assert_almost_equal(linalg.cond(A, 1), 4)
|
| 779 |
+
assert_almost_equal(linalg.cond(A, -1), 0.5)
|
| 780 |
+
assert_almost_equal(linalg.cond(A, 'fro'), np.sqrt(265 / 12))
|
| 781 |
+
|
| 782 |
+
def test_singular(self):
|
| 783 |
+
# Singular matrices have infinite condition number for
|
| 784 |
+
# positive norms, and negative norms shouldn't raise
|
| 785 |
+
# exceptions
|
| 786 |
+
As = [np.zeros((2, 2)), np.ones((2, 2))]
|
| 787 |
+
p_pos = [None, 1, 2, 'fro']
|
| 788 |
+
p_neg = [-1, -2]
|
| 789 |
+
for A, p in itertools.product(As, p_pos):
|
| 790 |
+
# Inversion may not hit exact infinity, so just check the
|
| 791 |
+
# number is large
|
| 792 |
+
assert_(linalg.cond(A, p) > 1e15)
|
| 793 |
+
for A, p in itertools.product(As, p_neg):
|
| 794 |
+
linalg.cond(A, p)
|
| 795 |
+
|
| 796 |
+
@pytest.mark.xfail(True, run=False,
|
| 797 |
+
reason="Platform/LAPACK-dependent failure, "
|
| 798 |
+
"see gh-18914")
|
| 799 |
+
def test_nan(self):
|
| 800 |
+
# nans should be passed through, not converted to infs
|
| 801 |
+
ps = [None, 1, -1, 2, -2, 'fro']
|
| 802 |
+
p_pos = [None, 1, 2, 'fro']
|
| 803 |
+
|
| 804 |
+
A = np.ones((2, 2))
|
| 805 |
+
A[0,1] = np.nan
|
| 806 |
+
for p in ps:
|
| 807 |
+
c = linalg.cond(A, p)
|
| 808 |
+
assert_(isinstance(c, np.float64))
|
| 809 |
+
assert_(np.isnan(c))
|
| 810 |
+
|
| 811 |
+
A = np.ones((3, 2, 2))
|
| 812 |
+
A[1,0,1] = np.nan
|
| 813 |
+
for p in ps:
|
| 814 |
+
c = linalg.cond(A, p)
|
| 815 |
+
assert_(np.isnan(c[1]))
|
| 816 |
+
if p in p_pos:
|
| 817 |
+
assert_(c[0] > 1e15)
|
| 818 |
+
assert_(c[2] > 1e15)
|
| 819 |
+
else:
|
| 820 |
+
assert_(not np.isnan(c[0]))
|
| 821 |
+
assert_(not np.isnan(c[2]))
|
| 822 |
+
|
| 823 |
+
def test_stacked_singular(self):
|
| 824 |
+
# Check behavior when only some of the stacked matrices are
|
| 825 |
+
# singular
|
| 826 |
+
np.random.seed(1234)
|
| 827 |
+
A = np.random.rand(2, 2, 2, 2)
|
| 828 |
+
A[0,0] = 0
|
| 829 |
+
A[1,1] = 0
|
| 830 |
+
|
| 831 |
+
for p in (None, 1, 2, 'fro', -1, -2):
|
| 832 |
+
c = linalg.cond(A, p)
|
| 833 |
+
assert_equal(c[0,0], np.inf)
|
| 834 |
+
assert_equal(c[1,1], np.inf)
|
| 835 |
+
assert_(np.isfinite(c[0,1]))
|
| 836 |
+
assert_(np.isfinite(c[1,0]))
|
| 837 |
+
|
| 838 |
+
|
| 839 |
+
class PinvCases(LinalgSquareTestCase,
|
| 840 |
+
LinalgNonsquareTestCase,
|
| 841 |
+
LinalgGeneralizedSquareTestCase,
|
| 842 |
+
LinalgGeneralizedNonsquareTestCase):
|
| 843 |
+
|
| 844 |
+
def do(self, a, b, tags):
|
| 845 |
+
a_ginv = linalg.pinv(a)
|
| 846 |
+
# `a @ a_ginv == I` does not hold if a is singular
|
| 847 |
+
dot = matmul
|
| 848 |
+
assert_almost_equal(dot(dot(a, a_ginv), a), a, single_decimal=5, double_decimal=11)
|
| 849 |
+
assert_(consistent_subclass(a_ginv, a))
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
class TestPinv(PinvCases):
|
| 853 |
+
pass
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
class PinvHermitianCases(HermitianTestCase, HermitianGeneralizedTestCase):
|
| 857 |
+
|
| 858 |
+
def do(self, a, b, tags):
|
| 859 |
+
a_ginv = linalg.pinv(a, hermitian=True)
|
| 860 |
+
# `a @ a_ginv == I` does not hold if a is singular
|
| 861 |
+
dot = matmul
|
| 862 |
+
assert_almost_equal(dot(dot(a, a_ginv), a), a, single_decimal=5, double_decimal=11)
|
| 863 |
+
assert_(consistent_subclass(a_ginv, a))
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
class TestPinvHermitian(PinvHermitianCases):
|
| 867 |
+
pass
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def test_pinv_rtol_arg():
|
| 871 |
+
a = np.array([[1, 2, 3], [4, 1, 1], [2, 3, 1]])
|
| 872 |
+
|
| 873 |
+
assert_almost_equal(
|
| 874 |
+
np.linalg.pinv(a, rcond=0.5),
|
| 875 |
+
np.linalg.pinv(a, rtol=0.5),
|
| 876 |
+
)
|
| 877 |
+
|
| 878 |
+
with pytest.raises(
|
| 879 |
+
ValueError, match=r"`rtol` and `rcond` can't be both set."
|
| 880 |
+
):
|
| 881 |
+
np.linalg.pinv(a, rcond=0.5, rtol=0.5)
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
class DetCases(LinalgSquareTestCase, LinalgGeneralizedSquareTestCase):
|
| 885 |
+
|
| 886 |
+
def do(self, a, b, tags):
|
| 887 |
+
d = linalg.det(a)
|
| 888 |
+
res = linalg.slogdet(a)
|
| 889 |
+
s, ld = res.sign, res.logabsdet
|
| 890 |
+
if asarray(a).dtype.type in (single, double):
|
| 891 |
+
ad = asarray(a).astype(double)
|
| 892 |
+
else:
|
| 893 |
+
ad = asarray(a).astype(cdouble)
|
| 894 |
+
ev = linalg.eigvals(ad)
|
| 895 |
+
assert_almost_equal(d, multiply.reduce(ev, axis=-1))
|
| 896 |
+
assert_almost_equal(s * np.exp(ld), multiply.reduce(ev, axis=-1))
|
| 897 |
+
|
| 898 |
+
s = np.atleast_1d(s)
|
| 899 |
+
ld = np.atleast_1d(ld)
|
| 900 |
+
m = (s != 0)
|
| 901 |
+
assert_almost_equal(np.abs(s[m]), 1)
|
| 902 |
+
assert_equal(ld[~m], -inf)
|
| 903 |
+
|
| 904 |
+
|
| 905 |
+
class TestDet(DetCases):
|
| 906 |
+
def test_zero(self):
|
| 907 |
+
assert_equal(linalg.det([[0.0]]), 0.0)
|
| 908 |
+
assert_equal(type(linalg.det([[0.0]])), double)
|
| 909 |
+
assert_equal(linalg.det([[0.0j]]), 0.0)
|
| 910 |
+
assert_equal(type(linalg.det([[0.0j]])), cdouble)
|
| 911 |
+
|
| 912 |
+
assert_equal(linalg.slogdet([[0.0]]), (0.0, -inf))
|
| 913 |
+
assert_equal(type(linalg.slogdet([[0.0]])[0]), double)
|
| 914 |
+
assert_equal(type(linalg.slogdet([[0.0]])[1]), double)
|
| 915 |
+
assert_equal(linalg.slogdet([[0.0j]]), (0.0j, -inf))
|
| 916 |
+
assert_equal(type(linalg.slogdet([[0.0j]])[0]), cdouble)
|
| 917 |
+
assert_equal(type(linalg.slogdet([[0.0j]])[1]), double)
|
| 918 |
+
|
| 919 |
+
@pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
|
| 920 |
+
def test_types(self, dtype):
|
| 921 |
+
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
|
| 922 |
+
assert_equal(np.linalg.det(x).dtype, dtype)
|
| 923 |
+
ph, s = np.linalg.slogdet(x)
|
| 924 |
+
assert_equal(s.dtype, get_real_dtype(dtype))
|
| 925 |
+
assert_equal(ph.dtype, dtype)
|
| 926 |
+
|
| 927 |
+
def test_0_size(self):
|
| 928 |
+
a = np.zeros((0, 0), dtype=np.complex64)
|
| 929 |
+
res = linalg.det(a)
|
| 930 |
+
assert_equal(res, 1.)
|
| 931 |
+
assert_(res.dtype.type is np.complex64)
|
| 932 |
+
res = linalg.slogdet(a)
|
| 933 |
+
assert_equal(res, (1, 0))
|
| 934 |
+
assert_(res[0].dtype.type is np.complex64)
|
| 935 |
+
assert_(res[1].dtype.type is np.float32)
|
| 936 |
+
|
| 937 |
+
a = np.zeros((0, 0), dtype=np.float64)
|
| 938 |
+
res = linalg.det(a)
|
| 939 |
+
assert_equal(res, 1.)
|
| 940 |
+
assert_(res.dtype.type is np.float64)
|
| 941 |
+
res = linalg.slogdet(a)
|
| 942 |
+
assert_equal(res, (1, 0))
|
| 943 |
+
assert_(res[0].dtype.type is np.float64)
|
| 944 |
+
assert_(res[1].dtype.type is np.float64)
|
| 945 |
+
|
| 946 |
+
|
| 947 |
+
class LstsqCases(LinalgSquareTestCase, LinalgNonsquareTestCase):
|
| 948 |
+
|
| 949 |
+
def do(self, a, b, tags):
|
| 950 |
+
arr = np.asarray(a)
|
| 951 |
+
m, n = arr.shape
|
| 952 |
+
u, s, vt = linalg.svd(a, False)
|
| 953 |
+
x, residuals, rank, sv = linalg.lstsq(a, b, rcond=-1)
|
| 954 |
+
if m == 0:
|
| 955 |
+
assert_((x == 0).all())
|
| 956 |
+
if m <= n:
|
| 957 |
+
assert_almost_equal(b, dot(a, x))
|
| 958 |
+
assert_equal(rank, m)
|
| 959 |
+
else:
|
| 960 |
+
assert_equal(rank, n)
|
| 961 |
+
assert_almost_equal(sv, sv.__array_wrap__(s))
|
| 962 |
+
if rank == n and m > n:
|
| 963 |
+
expect_resids = (
|
| 964 |
+
np.asarray(abs(np.dot(a, x) - b)) ** 2).sum(axis=0)
|
| 965 |
+
expect_resids = np.asarray(expect_resids)
|
| 966 |
+
if np.asarray(b).ndim == 1:
|
| 967 |
+
expect_resids.shape = (1,)
|
| 968 |
+
assert_equal(residuals.shape, expect_resids.shape)
|
| 969 |
+
else:
|
| 970 |
+
expect_resids = np.array([]).view(type(x))
|
| 971 |
+
assert_almost_equal(residuals, expect_resids)
|
| 972 |
+
assert_(np.issubdtype(residuals.dtype, np.floating))
|
| 973 |
+
assert_(consistent_subclass(x, b))
|
| 974 |
+
assert_(consistent_subclass(residuals, b))
|
| 975 |
+
|
| 976 |
+
|
| 977 |
+
class TestLstsq(LstsqCases):
|
| 978 |
+
def test_rcond(self):
|
| 979 |
+
a = np.array([[0., 1., 0., 1., 2., 0.],
|
| 980 |
+
[0., 2., 0., 0., 1., 0.],
|
| 981 |
+
[1., 0., 1., 0., 0., 4.],
|
| 982 |
+
[0., 0., 0., 2., 3., 0.]]).T
|
| 983 |
+
|
| 984 |
+
b = np.array([1, 0, 0, 0, 0, 0])
|
| 985 |
+
|
| 986 |
+
x, residuals, rank, s = linalg.lstsq(a, b, rcond=-1)
|
| 987 |
+
assert_(rank == 4)
|
| 988 |
+
x, residuals, rank, s = linalg.lstsq(a, b)
|
| 989 |
+
assert_(rank == 3)
|
| 990 |
+
x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
|
| 991 |
+
assert_(rank == 3)
|
| 992 |
+
|
| 993 |
+
@pytest.mark.parametrize(["m", "n", "n_rhs"], [
|
| 994 |
+
(4, 2, 2),
|
| 995 |
+
(0, 4, 1),
|
| 996 |
+
(0, 4, 2),
|
| 997 |
+
(4, 0, 1),
|
| 998 |
+
(4, 0, 2),
|
| 999 |
+
(4, 2, 0),
|
| 1000 |
+
(0, 0, 0)
|
| 1001 |
+
])
|
| 1002 |
+
def test_empty_a_b(self, m, n, n_rhs):
|
| 1003 |
+
a = np.arange(m * n).reshape(m, n)
|
| 1004 |
+
b = np.ones((m, n_rhs))
|
| 1005 |
+
x, residuals, rank, s = linalg.lstsq(a, b, rcond=None)
|
| 1006 |
+
if m == 0:
|
| 1007 |
+
assert_((x == 0).all())
|
| 1008 |
+
assert_equal(x.shape, (n, n_rhs))
|
| 1009 |
+
assert_equal(residuals.shape, ((n_rhs,) if m > n else (0,)))
|
| 1010 |
+
if m > n and n_rhs > 0:
|
| 1011 |
+
# residuals are exactly the squared norms of b's columns
|
| 1012 |
+
r = b - np.dot(a, x)
|
| 1013 |
+
assert_almost_equal(residuals, (r * r).sum(axis=-2))
|
| 1014 |
+
assert_equal(rank, min(m, n))
|
| 1015 |
+
assert_equal(s.shape, (min(m, n),))
|
| 1016 |
+
|
| 1017 |
+
def test_incompatible_dims(self):
|
| 1018 |
+
# use modified version of docstring example
|
| 1019 |
+
x = np.array([0, 1, 2, 3])
|
| 1020 |
+
y = np.array([-1, 0.2, 0.9, 2.1, 3.3])
|
| 1021 |
+
A = np.vstack([x, np.ones(len(x))]).T
|
| 1022 |
+
with assert_raises_regex(LinAlgError, "Incompatible dimensions"):
|
| 1023 |
+
linalg.lstsq(A, y, rcond=None)
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
@pytest.mark.parametrize('dt', [np.dtype(c) for c in '?bBhHiIqQefdgFDGO'])
|
| 1027 |
+
class TestMatrixPower:
|
| 1028 |
+
|
| 1029 |
+
rshft_0 = np.eye(4)
|
| 1030 |
+
rshft_1 = rshft_0[[3, 0, 1, 2]]
|
| 1031 |
+
rshft_2 = rshft_0[[2, 3, 0, 1]]
|
| 1032 |
+
rshft_3 = rshft_0[[1, 2, 3, 0]]
|
| 1033 |
+
rshft_all = [rshft_0, rshft_1, rshft_2, rshft_3]
|
| 1034 |
+
noninv = array([[1, 0], [0, 0]])
|
| 1035 |
+
stacked = np.block([[[rshft_0]]]*2)
|
| 1036 |
+
#FIXME the 'e' dtype might work in future
|
| 1037 |
+
dtnoinv = [object, np.dtype('e'), np.dtype('g'), np.dtype('G')]
|
| 1038 |
+
|
| 1039 |
+
def test_large_power(self, dt):
|
| 1040 |
+
rshft = self.rshft_1.astype(dt)
|
| 1041 |
+
assert_equal(
|
| 1042 |
+
matrix_power(rshft, 2**100 + 2**10 + 2**5 + 0), self.rshft_0)
|
| 1043 |
+
assert_equal(
|
| 1044 |
+
matrix_power(rshft, 2**100 + 2**10 + 2**5 + 1), self.rshft_1)
|
| 1045 |
+
assert_equal(
|
| 1046 |
+
matrix_power(rshft, 2**100 + 2**10 + 2**5 + 2), self.rshft_2)
|
| 1047 |
+
assert_equal(
|
| 1048 |
+
matrix_power(rshft, 2**100 + 2**10 + 2**5 + 3), self.rshft_3)
|
| 1049 |
+
|
| 1050 |
+
def test_power_is_zero(self, dt):
|
| 1051 |
+
def tz(M):
|
| 1052 |
+
mz = matrix_power(M, 0)
|
| 1053 |
+
assert_equal(mz, identity_like_generalized(M))
|
| 1054 |
+
assert_equal(mz.dtype, M.dtype)
|
| 1055 |
+
|
| 1056 |
+
for mat in self.rshft_all:
|
| 1057 |
+
tz(mat.astype(dt))
|
| 1058 |
+
if dt != object:
|
| 1059 |
+
tz(self.stacked.astype(dt))
|
| 1060 |
+
|
| 1061 |
+
def test_power_is_one(self, dt):
|
| 1062 |
+
def tz(mat):
|
| 1063 |
+
mz = matrix_power(mat, 1)
|
| 1064 |
+
assert_equal(mz, mat)
|
| 1065 |
+
assert_equal(mz.dtype, mat.dtype)
|
| 1066 |
+
|
| 1067 |
+
for mat in self.rshft_all:
|
| 1068 |
+
tz(mat.astype(dt))
|
| 1069 |
+
if dt != object:
|
| 1070 |
+
tz(self.stacked.astype(dt))
|
| 1071 |
+
|
| 1072 |
+
def test_power_is_two(self, dt):
|
| 1073 |
+
def tz(mat):
|
| 1074 |
+
mz = matrix_power(mat, 2)
|
| 1075 |
+
mmul = matmul if mat.dtype != object else dot
|
| 1076 |
+
assert_equal(mz, mmul(mat, mat))
|
| 1077 |
+
assert_equal(mz.dtype, mat.dtype)
|
| 1078 |
+
|
| 1079 |
+
for mat in self.rshft_all:
|
| 1080 |
+
tz(mat.astype(dt))
|
| 1081 |
+
if dt != object:
|
| 1082 |
+
tz(self.stacked.astype(dt))
|
| 1083 |
+
|
| 1084 |
+
def test_power_is_minus_one(self, dt):
|
| 1085 |
+
def tz(mat):
|
| 1086 |
+
invmat = matrix_power(mat, -1)
|
| 1087 |
+
mmul = matmul if mat.dtype != object else dot
|
| 1088 |
+
assert_almost_equal(
|
| 1089 |
+
mmul(invmat, mat), identity_like_generalized(mat))
|
| 1090 |
+
|
| 1091 |
+
for mat in self.rshft_all:
|
| 1092 |
+
if dt not in self.dtnoinv:
|
| 1093 |
+
tz(mat.astype(dt))
|
| 1094 |
+
|
| 1095 |
+
def test_exceptions_bad_power(self, dt):
|
| 1096 |
+
mat = self.rshft_0.astype(dt)
|
| 1097 |
+
assert_raises(TypeError, matrix_power, mat, 1.5)
|
| 1098 |
+
assert_raises(TypeError, matrix_power, mat, [1])
|
| 1099 |
+
|
| 1100 |
+
def test_exceptions_non_square(self, dt):
|
| 1101 |
+
assert_raises(LinAlgError, matrix_power, np.array([1], dt), 1)
|
| 1102 |
+
assert_raises(LinAlgError, matrix_power, np.array([[1], [2]], dt), 1)
|
| 1103 |
+
assert_raises(LinAlgError, matrix_power, np.ones((4, 3, 2), dt), 1)
|
| 1104 |
+
|
| 1105 |
+
@pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
|
| 1106 |
+
def test_exceptions_not_invertible(self, dt):
|
| 1107 |
+
if dt in self.dtnoinv:
|
| 1108 |
+
return
|
| 1109 |
+
mat = self.noninv.astype(dt)
|
| 1110 |
+
assert_raises(LinAlgError, matrix_power, mat, -1)
|
| 1111 |
+
|
| 1112 |
+
|
| 1113 |
+
class TestEigvalshCases(HermitianTestCase, HermitianGeneralizedTestCase):
|
| 1114 |
+
|
| 1115 |
+
def do(self, a, b, tags):
|
| 1116 |
+
# note that eigenvalue arrays returned by eig must be sorted since
|
| 1117 |
+
# their order isn't guaranteed.
|
| 1118 |
+
ev = linalg.eigvalsh(a, 'L')
|
| 1119 |
+
evalues, evectors = linalg.eig(a)
|
| 1120 |
+
evalues.sort(axis=-1)
|
| 1121 |
+
assert_allclose(ev, evalues, rtol=get_rtol(ev.dtype))
|
| 1122 |
+
|
| 1123 |
+
ev2 = linalg.eigvalsh(a, 'U')
|
| 1124 |
+
assert_allclose(ev2, evalues, rtol=get_rtol(ev.dtype))
|
| 1125 |
+
|
| 1126 |
+
|
| 1127 |
+
class TestEigvalsh:
|
| 1128 |
+
@pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
|
| 1129 |
+
def test_types(self, dtype):
|
| 1130 |
+
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
|
| 1131 |
+
w = np.linalg.eigvalsh(x)
|
| 1132 |
+
assert_equal(w.dtype, get_real_dtype(dtype))
|
| 1133 |
+
|
| 1134 |
+
def test_invalid(self):
|
| 1135 |
+
x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
|
| 1136 |
+
assert_raises(ValueError, np.linalg.eigvalsh, x, UPLO="lrong")
|
| 1137 |
+
assert_raises(ValueError, np.linalg.eigvalsh, x, "lower")
|
| 1138 |
+
assert_raises(ValueError, np.linalg.eigvalsh, x, "upper")
|
| 1139 |
+
|
| 1140 |
+
def test_UPLO(self):
|
| 1141 |
+
Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
|
| 1142 |
+
Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
|
| 1143 |
+
tgt = np.array([-1, 1], dtype=np.double)
|
| 1144 |
+
rtol = get_rtol(np.double)
|
| 1145 |
+
|
| 1146 |
+
# Check default is 'L'
|
| 1147 |
+
w = np.linalg.eigvalsh(Klo)
|
| 1148 |
+
assert_allclose(w, tgt, rtol=rtol)
|
| 1149 |
+
# Check 'L'
|
| 1150 |
+
w = np.linalg.eigvalsh(Klo, UPLO='L')
|
| 1151 |
+
assert_allclose(w, tgt, rtol=rtol)
|
| 1152 |
+
# Check 'l'
|
| 1153 |
+
w = np.linalg.eigvalsh(Klo, UPLO='l')
|
| 1154 |
+
assert_allclose(w, tgt, rtol=rtol)
|
| 1155 |
+
# Check 'U'
|
| 1156 |
+
w = np.linalg.eigvalsh(Kup, UPLO='U')
|
| 1157 |
+
assert_allclose(w, tgt, rtol=rtol)
|
| 1158 |
+
# Check 'u'
|
| 1159 |
+
w = np.linalg.eigvalsh(Kup, UPLO='u')
|
| 1160 |
+
assert_allclose(w, tgt, rtol=rtol)
|
| 1161 |
+
|
| 1162 |
+
def test_0_size(self):
|
| 1163 |
+
# Check that all kinds of 0-sized arrays work
|
| 1164 |
+
class ArraySubclass(np.ndarray):
|
| 1165 |
+
pass
|
| 1166 |
+
a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
|
| 1167 |
+
res = linalg.eigvalsh(a)
|
| 1168 |
+
assert_(res.dtype.type is np.float64)
|
| 1169 |
+
assert_equal((0, 1), res.shape)
|
| 1170 |
+
# This is just for documentation, it might make sense to change:
|
| 1171 |
+
assert_(isinstance(res, np.ndarray))
|
| 1172 |
+
|
| 1173 |
+
a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
|
| 1174 |
+
res = linalg.eigvalsh(a)
|
| 1175 |
+
assert_(res.dtype.type is np.float32)
|
| 1176 |
+
assert_equal((0,), res.shape)
|
| 1177 |
+
# This is just for documentation, it might make sense to change:
|
| 1178 |
+
assert_(isinstance(res, np.ndarray))
|
| 1179 |
+
|
| 1180 |
+
|
| 1181 |
+
class TestEighCases(HermitianTestCase, HermitianGeneralizedTestCase):
|
| 1182 |
+
|
| 1183 |
+
def do(self, a, b, tags):
|
| 1184 |
+
# note that eigenvalue arrays returned by eig must be sorted since
|
| 1185 |
+
# their order isn't guaranteed.
|
| 1186 |
+
res = linalg.eigh(a)
|
| 1187 |
+
ev, evc = res.eigenvalues, res.eigenvectors
|
| 1188 |
+
evalues, evectors = linalg.eig(a)
|
| 1189 |
+
evalues.sort(axis=-1)
|
| 1190 |
+
assert_almost_equal(ev, evalues)
|
| 1191 |
+
|
| 1192 |
+
assert_allclose(matmul(a, evc),
|
| 1193 |
+
np.asarray(ev)[..., None, :] * np.asarray(evc),
|
| 1194 |
+
rtol=get_rtol(ev.dtype))
|
| 1195 |
+
|
| 1196 |
+
ev2, evc2 = linalg.eigh(a, 'U')
|
| 1197 |
+
assert_almost_equal(ev2, evalues)
|
| 1198 |
+
|
| 1199 |
+
assert_allclose(matmul(a, evc2),
|
| 1200 |
+
np.asarray(ev2)[..., None, :] * np.asarray(evc2),
|
| 1201 |
+
rtol=get_rtol(ev.dtype), err_msg=repr(a))
|
| 1202 |
+
|
| 1203 |
+
|
| 1204 |
+
class TestEigh:
|
| 1205 |
+
@pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
|
| 1206 |
+
def test_types(self, dtype):
|
| 1207 |
+
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
|
| 1208 |
+
w, v = np.linalg.eigh(x)
|
| 1209 |
+
assert_equal(w.dtype, get_real_dtype(dtype))
|
| 1210 |
+
assert_equal(v.dtype, dtype)
|
| 1211 |
+
|
| 1212 |
+
def test_invalid(self):
|
| 1213 |
+
x = np.array([[1, 0.5], [0.5, 1]], dtype=np.float32)
|
| 1214 |
+
assert_raises(ValueError, np.linalg.eigh, x, UPLO="lrong")
|
| 1215 |
+
assert_raises(ValueError, np.linalg.eigh, x, "lower")
|
| 1216 |
+
assert_raises(ValueError, np.linalg.eigh, x, "upper")
|
| 1217 |
+
|
| 1218 |
+
def test_UPLO(self):
|
| 1219 |
+
Klo = np.array([[0, 0], [1, 0]], dtype=np.double)
|
| 1220 |
+
Kup = np.array([[0, 1], [0, 0]], dtype=np.double)
|
| 1221 |
+
tgt = np.array([-1, 1], dtype=np.double)
|
| 1222 |
+
rtol = get_rtol(np.double)
|
| 1223 |
+
|
| 1224 |
+
# Check default is 'L'
|
| 1225 |
+
w, v = np.linalg.eigh(Klo)
|
| 1226 |
+
assert_allclose(w, tgt, rtol=rtol)
|
| 1227 |
+
# Check 'L'
|
| 1228 |
+
w, v = np.linalg.eigh(Klo, UPLO='L')
|
| 1229 |
+
assert_allclose(w, tgt, rtol=rtol)
|
| 1230 |
+
# Check 'l'
|
| 1231 |
+
w, v = np.linalg.eigh(Klo, UPLO='l')
|
| 1232 |
+
assert_allclose(w, tgt, rtol=rtol)
|
| 1233 |
+
# Check 'U'
|
| 1234 |
+
w, v = np.linalg.eigh(Kup, UPLO='U')
|
| 1235 |
+
assert_allclose(w, tgt, rtol=rtol)
|
| 1236 |
+
# Check 'u'
|
| 1237 |
+
w, v = np.linalg.eigh(Kup, UPLO='u')
|
| 1238 |
+
assert_allclose(w, tgt, rtol=rtol)
|
| 1239 |
+
|
| 1240 |
+
def test_0_size(self):
|
| 1241 |
+
# Check that all kinds of 0-sized arrays work
|
| 1242 |
+
class ArraySubclass(np.ndarray):
|
| 1243 |
+
pass
|
| 1244 |
+
a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
|
| 1245 |
+
res, res_v = linalg.eigh(a)
|
| 1246 |
+
assert_(res_v.dtype.type is np.float64)
|
| 1247 |
+
assert_(res.dtype.type is np.float64)
|
| 1248 |
+
assert_equal(a.shape, res_v.shape)
|
| 1249 |
+
assert_equal((0, 1), res.shape)
|
| 1250 |
+
# This is just for documentation, it might make sense to change:
|
| 1251 |
+
assert_(isinstance(a, np.ndarray))
|
| 1252 |
+
|
| 1253 |
+
a = np.zeros((0, 0), dtype=np.complex64).view(ArraySubclass)
|
| 1254 |
+
res, res_v = linalg.eigh(a)
|
| 1255 |
+
assert_(res_v.dtype.type is np.complex64)
|
| 1256 |
+
assert_(res.dtype.type is np.float32)
|
| 1257 |
+
assert_equal(a.shape, res_v.shape)
|
| 1258 |
+
assert_equal((0,), res.shape)
|
| 1259 |
+
# This is just for documentation, it might make sense to change:
|
| 1260 |
+
assert_(isinstance(a, np.ndarray))
|
| 1261 |
+
|
| 1262 |
+
|
| 1263 |
+
class _TestNormBase:
|
| 1264 |
+
dt = None
|
| 1265 |
+
dec = None
|
| 1266 |
+
|
| 1267 |
+
@staticmethod
|
| 1268 |
+
def check_dtype(x, res):
|
| 1269 |
+
if issubclass(x.dtype.type, np.inexact):
|
| 1270 |
+
assert_equal(res.dtype, x.real.dtype)
|
| 1271 |
+
else:
|
| 1272 |
+
# For integer input, don't have to test float precision of output.
|
| 1273 |
+
assert_(issubclass(res.dtype.type, np.floating))
|
| 1274 |
+
|
| 1275 |
+
|
| 1276 |
+
class _TestNormGeneral(_TestNormBase):
|
| 1277 |
+
|
| 1278 |
+
def test_empty(self):
|
| 1279 |
+
assert_equal(norm([]), 0.0)
|
| 1280 |
+
assert_equal(norm(array([], dtype=self.dt)), 0.0)
|
| 1281 |
+
assert_equal(norm(atleast_2d(array([], dtype=self.dt))), 0.0)
|
| 1282 |
+
|
| 1283 |
+
def test_vector_return_type(self):
|
| 1284 |
+
a = np.array([1, 0, 1])
|
| 1285 |
+
|
| 1286 |
+
exact_types = np.typecodes['AllInteger']
|
| 1287 |
+
inexact_types = np.typecodes['AllFloat']
|
| 1288 |
+
|
| 1289 |
+
all_types = exact_types + inexact_types
|
| 1290 |
+
|
| 1291 |
+
for each_type in all_types:
|
| 1292 |
+
at = a.astype(each_type)
|
| 1293 |
+
|
| 1294 |
+
an = norm(at, -np.inf)
|
| 1295 |
+
self.check_dtype(at, an)
|
| 1296 |
+
assert_almost_equal(an, 0.0)
|
| 1297 |
+
|
| 1298 |
+
with suppress_warnings() as sup:
|
| 1299 |
+
sup.filter(RuntimeWarning, "divide by zero encountered")
|
| 1300 |
+
an = norm(at, -1)
|
| 1301 |
+
self.check_dtype(at, an)
|
| 1302 |
+
assert_almost_equal(an, 0.0)
|
| 1303 |
+
|
| 1304 |
+
an = norm(at, 0)
|
| 1305 |
+
self.check_dtype(at, an)
|
| 1306 |
+
assert_almost_equal(an, 2)
|
| 1307 |
+
|
| 1308 |
+
an = norm(at, 1)
|
| 1309 |
+
self.check_dtype(at, an)
|
| 1310 |
+
assert_almost_equal(an, 2.0)
|
| 1311 |
+
|
| 1312 |
+
an = norm(at, 2)
|
| 1313 |
+
self.check_dtype(at, an)
|
| 1314 |
+
assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/2.0))
|
| 1315 |
+
|
| 1316 |
+
an = norm(at, 4)
|
| 1317 |
+
self.check_dtype(at, an)
|
| 1318 |
+
assert_almost_equal(an, an.dtype.type(2.0)**an.dtype.type(1.0/4.0))
|
| 1319 |
+
|
| 1320 |
+
an = norm(at, np.inf)
|
| 1321 |
+
self.check_dtype(at, an)
|
| 1322 |
+
assert_almost_equal(an, 1.0)
|
| 1323 |
+
|
| 1324 |
+
def test_vector(self):
|
| 1325 |
+
a = [1, 2, 3, 4]
|
| 1326 |
+
b = [-1, -2, -3, -4]
|
| 1327 |
+
c = [-1, 2, -3, 4]
|
| 1328 |
+
|
| 1329 |
+
def _test(v):
|
| 1330 |
+
np.testing.assert_almost_equal(norm(v), 30 ** 0.5,
|
| 1331 |
+
decimal=self.dec)
|
| 1332 |
+
np.testing.assert_almost_equal(norm(v, inf), 4.0,
|
| 1333 |
+
decimal=self.dec)
|
| 1334 |
+
np.testing.assert_almost_equal(norm(v, -inf), 1.0,
|
| 1335 |
+
decimal=self.dec)
|
| 1336 |
+
np.testing.assert_almost_equal(norm(v, 1), 10.0,
|
| 1337 |
+
decimal=self.dec)
|
| 1338 |
+
np.testing.assert_almost_equal(norm(v, -1), 12.0 / 25,
|
| 1339 |
+
decimal=self.dec)
|
| 1340 |
+
np.testing.assert_almost_equal(norm(v, 2), 30 ** 0.5,
|
| 1341 |
+
decimal=self.dec)
|
| 1342 |
+
np.testing.assert_almost_equal(norm(v, -2), ((205. / 144) ** -0.5),
|
| 1343 |
+
decimal=self.dec)
|
| 1344 |
+
np.testing.assert_almost_equal(norm(v, 0), 4,
|
| 1345 |
+
decimal=self.dec)
|
| 1346 |
+
|
| 1347 |
+
for v in (a, b, c,):
|
| 1348 |
+
_test(v)
|
| 1349 |
+
|
| 1350 |
+
for v in (array(a, dtype=self.dt), array(b, dtype=self.dt),
|
| 1351 |
+
array(c, dtype=self.dt)):
|
| 1352 |
+
_test(v)
|
| 1353 |
+
|
| 1354 |
+
def test_axis(self):
|
| 1355 |
+
# Vector norms.
|
| 1356 |
+
# Compare the use of `axis` with computing the norm of each row
|
| 1357 |
+
# or column separately.
|
| 1358 |
+
A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
|
| 1359 |
+
for order in [None, -1, 0, 1, 2, 3, np.inf, -np.inf]:
|
| 1360 |
+
expected0 = [norm(A[:, k], ord=order) for k in range(A.shape[1])]
|
| 1361 |
+
assert_almost_equal(norm(A, ord=order, axis=0), expected0)
|
| 1362 |
+
expected1 = [norm(A[k, :], ord=order) for k in range(A.shape[0])]
|
| 1363 |
+
assert_almost_equal(norm(A, ord=order, axis=1), expected1)
|
| 1364 |
+
|
| 1365 |
+
# Matrix norms.
|
| 1366 |
+
B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
|
| 1367 |
+
nd = B.ndim
|
| 1368 |
+
for order in [None, -2, 2, -1, 1, np.inf, -np.inf, 'fro']:
|
| 1369 |
+
for axis in itertools.combinations(range(-nd, nd), 2):
|
| 1370 |
+
row_axis, col_axis = axis
|
| 1371 |
+
if row_axis < 0:
|
| 1372 |
+
row_axis += nd
|
| 1373 |
+
if col_axis < 0:
|
| 1374 |
+
col_axis += nd
|
| 1375 |
+
if row_axis == col_axis:
|
| 1376 |
+
assert_raises(ValueError, norm, B, ord=order, axis=axis)
|
| 1377 |
+
else:
|
| 1378 |
+
n = norm(B, ord=order, axis=axis)
|
| 1379 |
+
|
| 1380 |
+
# The logic using k_index only works for nd = 3.
|
| 1381 |
+
# This has to be changed if nd is increased.
|
| 1382 |
+
k_index = nd - (row_axis + col_axis)
|
| 1383 |
+
if row_axis < col_axis:
|
| 1384 |
+
expected = [norm(B[:].take(k, axis=k_index), ord=order)
|
| 1385 |
+
for k in range(B.shape[k_index])]
|
| 1386 |
+
else:
|
| 1387 |
+
expected = [norm(B[:].take(k, axis=k_index).T, ord=order)
|
| 1388 |
+
for k in range(B.shape[k_index])]
|
| 1389 |
+
assert_almost_equal(n, expected)
|
| 1390 |
+
|
| 1391 |
+
def test_keepdims(self):
|
| 1392 |
+
A = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
|
| 1393 |
+
|
| 1394 |
+
allclose_err = 'order {0}, axis = {1}'
|
| 1395 |
+
shape_err = 'Shape mismatch found {0}, expected {1}, order={2}, axis={3}'
|
| 1396 |
+
|
| 1397 |
+
# check the order=None, axis=None case
|
| 1398 |
+
expected = norm(A, ord=None, axis=None)
|
| 1399 |
+
found = norm(A, ord=None, axis=None, keepdims=True)
|
| 1400 |
+
assert_allclose(np.squeeze(found), expected,
|
| 1401 |
+
err_msg=allclose_err.format(None, None))
|
| 1402 |
+
expected_shape = (1, 1, 1)
|
| 1403 |
+
assert_(found.shape == expected_shape,
|
| 1404 |
+
shape_err.format(found.shape, expected_shape, None, None))
|
| 1405 |
+
|
| 1406 |
+
# Vector norms.
|
| 1407 |
+
for order in [None, -1, 0, 1, 2, 3, np.inf, -np.inf]:
|
| 1408 |
+
for k in range(A.ndim):
|
| 1409 |
+
expected = norm(A, ord=order, axis=k)
|
| 1410 |
+
found = norm(A, ord=order, axis=k, keepdims=True)
|
| 1411 |
+
assert_allclose(np.squeeze(found), expected,
|
| 1412 |
+
err_msg=allclose_err.format(order, k))
|
| 1413 |
+
expected_shape = list(A.shape)
|
| 1414 |
+
expected_shape[k] = 1
|
| 1415 |
+
expected_shape = tuple(expected_shape)
|
| 1416 |
+
assert_(found.shape == expected_shape,
|
| 1417 |
+
shape_err.format(found.shape, expected_shape, order, k))
|
| 1418 |
+
|
| 1419 |
+
# Matrix norms.
|
| 1420 |
+
for order in [None, -2, 2, -1, 1, np.inf, -np.inf, 'fro', 'nuc']:
|
| 1421 |
+
for k in itertools.permutations(range(A.ndim), 2):
|
| 1422 |
+
expected = norm(A, ord=order, axis=k)
|
| 1423 |
+
found = norm(A, ord=order, axis=k, keepdims=True)
|
| 1424 |
+
assert_allclose(np.squeeze(found), expected,
|
| 1425 |
+
err_msg=allclose_err.format(order, k))
|
| 1426 |
+
expected_shape = list(A.shape)
|
| 1427 |
+
expected_shape[k[0]] = 1
|
| 1428 |
+
expected_shape[k[1]] = 1
|
| 1429 |
+
expected_shape = tuple(expected_shape)
|
| 1430 |
+
assert_(found.shape == expected_shape,
|
| 1431 |
+
shape_err.format(found.shape, expected_shape, order, k))
|
| 1432 |
+
|
| 1433 |
+
|
| 1434 |
+
class _TestNorm2D(_TestNormBase):
|
| 1435 |
+
# Define the part for 2d arrays separately, so we can subclass this
|
| 1436 |
+
# and run the tests using np.matrix in matrixlib.tests.test_matrix_linalg.
|
| 1437 |
+
array = np.array
|
| 1438 |
+
|
| 1439 |
+
def test_matrix_empty(self):
|
| 1440 |
+
assert_equal(norm(self.array([[]], dtype=self.dt)), 0.0)
|
| 1441 |
+
|
| 1442 |
+
def test_matrix_return_type(self):
|
| 1443 |
+
a = self.array([[1, 0, 1], [0, 1, 1]])
|
| 1444 |
+
|
| 1445 |
+
exact_types = np.typecodes['AllInteger']
|
| 1446 |
+
|
| 1447 |
+
# float32, complex64, float64, complex128 types are the only types
|
| 1448 |
+
# allowed by `linalg`, which performs the matrix operations used
|
| 1449 |
+
# within `norm`.
|
| 1450 |
+
inexact_types = 'fdFD'
|
| 1451 |
+
|
| 1452 |
+
all_types = exact_types + inexact_types
|
| 1453 |
+
|
| 1454 |
+
for each_type in all_types:
|
| 1455 |
+
at = a.astype(each_type)
|
| 1456 |
+
|
| 1457 |
+
an = norm(at, -np.inf)
|
| 1458 |
+
self.check_dtype(at, an)
|
| 1459 |
+
assert_almost_equal(an, 2.0)
|
| 1460 |
+
|
| 1461 |
+
with suppress_warnings() as sup:
|
| 1462 |
+
sup.filter(RuntimeWarning, "divide by zero encountered")
|
| 1463 |
+
an = norm(at, -1)
|
| 1464 |
+
self.check_dtype(at, an)
|
| 1465 |
+
assert_almost_equal(an, 1.0)
|
| 1466 |
+
|
| 1467 |
+
an = norm(at, 1)
|
| 1468 |
+
self.check_dtype(at, an)
|
| 1469 |
+
assert_almost_equal(an, 2.0)
|
| 1470 |
+
|
| 1471 |
+
an = norm(at, 2)
|
| 1472 |
+
self.check_dtype(at, an)
|
| 1473 |
+
assert_almost_equal(an, 3.0**(1.0/2.0))
|
| 1474 |
+
|
| 1475 |
+
an = norm(at, -2)
|
| 1476 |
+
self.check_dtype(at, an)
|
| 1477 |
+
assert_almost_equal(an, 1.0)
|
| 1478 |
+
|
| 1479 |
+
an = norm(at, np.inf)
|
| 1480 |
+
self.check_dtype(at, an)
|
| 1481 |
+
assert_almost_equal(an, 2.0)
|
| 1482 |
+
|
| 1483 |
+
an = norm(at, 'fro')
|
| 1484 |
+
self.check_dtype(at, an)
|
| 1485 |
+
assert_almost_equal(an, 2.0)
|
| 1486 |
+
|
| 1487 |
+
an = norm(at, 'nuc')
|
| 1488 |
+
self.check_dtype(at, an)
|
| 1489 |
+
# Lower bar needed to support low precision floats.
|
| 1490 |
+
# They end up being off by 1 in the 7th place.
|
| 1491 |
+
np.testing.assert_almost_equal(an, 2.7320508075688772, decimal=6)
|
| 1492 |
+
|
| 1493 |
+
def test_matrix_2x2(self):
|
| 1494 |
+
A = self.array([[1, 3], [5, 7]], dtype=self.dt)
|
| 1495 |
+
assert_almost_equal(norm(A), 84 ** 0.5)
|
| 1496 |
+
assert_almost_equal(norm(A, 'fro'), 84 ** 0.5)
|
| 1497 |
+
assert_almost_equal(norm(A, 'nuc'), 10.0)
|
| 1498 |
+
assert_almost_equal(norm(A, inf), 12.0)
|
| 1499 |
+
assert_almost_equal(norm(A, -inf), 4.0)
|
| 1500 |
+
assert_almost_equal(norm(A, 1), 10.0)
|
| 1501 |
+
assert_almost_equal(norm(A, -1), 6.0)
|
| 1502 |
+
assert_almost_equal(norm(A, 2), 9.1231056256176615)
|
| 1503 |
+
assert_almost_equal(norm(A, -2), 0.87689437438234041)
|
| 1504 |
+
|
| 1505 |
+
assert_raises(ValueError, norm, A, 'nofro')
|
| 1506 |
+
assert_raises(ValueError, norm, A, -3)
|
| 1507 |
+
assert_raises(ValueError, norm, A, 0)
|
| 1508 |
+
|
| 1509 |
+
def test_matrix_3x3(self):
|
| 1510 |
+
# This test has been added because the 2x2 example
|
| 1511 |
+
# happened to have equal nuclear norm and induced 1-norm.
|
| 1512 |
+
# The 1/10 scaling factor accommodates the absolute tolerance
|
| 1513 |
+
# used in assert_almost_equal.
|
| 1514 |
+
A = (1 / 10) * \
|
| 1515 |
+
self.array([[1, 2, 3], [6, 0, 5], [3, 2, 1]], dtype=self.dt)
|
| 1516 |
+
assert_almost_equal(norm(A), (1 / 10) * 89 ** 0.5)
|
| 1517 |
+
assert_almost_equal(norm(A, 'fro'), (1 / 10) * 89 ** 0.5)
|
| 1518 |
+
assert_almost_equal(norm(A, 'nuc'), 1.3366836911774836)
|
| 1519 |
+
assert_almost_equal(norm(A, inf), 1.1)
|
| 1520 |
+
assert_almost_equal(norm(A, -inf), 0.6)
|
| 1521 |
+
assert_almost_equal(norm(A, 1), 1.0)
|
| 1522 |
+
assert_almost_equal(norm(A, -1), 0.4)
|
| 1523 |
+
assert_almost_equal(norm(A, 2), 0.88722940323461277)
|
| 1524 |
+
assert_almost_equal(norm(A, -2), 0.19456584790481812)
|
| 1525 |
+
|
| 1526 |
+
def test_bad_args(self):
|
| 1527 |
+
# Check that bad arguments raise the appropriate exceptions.
|
| 1528 |
+
|
| 1529 |
+
A = self.array([[1, 2, 3], [4, 5, 6]], dtype=self.dt)
|
| 1530 |
+
B = np.arange(1, 25, dtype=self.dt).reshape(2, 3, 4)
|
| 1531 |
+
|
| 1532 |
+
# Using `axis=<integer>` or passing in a 1-D array implies vector
|
| 1533 |
+
# norms are being computed, so also using `ord='fro'`
|
| 1534 |
+
# or `ord='nuc'` or any other string raises a ValueError.
|
| 1535 |
+
assert_raises(ValueError, norm, A, 'fro', 0)
|
| 1536 |
+
assert_raises(ValueError, norm, A, 'nuc', 0)
|
| 1537 |
+
assert_raises(ValueError, norm, [3, 4], 'fro', None)
|
| 1538 |
+
assert_raises(ValueError, norm, [3, 4], 'nuc', None)
|
| 1539 |
+
assert_raises(ValueError, norm, [3, 4], 'test', None)
|
| 1540 |
+
|
| 1541 |
+
# Similarly, norm should raise an exception when ord is any finite
|
| 1542 |
+
# number other than 1, 2, -1 or -2 when computing matrix norms.
|
| 1543 |
+
for order in [0, 3]:
|
| 1544 |
+
assert_raises(ValueError, norm, A, order, None)
|
| 1545 |
+
assert_raises(ValueError, norm, A, order, (0, 1))
|
| 1546 |
+
assert_raises(ValueError, norm, B, order, (1, 2))
|
| 1547 |
+
|
| 1548 |
+
# Invalid axis
|
| 1549 |
+
assert_raises(AxisError, norm, B, None, 3)
|
| 1550 |
+
assert_raises(AxisError, norm, B, None, (2, 3))
|
| 1551 |
+
assert_raises(ValueError, norm, B, None, (0, 1, 2))
|
| 1552 |
+
|
| 1553 |
+
|
| 1554 |
+
class _TestNorm(_TestNorm2D, _TestNormGeneral):
|
| 1555 |
+
pass
|
| 1556 |
+
|
| 1557 |
+
|
| 1558 |
+
class TestNorm_NonSystematic:
|
| 1559 |
+
|
| 1560 |
+
def test_longdouble_norm(self):
|
| 1561 |
+
# Non-regression test: p-norm of longdouble would previously raise
|
| 1562 |
+
# UnboundLocalError.
|
| 1563 |
+
x = np.arange(10, dtype=np.longdouble)
|
| 1564 |
+
old_assert_almost_equal(norm(x, ord=3), 12.65, decimal=2)
|
| 1565 |
+
|
| 1566 |
+
def test_intmin(self):
|
| 1567 |
+
# Non-regression test: p-norm of signed integer would previously do
|
| 1568 |
+
# float cast and abs in the wrong order.
|
| 1569 |
+
x = np.array([-2 ** 31], dtype=np.int32)
|
| 1570 |
+
old_assert_almost_equal(norm(x, ord=3), 2 ** 31, decimal=5)
|
| 1571 |
+
|
| 1572 |
+
def test_complex_high_ord(self):
|
| 1573 |
+
# gh-4156
|
| 1574 |
+
d = np.empty((2,), dtype=np.clongdouble)
|
| 1575 |
+
d[0] = 6 + 7j
|
| 1576 |
+
d[1] = -6 + 7j
|
| 1577 |
+
res = 11.615898132184
|
| 1578 |
+
old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=10)
|
| 1579 |
+
d = d.astype(np.complex128)
|
| 1580 |
+
old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=9)
|
| 1581 |
+
d = d.astype(np.complex64)
|
| 1582 |
+
old_assert_almost_equal(np.linalg.norm(d, ord=3), res, decimal=5)
|
| 1583 |
+
|
| 1584 |
+
|
| 1585 |
+
# Separate definitions so we can use them for matrix tests.
|
| 1586 |
+
class _TestNormDoubleBase(_TestNormBase):
|
| 1587 |
+
dt = np.double
|
| 1588 |
+
dec = 12
|
| 1589 |
+
|
| 1590 |
+
|
| 1591 |
+
class _TestNormSingleBase(_TestNormBase):
|
| 1592 |
+
dt = np.float32
|
| 1593 |
+
dec = 6
|
| 1594 |
+
|
| 1595 |
+
|
| 1596 |
+
class _TestNormInt64Base(_TestNormBase):
|
| 1597 |
+
dt = np.int64
|
| 1598 |
+
dec = 12
|
| 1599 |
+
|
| 1600 |
+
|
| 1601 |
+
class TestNormDouble(_TestNorm, _TestNormDoubleBase):
|
| 1602 |
+
pass
|
| 1603 |
+
|
| 1604 |
+
|
| 1605 |
+
class TestNormSingle(_TestNorm, _TestNormSingleBase):
|
| 1606 |
+
pass
|
| 1607 |
+
|
| 1608 |
+
|
| 1609 |
+
class TestNormInt64(_TestNorm, _TestNormInt64Base):
|
| 1610 |
+
pass
|
| 1611 |
+
|
| 1612 |
+
|
| 1613 |
+
class TestMatrixRank:
|
| 1614 |
+
|
| 1615 |
+
def test_matrix_rank(self):
|
| 1616 |
+
# Full rank matrix
|
| 1617 |
+
assert_equal(4, matrix_rank(np.eye(4)))
|
| 1618 |
+
# rank deficient matrix
|
| 1619 |
+
I = np.eye(4)
|
| 1620 |
+
I[-1, -1] = 0.
|
| 1621 |
+
assert_equal(matrix_rank(I), 3)
|
| 1622 |
+
# All zeros - zero rank
|
| 1623 |
+
assert_equal(matrix_rank(np.zeros((4, 4))), 0)
|
| 1624 |
+
# 1 dimension - rank 1 unless all 0
|
| 1625 |
+
assert_equal(matrix_rank([1, 0, 0, 0]), 1)
|
| 1626 |
+
assert_equal(matrix_rank(np.zeros((4,))), 0)
|
| 1627 |
+
# accepts array-like
|
| 1628 |
+
assert_equal(matrix_rank([1]), 1)
|
| 1629 |
+
# greater than 2 dimensions treated as stacked matrices
|
| 1630 |
+
ms = np.array([I, np.eye(4), np.zeros((4,4))])
|
| 1631 |
+
assert_equal(matrix_rank(ms), np.array([3, 4, 0]))
|
| 1632 |
+
# works on scalar
|
| 1633 |
+
assert_equal(matrix_rank(1), 1)
|
| 1634 |
+
|
| 1635 |
+
with assert_raises_regex(
|
| 1636 |
+
ValueError, "`tol` and `rtol` can\'t be both set."
|
| 1637 |
+
):
|
| 1638 |
+
matrix_rank(I, tol=0.01, rtol=0.01)
|
| 1639 |
+
|
| 1640 |
+
def test_symmetric_rank(self):
|
| 1641 |
+
assert_equal(4, matrix_rank(np.eye(4), hermitian=True))
|
| 1642 |
+
assert_equal(1, matrix_rank(np.ones((4, 4)), hermitian=True))
|
| 1643 |
+
assert_equal(0, matrix_rank(np.zeros((4, 4)), hermitian=True))
|
| 1644 |
+
# rank deficient matrix
|
| 1645 |
+
I = np.eye(4)
|
| 1646 |
+
I[-1, -1] = 0.
|
| 1647 |
+
assert_equal(3, matrix_rank(I, hermitian=True))
|
| 1648 |
+
# manually supplied tolerance
|
| 1649 |
+
I[-1, -1] = 1e-8
|
| 1650 |
+
assert_equal(4, matrix_rank(I, hermitian=True, tol=0.99e-8))
|
| 1651 |
+
assert_equal(3, matrix_rank(I, hermitian=True, tol=1.01e-8))
|
| 1652 |
+
|
| 1653 |
+
|
| 1654 |
+
def test_reduced_rank():
|
| 1655 |
+
# Test matrices with reduced rank
|
| 1656 |
+
rng = np.random.RandomState(20120714)
|
| 1657 |
+
for i in range(100):
|
| 1658 |
+
# Make a rank deficient matrix
|
| 1659 |
+
X = rng.normal(size=(40, 10))
|
| 1660 |
+
X[:, 0] = X[:, 1] + X[:, 2]
|
| 1661 |
+
# Assert that matrix_rank detected deficiency
|
| 1662 |
+
assert_equal(matrix_rank(X), 9)
|
| 1663 |
+
X[:, 3] = X[:, 4] + X[:, 5]
|
| 1664 |
+
assert_equal(matrix_rank(X), 8)
|
| 1665 |
+
|
| 1666 |
+
|
| 1667 |
+
class TestQR:
|
| 1668 |
+
# Define the array class here, so run this on matrices elsewhere.
|
| 1669 |
+
array = np.array
|
| 1670 |
+
|
| 1671 |
+
def check_qr(self, a):
|
| 1672 |
+
# This test expects the argument `a` to be an ndarray or
|
| 1673 |
+
# a subclass of an ndarray of inexact type.
|
| 1674 |
+
a_type = type(a)
|
| 1675 |
+
a_dtype = a.dtype
|
| 1676 |
+
m, n = a.shape
|
| 1677 |
+
k = min(m, n)
|
| 1678 |
+
|
| 1679 |
+
# mode == 'complete'
|
| 1680 |
+
res = linalg.qr(a, mode='complete')
|
| 1681 |
+
Q, R = res.Q, res.R
|
| 1682 |
+
assert_(Q.dtype == a_dtype)
|
| 1683 |
+
assert_(R.dtype == a_dtype)
|
| 1684 |
+
assert_(isinstance(Q, a_type))
|
| 1685 |
+
assert_(isinstance(R, a_type))
|
| 1686 |
+
assert_(Q.shape == (m, m))
|
| 1687 |
+
assert_(R.shape == (m, n))
|
| 1688 |
+
assert_almost_equal(dot(Q, R), a)
|
| 1689 |
+
assert_almost_equal(dot(Q.T.conj(), Q), np.eye(m))
|
| 1690 |
+
assert_almost_equal(np.triu(R), R)
|
| 1691 |
+
|
| 1692 |
+
# mode == 'reduced'
|
| 1693 |
+
q1, r1 = linalg.qr(a, mode='reduced')
|
| 1694 |
+
assert_(q1.dtype == a_dtype)
|
| 1695 |
+
assert_(r1.dtype == a_dtype)
|
| 1696 |
+
assert_(isinstance(q1, a_type))
|
| 1697 |
+
assert_(isinstance(r1, a_type))
|
| 1698 |
+
assert_(q1.shape == (m, k))
|
| 1699 |
+
assert_(r1.shape == (k, n))
|
| 1700 |
+
assert_almost_equal(dot(q1, r1), a)
|
| 1701 |
+
assert_almost_equal(dot(q1.T.conj(), q1), np.eye(k))
|
| 1702 |
+
assert_almost_equal(np.triu(r1), r1)
|
| 1703 |
+
|
| 1704 |
+
# mode == 'r'
|
| 1705 |
+
r2 = linalg.qr(a, mode='r')
|
| 1706 |
+
assert_(r2.dtype == a_dtype)
|
| 1707 |
+
assert_(isinstance(r2, a_type))
|
| 1708 |
+
assert_almost_equal(r2, r1)
|
| 1709 |
+
|
| 1710 |
+
|
| 1711 |
+
@pytest.mark.parametrize(["m", "n"], [
|
| 1712 |
+
(3, 0),
|
| 1713 |
+
(0, 3),
|
| 1714 |
+
(0, 0)
|
| 1715 |
+
])
|
| 1716 |
+
def test_qr_empty(self, m, n):
|
| 1717 |
+
k = min(m, n)
|
| 1718 |
+
a = np.empty((m, n))
|
| 1719 |
+
|
| 1720 |
+
self.check_qr(a)
|
| 1721 |
+
|
| 1722 |
+
h, tau = np.linalg.qr(a, mode='raw')
|
| 1723 |
+
assert_equal(h.dtype, np.double)
|
| 1724 |
+
assert_equal(tau.dtype, np.double)
|
| 1725 |
+
assert_equal(h.shape, (n, m))
|
| 1726 |
+
assert_equal(tau.shape, (k,))
|
| 1727 |
+
|
| 1728 |
+
def test_mode_raw(self):
|
| 1729 |
+
# The factorization is not unique and varies between libraries,
|
| 1730 |
+
# so it is not possible to check against known values. Functional
|
| 1731 |
+
# testing is a possibility, but awaits the exposure of more
|
| 1732 |
+
# of the functions in lapack_lite. Consequently, this test is
|
| 1733 |
+
# very limited in scope. Note that the results are in FORTRAN
|
| 1734 |
+
# order, hence the h arrays are transposed.
|
| 1735 |
+
a = self.array([[1, 2], [3, 4], [5, 6]], dtype=np.double)
|
| 1736 |
+
|
| 1737 |
+
# Test double
|
| 1738 |
+
h, tau = linalg.qr(a, mode='raw')
|
| 1739 |
+
assert_(h.dtype == np.double)
|
| 1740 |
+
assert_(tau.dtype == np.double)
|
| 1741 |
+
assert_(h.shape == (2, 3))
|
| 1742 |
+
assert_(tau.shape == (2,))
|
| 1743 |
+
|
| 1744 |
+
h, tau = linalg.qr(a.T, mode='raw')
|
| 1745 |
+
assert_(h.dtype == np.double)
|
| 1746 |
+
assert_(tau.dtype == np.double)
|
| 1747 |
+
assert_(h.shape == (3, 2))
|
| 1748 |
+
assert_(tau.shape == (2,))
|
| 1749 |
+
|
| 1750 |
+
def test_mode_all_but_economic(self):
|
| 1751 |
+
a = self.array([[1, 2], [3, 4]])
|
| 1752 |
+
b = self.array([[1, 2], [3, 4], [5, 6]])
|
| 1753 |
+
for dt in "fd":
|
| 1754 |
+
m1 = a.astype(dt)
|
| 1755 |
+
m2 = b.astype(dt)
|
| 1756 |
+
self.check_qr(m1)
|
| 1757 |
+
self.check_qr(m2)
|
| 1758 |
+
self.check_qr(m2.T)
|
| 1759 |
+
|
| 1760 |
+
for dt in "fd":
|
| 1761 |
+
m1 = 1 + 1j * a.astype(dt)
|
| 1762 |
+
m2 = 1 + 1j * b.astype(dt)
|
| 1763 |
+
self.check_qr(m1)
|
| 1764 |
+
self.check_qr(m2)
|
| 1765 |
+
self.check_qr(m2.T)
|
| 1766 |
+
|
| 1767 |
+
def check_qr_stacked(self, a):
|
| 1768 |
+
# This test expects the argument `a` to be an ndarray or
|
| 1769 |
+
# a subclass of an ndarray of inexact type.
|
| 1770 |
+
a_type = type(a)
|
| 1771 |
+
a_dtype = a.dtype
|
| 1772 |
+
m, n = a.shape[-2:]
|
| 1773 |
+
k = min(m, n)
|
| 1774 |
+
|
| 1775 |
+
# mode == 'complete'
|
| 1776 |
+
q, r = linalg.qr(a, mode='complete')
|
| 1777 |
+
assert_(q.dtype == a_dtype)
|
| 1778 |
+
assert_(r.dtype == a_dtype)
|
| 1779 |
+
assert_(isinstance(q, a_type))
|
| 1780 |
+
assert_(isinstance(r, a_type))
|
| 1781 |
+
assert_(q.shape[-2:] == (m, m))
|
| 1782 |
+
assert_(r.shape[-2:] == (m, n))
|
| 1783 |
+
assert_almost_equal(matmul(q, r), a)
|
| 1784 |
+
I_mat = np.identity(q.shape[-1])
|
| 1785 |
+
stack_I_mat = np.broadcast_to(I_mat,
|
| 1786 |
+
q.shape[:-2] + (q.shape[-1],)*2)
|
| 1787 |
+
assert_almost_equal(matmul(swapaxes(q, -1, -2).conj(), q), stack_I_mat)
|
| 1788 |
+
assert_almost_equal(np.triu(r[..., :, :]), r)
|
| 1789 |
+
|
| 1790 |
+
# mode == 'reduced'
|
| 1791 |
+
q1, r1 = linalg.qr(a, mode='reduced')
|
| 1792 |
+
assert_(q1.dtype == a_dtype)
|
| 1793 |
+
assert_(r1.dtype == a_dtype)
|
| 1794 |
+
assert_(isinstance(q1, a_type))
|
| 1795 |
+
assert_(isinstance(r1, a_type))
|
| 1796 |
+
assert_(q1.shape[-2:] == (m, k))
|
| 1797 |
+
assert_(r1.shape[-2:] == (k, n))
|
| 1798 |
+
assert_almost_equal(matmul(q1, r1), a)
|
| 1799 |
+
I_mat = np.identity(q1.shape[-1])
|
| 1800 |
+
stack_I_mat = np.broadcast_to(I_mat,
|
| 1801 |
+
q1.shape[:-2] + (q1.shape[-1],)*2)
|
| 1802 |
+
assert_almost_equal(matmul(swapaxes(q1, -1, -2).conj(), q1),
|
| 1803 |
+
stack_I_mat)
|
| 1804 |
+
assert_almost_equal(np.triu(r1[..., :, :]), r1)
|
| 1805 |
+
|
| 1806 |
+
# mode == 'r'
|
| 1807 |
+
r2 = linalg.qr(a, mode='r')
|
| 1808 |
+
assert_(r2.dtype == a_dtype)
|
| 1809 |
+
assert_(isinstance(r2, a_type))
|
| 1810 |
+
assert_almost_equal(r2, r1)
|
| 1811 |
+
|
| 1812 |
+
@pytest.mark.parametrize("size", [
|
| 1813 |
+
(3, 4), (4, 3), (4, 4),
|
| 1814 |
+
(3, 0), (0, 3)])
|
| 1815 |
+
@pytest.mark.parametrize("outer_size", [
|
| 1816 |
+
(2, 2), (2,), (2, 3, 4)])
|
| 1817 |
+
@pytest.mark.parametrize("dt", [
|
| 1818 |
+
np.single, np.double,
|
| 1819 |
+
np.csingle, np.cdouble])
|
| 1820 |
+
def test_stacked_inputs(self, outer_size, size, dt):
|
| 1821 |
+
|
| 1822 |
+
rng = np.random.default_rng(123)
|
| 1823 |
+
A = rng.normal(size=outer_size + size).astype(dt)
|
| 1824 |
+
B = rng.normal(size=outer_size + size).astype(dt)
|
| 1825 |
+
self.check_qr_stacked(A)
|
| 1826 |
+
self.check_qr_stacked(A + 1.j*B)
|
| 1827 |
+
|
| 1828 |
+
|
| 1829 |
+
class TestCholesky:
|
| 1830 |
+
|
| 1831 |
+
@pytest.mark.parametrize(
|
| 1832 |
+
'shape', [(1, 1), (2, 2), (3, 3), (50, 50), (3, 10, 10)]
|
| 1833 |
+
)
|
| 1834 |
+
@pytest.mark.parametrize(
|
| 1835 |
+
'dtype', (np.float32, np.float64, np.complex64, np.complex128)
|
| 1836 |
+
)
|
| 1837 |
+
@pytest.mark.parametrize(
|
| 1838 |
+
'upper', [False, True])
|
| 1839 |
+
def test_basic_property(self, shape, dtype, upper):
|
| 1840 |
+
np.random.seed(1)
|
| 1841 |
+
a = np.random.randn(*shape)
|
| 1842 |
+
if np.issubdtype(dtype, np.complexfloating):
|
| 1843 |
+
a = a + 1j*np.random.randn(*shape)
|
| 1844 |
+
|
| 1845 |
+
t = list(range(len(shape)))
|
| 1846 |
+
t[-2:] = -1, -2
|
| 1847 |
+
|
| 1848 |
+
a = np.matmul(a.transpose(t).conj(), a)
|
| 1849 |
+
a = np.asarray(a, dtype=dtype)
|
| 1850 |
+
|
| 1851 |
+
c = np.linalg.cholesky(a, upper=upper)
|
| 1852 |
+
|
| 1853 |
+
# Check A = L L^H or A = U^H U
|
| 1854 |
+
if upper:
|
| 1855 |
+
b = np.matmul(c.transpose(t).conj(), c)
|
| 1856 |
+
else:
|
| 1857 |
+
b = np.matmul(c, c.transpose(t).conj())
|
| 1858 |
+
|
| 1859 |
+
atol = 500 * a.shape[0] * np.finfo(dtype).eps
|
| 1860 |
+
assert_allclose(b, a, atol=atol, err_msg=f'{shape} {dtype}\n{a}\n{c}')
|
| 1861 |
+
|
| 1862 |
+
# Check diag(L or U) is real and positive
|
| 1863 |
+
d = np.diagonal(c, axis1=-2, axis2=-1)
|
| 1864 |
+
assert_(np.all(np.isreal(d)))
|
| 1865 |
+
assert_(np.all(d >= 0))
|
| 1866 |
+
|
| 1867 |
+
def test_0_size(self):
|
| 1868 |
+
class ArraySubclass(np.ndarray):
|
| 1869 |
+
pass
|
| 1870 |
+
a = np.zeros((0, 1, 1), dtype=np.int_).view(ArraySubclass)
|
| 1871 |
+
res = linalg.cholesky(a)
|
| 1872 |
+
assert_equal(a.shape, res.shape)
|
| 1873 |
+
assert_(res.dtype.type is np.float64)
|
| 1874 |
+
# for documentation purpose:
|
| 1875 |
+
assert_(isinstance(res, np.ndarray))
|
| 1876 |
+
|
| 1877 |
+
a = np.zeros((1, 0, 0), dtype=np.complex64).view(ArraySubclass)
|
| 1878 |
+
res = linalg.cholesky(a)
|
| 1879 |
+
assert_equal(a.shape, res.shape)
|
| 1880 |
+
assert_(res.dtype.type is np.complex64)
|
| 1881 |
+
assert_(isinstance(res, np.ndarray))
|
| 1882 |
+
|
| 1883 |
+
def test_upper_lower_arg(self):
|
| 1884 |
+
# Explicit test of upper argument that also checks the default.
|
| 1885 |
+
a = np.array([[1+0j, 0-2j], [0+2j, 5+0j]])
|
| 1886 |
+
|
| 1887 |
+
assert_equal(linalg.cholesky(a), linalg.cholesky(a, upper=False))
|
| 1888 |
+
|
| 1889 |
+
assert_equal(
|
| 1890 |
+
linalg.cholesky(a, upper=True),
|
| 1891 |
+
linalg.cholesky(a).T.conj()
|
| 1892 |
+
)
|
| 1893 |
+
|
| 1894 |
+
|
| 1895 |
+
class TestOuter:
|
| 1896 |
+
arr1 = np.arange(3)
|
| 1897 |
+
arr2 = np.arange(3)
|
| 1898 |
+
expected = np.array(
|
| 1899 |
+
[[0, 0, 0],
|
| 1900 |
+
[0, 1, 2],
|
| 1901 |
+
[0, 2, 4]]
|
| 1902 |
+
)
|
| 1903 |
+
|
| 1904 |
+
assert_array_equal(np.linalg.outer(arr1, arr2), expected)
|
| 1905 |
+
|
| 1906 |
+
with assert_raises_regex(
|
| 1907 |
+
ValueError, "Input arrays must be one-dimensional"
|
| 1908 |
+
):
|
| 1909 |
+
np.linalg.outer(arr1[:, np.newaxis], arr2)
|
| 1910 |
+
|
| 1911 |
+
|
| 1912 |
+
def test_byteorder_check():
|
| 1913 |
+
# Byte order check should pass for native order
|
| 1914 |
+
if sys.byteorder == 'little':
|
| 1915 |
+
native = '<'
|
| 1916 |
+
else:
|
| 1917 |
+
native = '>'
|
| 1918 |
+
|
| 1919 |
+
for dtt in (np.float32, np.float64):
|
| 1920 |
+
arr = np.eye(4, dtype=dtt)
|
| 1921 |
+
n_arr = arr.view(arr.dtype.newbyteorder(native))
|
| 1922 |
+
sw_arr = arr.view(arr.dtype.newbyteorder("S")).byteswap()
|
| 1923 |
+
assert_equal(arr.dtype.byteorder, '=')
|
| 1924 |
+
for routine in (linalg.inv, linalg.det, linalg.pinv):
|
| 1925 |
+
# Normal call
|
| 1926 |
+
res = routine(arr)
|
| 1927 |
+
# Native but not '='
|
| 1928 |
+
assert_array_equal(res, routine(n_arr))
|
| 1929 |
+
# Swapped
|
| 1930 |
+
assert_array_equal(res, routine(sw_arr))
|
| 1931 |
+
|
| 1932 |
+
|
| 1933 |
+
@pytest.mark.skipif(IS_WASM, reason="fp errors don't work in wasm")
|
| 1934 |
+
def test_generalized_raise_multiloop():
|
| 1935 |
+
# It should raise an error even if the error doesn't occur in the
|
| 1936 |
+
# last iteration of the ufunc inner loop
|
| 1937 |
+
|
| 1938 |
+
invertible = np.array([[1, 2], [3, 4]])
|
| 1939 |
+
non_invertible = np.array([[1, 1], [1, 1]])
|
| 1940 |
+
|
| 1941 |
+
x = np.zeros([4, 4, 2, 2])[1::2]
|
| 1942 |
+
x[...] = invertible
|
| 1943 |
+
x[0, 0] = non_invertible
|
| 1944 |
+
|
| 1945 |
+
assert_raises(np.linalg.LinAlgError, np.linalg.inv, x)
|
| 1946 |
+
|
| 1947 |
+
@pytest.mark.skipif(
|
| 1948 |
+
threading.active_count() > 1,
|
| 1949 |
+
reason="skipping test that uses fork because there are multiple threads")
|
| 1950 |
+
def test_xerbla_override():
|
| 1951 |
+
# Check that our xerbla has been successfully linked in. If it is not,
|
| 1952 |
+
# the default xerbla routine is called, which prints a message to stdout
|
| 1953 |
+
# and may, or may not, abort the process depending on the LAPACK package.
|
| 1954 |
+
|
| 1955 |
+
XERBLA_OK = 255
|
| 1956 |
+
|
| 1957 |
+
try:
|
| 1958 |
+
pid = os.fork()
|
| 1959 |
+
except (OSError, AttributeError):
|
| 1960 |
+
# fork failed, or not running on POSIX
|
| 1961 |
+
pytest.skip("Not POSIX or fork failed.")
|
| 1962 |
+
|
| 1963 |
+
if pid == 0:
|
| 1964 |
+
# child; close i/o file handles
|
| 1965 |
+
os.close(1)
|
| 1966 |
+
os.close(0)
|
| 1967 |
+
# Avoid producing core files.
|
| 1968 |
+
import resource
|
| 1969 |
+
resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
|
| 1970 |
+
# These calls may abort.
|
| 1971 |
+
try:
|
| 1972 |
+
np.linalg.lapack_lite.xerbla()
|
| 1973 |
+
except ValueError:
|
| 1974 |
+
pass
|
| 1975 |
+
except Exception:
|
| 1976 |
+
os._exit(os.EX_CONFIG)
|
| 1977 |
+
|
| 1978 |
+
try:
|
| 1979 |
+
a = np.array([[1.]])
|
| 1980 |
+
np.linalg.lapack_lite.dorgqr(
|
| 1981 |
+
1, 1, 1, a,
|
| 1982 |
+
0, # <- invalid value
|
| 1983 |
+
a, a, 0, 0)
|
| 1984 |
+
except ValueError as e:
|
| 1985 |
+
if "DORGQR parameter number 5" in str(e):
|
| 1986 |
+
# success, reuse error code to mark success as
|
| 1987 |
+
# FORTRAN STOP returns as success.
|
| 1988 |
+
os._exit(XERBLA_OK)
|
| 1989 |
+
|
| 1990 |
+
# Did not abort, but our xerbla was not linked in.
|
| 1991 |
+
os._exit(os.EX_CONFIG)
|
| 1992 |
+
else:
|
| 1993 |
+
# parent
|
| 1994 |
+
pid, status = os.wait()
|
| 1995 |
+
if os.WEXITSTATUS(status) != XERBLA_OK:
|
| 1996 |
+
pytest.skip('Numpy xerbla not linked in.')
|
| 1997 |
+
|
| 1998 |
+
|
| 1999 |
+
@pytest.mark.skipif(IS_WASM, reason="Cannot start subprocess")
|
| 2000 |
+
@pytest.mark.slow
|
| 2001 |
+
def test_sdot_bug_8577():
|
| 2002 |
+
# Regression test that loading certain other libraries does not
|
| 2003 |
+
# result to wrong results in float32 linear algebra.
|
| 2004 |
+
#
|
| 2005 |
+
# There's a bug gh-8577 on OSX that can trigger this, and perhaps
|
| 2006 |
+
# there are also other situations in which it occurs.
|
| 2007 |
+
#
|
| 2008 |
+
# Do the check in a separate process.
|
| 2009 |
+
|
| 2010 |
+
bad_libs = ['PyQt5.QtWidgets', 'IPython']
|
| 2011 |
+
|
| 2012 |
+
template = textwrap.dedent("""
|
| 2013 |
+
import sys
|
| 2014 |
+
{before}
|
| 2015 |
+
try:
|
| 2016 |
+
import {bad_lib}
|
| 2017 |
+
except ImportError:
|
| 2018 |
+
sys.exit(0)
|
| 2019 |
+
{after}
|
| 2020 |
+
x = np.ones(2, dtype=np.float32)
|
| 2021 |
+
sys.exit(0 if np.allclose(x.dot(x), 2.0) else 1)
|
| 2022 |
+
""")
|
| 2023 |
+
|
| 2024 |
+
for bad_lib in bad_libs:
|
| 2025 |
+
code = template.format(before="import numpy as np", after="",
|
| 2026 |
+
bad_lib=bad_lib)
|
| 2027 |
+
subprocess.check_call([sys.executable, "-c", code])
|
| 2028 |
+
|
| 2029 |
+
# Swapped import order
|
| 2030 |
+
code = template.format(after="import numpy as np", before="",
|
| 2031 |
+
bad_lib=bad_lib)
|
| 2032 |
+
subprocess.check_call([sys.executable, "-c", code])
|
| 2033 |
+
|
| 2034 |
+
|
| 2035 |
+
class TestMultiDot:
|
| 2036 |
+
|
| 2037 |
+
def test_basic_function_with_three_arguments(self):
|
| 2038 |
+
# multi_dot with three arguments uses a fast hand coded algorithm to
|
| 2039 |
+
# determine the optimal order. Therefore test it separately.
|
| 2040 |
+
A = np.random.random((6, 2))
|
| 2041 |
+
B = np.random.random((2, 6))
|
| 2042 |
+
C = np.random.random((6, 2))
|
| 2043 |
+
|
| 2044 |
+
assert_almost_equal(multi_dot([A, B, C]), A.dot(B).dot(C))
|
| 2045 |
+
assert_almost_equal(multi_dot([A, B, C]), np.dot(A, np.dot(B, C)))
|
| 2046 |
+
|
| 2047 |
+
def test_basic_function_with_two_arguments(self):
|
| 2048 |
+
# separate code path with two arguments
|
| 2049 |
+
A = np.random.random((6, 2))
|
| 2050 |
+
B = np.random.random((2, 6))
|
| 2051 |
+
|
| 2052 |
+
assert_almost_equal(multi_dot([A, B]), A.dot(B))
|
| 2053 |
+
assert_almost_equal(multi_dot([A, B]), np.dot(A, B))
|
| 2054 |
+
|
| 2055 |
+
def test_basic_function_with_dynamic_programming_optimization(self):
|
| 2056 |
+
# multi_dot with four or more arguments uses the dynamic programming
|
| 2057 |
+
# optimization and therefore deserve a separate
|
| 2058 |
+
A = np.random.random((6, 2))
|
| 2059 |
+
B = np.random.random((2, 6))
|
| 2060 |
+
C = np.random.random((6, 2))
|
| 2061 |
+
D = np.random.random((2, 1))
|
| 2062 |
+
assert_almost_equal(multi_dot([A, B, C, D]), A.dot(B).dot(C).dot(D))
|
| 2063 |
+
|
| 2064 |
+
def test_vector_as_first_argument(self):
|
| 2065 |
+
# The first argument can be 1-D
|
| 2066 |
+
A1d = np.random.random(2) # 1-D
|
| 2067 |
+
B = np.random.random((2, 6))
|
| 2068 |
+
C = np.random.random((6, 2))
|
| 2069 |
+
D = np.random.random((2, 2))
|
| 2070 |
+
|
| 2071 |
+
# the result should be 1-D
|
| 2072 |
+
assert_equal(multi_dot([A1d, B, C, D]).shape, (2,))
|
| 2073 |
+
|
| 2074 |
+
def test_vector_as_last_argument(self):
|
| 2075 |
+
# The last argument can be 1-D
|
| 2076 |
+
A = np.random.random((6, 2))
|
| 2077 |
+
B = np.random.random((2, 6))
|
| 2078 |
+
C = np.random.random((6, 2))
|
| 2079 |
+
D1d = np.random.random(2) # 1-D
|
| 2080 |
+
|
| 2081 |
+
# the result should be 1-D
|
| 2082 |
+
assert_equal(multi_dot([A, B, C, D1d]).shape, (6,))
|
| 2083 |
+
|
| 2084 |
+
def test_vector_as_first_and_last_argument(self):
|
| 2085 |
+
# The first and last arguments can be 1-D
|
| 2086 |
+
A1d = np.random.random(2) # 1-D
|
| 2087 |
+
B = np.random.random((2, 6))
|
| 2088 |
+
C = np.random.random((6, 2))
|
| 2089 |
+
D1d = np.random.random(2) # 1-D
|
| 2090 |
+
|
| 2091 |
+
# the result should be a scalar
|
| 2092 |
+
assert_equal(multi_dot([A1d, B, C, D1d]).shape, ())
|
| 2093 |
+
|
| 2094 |
+
def test_three_arguments_and_out(self):
|
| 2095 |
+
# multi_dot with three arguments uses a fast hand coded algorithm to
|
| 2096 |
+
# determine the optimal order. Therefore test it separately.
|
| 2097 |
+
A = np.random.random((6, 2))
|
| 2098 |
+
B = np.random.random((2, 6))
|
| 2099 |
+
C = np.random.random((6, 2))
|
| 2100 |
+
|
| 2101 |
+
out = np.zeros((6, 2))
|
| 2102 |
+
ret = multi_dot([A, B, C], out=out)
|
| 2103 |
+
assert out is ret
|
| 2104 |
+
assert_almost_equal(out, A.dot(B).dot(C))
|
| 2105 |
+
assert_almost_equal(out, np.dot(A, np.dot(B, C)))
|
| 2106 |
+
|
| 2107 |
+
def test_two_arguments_and_out(self):
|
| 2108 |
+
# separate code path with two arguments
|
| 2109 |
+
A = np.random.random((6, 2))
|
| 2110 |
+
B = np.random.random((2, 6))
|
| 2111 |
+
out = np.zeros((6, 6))
|
| 2112 |
+
ret = multi_dot([A, B], out=out)
|
| 2113 |
+
assert out is ret
|
| 2114 |
+
assert_almost_equal(out, A.dot(B))
|
| 2115 |
+
assert_almost_equal(out, np.dot(A, B))
|
| 2116 |
+
|
| 2117 |
+
def test_dynamic_programming_optimization_and_out(self):
|
| 2118 |
+
# multi_dot with four or more arguments uses the dynamic programming
|
| 2119 |
+
# optimization and therefore deserve a separate test
|
| 2120 |
+
A = np.random.random((6, 2))
|
| 2121 |
+
B = np.random.random((2, 6))
|
| 2122 |
+
C = np.random.random((6, 2))
|
| 2123 |
+
D = np.random.random((2, 1))
|
| 2124 |
+
out = np.zeros((6, 1))
|
| 2125 |
+
ret = multi_dot([A, B, C, D], out=out)
|
| 2126 |
+
assert out is ret
|
| 2127 |
+
assert_almost_equal(out, A.dot(B).dot(C).dot(D))
|
| 2128 |
+
|
| 2129 |
+
def test_dynamic_programming_logic(self):
|
| 2130 |
+
# Test for the dynamic programming part
|
| 2131 |
+
# This test is directly taken from Cormen page 376.
|
| 2132 |
+
arrays = [np.random.random((30, 35)),
|
| 2133 |
+
np.random.random((35, 15)),
|
| 2134 |
+
np.random.random((15, 5)),
|
| 2135 |
+
np.random.random((5, 10)),
|
| 2136 |
+
np.random.random((10, 20)),
|
| 2137 |
+
np.random.random((20, 25))]
|
| 2138 |
+
m_expected = np.array([[0., 15750., 7875., 9375., 11875., 15125.],
|
| 2139 |
+
[0., 0., 2625., 4375., 7125., 10500.],
|
| 2140 |
+
[0., 0., 0., 750., 2500., 5375.],
|
| 2141 |
+
[0., 0., 0., 0., 1000., 3500.],
|
| 2142 |
+
[0., 0., 0., 0., 0., 5000.],
|
| 2143 |
+
[0., 0., 0., 0., 0., 0.]])
|
| 2144 |
+
s_expected = np.array([[0, 1, 1, 3, 3, 3],
|
| 2145 |
+
[0, 0, 2, 3, 3, 3],
|
| 2146 |
+
[0, 0, 0, 3, 3, 3],
|
| 2147 |
+
[0, 0, 0, 0, 4, 5],
|
| 2148 |
+
[0, 0, 0, 0, 0, 5],
|
| 2149 |
+
[0, 0, 0, 0, 0, 0]], dtype=int)
|
| 2150 |
+
s_expected -= 1 # Cormen uses 1-based index, python does not.
|
| 2151 |
+
|
| 2152 |
+
s, m = _multi_dot_matrix_chain_order(arrays, return_costs=True)
|
| 2153 |
+
|
| 2154 |
+
# Only the upper triangular part (without the diagonal) is interesting.
|
| 2155 |
+
assert_almost_equal(np.triu(s[:-1, 1:]),
|
| 2156 |
+
np.triu(s_expected[:-1, 1:]))
|
| 2157 |
+
assert_almost_equal(np.triu(m), np.triu(m_expected))
|
| 2158 |
+
|
| 2159 |
+
def test_too_few_input_arrays(self):
|
| 2160 |
+
assert_raises(ValueError, multi_dot, [])
|
| 2161 |
+
assert_raises(ValueError, multi_dot, [np.random.random((3, 3))])
|
| 2162 |
+
|
| 2163 |
+
|
| 2164 |
+
class TestTensorinv:
|
| 2165 |
+
|
| 2166 |
+
@pytest.mark.parametrize("arr, ind", [
|
| 2167 |
+
(np.ones((4, 6, 8, 2)), 2),
|
| 2168 |
+
(np.ones((3, 3, 2)), 1),
|
| 2169 |
+
])
|
| 2170 |
+
def test_non_square_handling(self, arr, ind):
|
| 2171 |
+
with assert_raises(LinAlgError):
|
| 2172 |
+
linalg.tensorinv(arr, ind=ind)
|
| 2173 |
+
|
| 2174 |
+
@pytest.mark.parametrize("shape, ind", [
|
| 2175 |
+
# examples from docstring
|
| 2176 |
+
((4, 6, 8, 3), 2),
|
| 2177 |
+
((24, 8, 3), 1),
|
| 2178 |
+
])
|
| 2179 |
+
def test_tensorinv_shape(self, shape, ind):
|
| 2180 |
+
a = np.eye(24)
|
| 2181 |
+
a.shape = shape
|
| 2182 |
+
ainv = linalg.tensorinv(a=a, ind=ind)
|
| 2183 |
+
expected = a.shape[ind:] + a.shape[:ind]
|
| 2184 |
+
actual = ainv.shape
|
| 2185 |
+
assert_equal(actual, expected)
|
| 2186 |
+
|
| 2187 |
+
@pytest.mark.parametrize("ind", [
|
| 2188 |
+
0, -2,
|
| 2189 |
+
])
|
| 2190 |
+
def test_tensorinv_ind_limit(self, ind):
|
| 2191 |
+
a = np.eye(24)
|
| 2192 |
+
a.shape = (4, 6, 8, 3)
|
| 2193 |
+
with assert_raises(ValueError):
|
| 2194 |
+
linalg.tensorinv(a=a, ind=ind)
|
| 2195 |
+
|
| 2196 |
+
def test_tensorinv_result(self):
|
| 2197 |
+
# mimic a docstring example
|
| 2198 |
+
a = np.eye(24)
|
| 2199 |
+
a.shape = (24, 8, 3)
|
| 2200 |
+
ainv = linalg.tensorinv(a, ind=1)
|
| 2201 |
+
b = np.ones(24)
|
| 2202 |
+
assert_allclose(np.tensordot(ainv, b, 1), np.linalg.tensorsolve(a, b))
|
| 2203 |
+
|
| 2204 |
+
|
| 2205 |
+
class TestTensorsolve:
|
| 2206 |
+
|
| 2207 |
+
@pytest.mark.parametrize("a, axes", [
|
| 2208 |
+
(np.ones((4, 6, 8, 2)), None),
|
| 2209 |
+
(np.ones((3, 3, 2)), (0, 2)),
|
| 2210 |
+
])
|
| 2211 |
+
def test_non_square_handling(self, a, axes):
|
| 2212 |
+
with assert_raises(LinAlgError):
|
| 2213 |
+
b = np.ones(a.shape[:2])
|
| 2214 |
+
linalg.tensorsolve(a, b, axes=axes)
|
| 2215 |
+
|
| 2216 |
+
@pytest.mark.parametrize("shape",
|
| 2217 |
+
[(2, 3, 6), (3, 4, 4, 3), (0, 3, 3, 0)],
|
| 2218 |
+
)
|
| 2219 |
+
def test_tensorsolve_result(self, shape):
|
| 2220 |
+
a = np.random.randn(*shape)
|
| 2221 |
+
b = np.ones(a.shape[:2])
|
| 2222 |
+
x = np.linalg.tensorsolve(a, b)
|
| 2223 |
+
assert_allclose(np.tensordot(a, x, axes=len(x.shape)), b)
|
| 2224 |
+
|
| 2225 |
+
|
| 2226 |
+
def test_unsupported_commontype():
|
| 2227 |
+
# linalg gracefully handles unsupported type
|
| 2228 |
+
arr = np.array([[1, -2], [2, 5]], dtype='float16')
|
| 2229 |
+
with assert_raises_regex(TypeError, "unsupported in linalg"):
|
| 2230 |
+
linalg.cholesky(arr)
|
| 2231 |
+
|
| 2232 |
+
|
| 2233 |
+
#@pytest.mark.slow
|
| 2234 |
+
#@pytest.mark.xfail(not HAS_LAPACK64, run=False,
|
| 2235 |
+
# reason="Numpy not compiled with 64-bit BLAS/LAPACK")
|
| 2236 |
+
#@requires_memory(free_bytes=16e9)
|
| 2237 |
+
@pytest.mark.skip(reason="Bad memory reports lead to OOM in ci testing")
|
| 2238 |
+
def test_blas64_dot():
|
| 2239 |
+
n = 2**32
|
| 2240 |
+
a = np.zeros([1, n], dtype=np.float32)
|
| 2241 |
+
b = np.ones([1, 1], dtype=np.float32)
|
| 2242 |
+
a[0,-1] = 1
|
| 2243 |
+
c = np.dot(b, a)
|
| 2244 |
+
assert_equal(c[0,-1], 1)
|
| 2245 |
+
|
| 2246 |
+
|
| 2247 |
+
@pytest.mark.xfail(not HAS_LAPACK64,
|
| 2248 |
+
reason="Numpy not compiled with 64-bit BLAS/LAPACK")
|
| 2249 |
+
def test_blas64_geqrf_lwork_smoketest():
|
| 2250 |
+
# Smoke test LAPACK geqrf lwork call with 64-bit integers
|
| 2251 |
+
dtype = np.float64
|
| 2252 |
+
lapack_routine = np.linalg.lapack_lite.dgeqrf
|
| 2253 |
+
|
| 2254 |
+
m = 2**32 + 1
|
| 2255 |
+
n = 2**32 + 1
|
| 2256 |
+
lda = m
|
| 2257 |
+
|
| 2258 |
+
# Dummy arrays, not referenced by the lapack routine, so don't
|
| 2259 |
+
# need to be of the right size
|
| 2260 |
+
a = np.zeros([1, 1], dtype=dtype)
|
| 2261 |
+
work = np.zeros([1], dtype=dtype)
|
| 2262 |
+
tau = np.zeros([1], dtype=dtype)
|
| 2263 |
+
|
| 2264 |
+
# Size query
|
| 2265 |
+
results = lapack_routine(m, n, a, lda, tau, work, -1, 0)
|
| 2266 |
+
assert_equal(results['info'], 0)
|
| 2267 |
+
assert_equal(results['m'], m)
|
| 2268 |
+
assert_equal(results['n'], m)
|
| 2269 |
+
|
| 2270 |
+
# Should result to an integer of a reasonable size
|
| 2271 |
+
lwork = int(work.item())
|
| 2272 |
+
assert_(2**32 < lwork < 2**42)
|
| 2273 |
+
|
| 2274 |
+
|
| 2275 |
+
def test_diagonal():
|
| 2276 |
+
# Here we only test if selected axes are compatible
|
| 2277 |
+
# with Array API (last two). Core implementation
|
| 2278 |
+
# of `diagonal` is tested in `test_multiarray.py`.
|
| 2279 |
+
x = np.arange(60).reshape((3, 4, 5))
|
| 2280 |
+
actual = np.linalg.diagonal(x)
|
| 2281 |
+
expected = np.array(
|
| 2282 |
+
[
|
| 2283 |
+
[0, 6, 12, 18],
|
| 2284 |
+
[20, 26, 32, 38],
|
| 2285 |
+
[40, 46, 52, 58],
|
| 2286 |
+
]
|
| 2287 |
+
)
|
| 2288 |
+
assert_equal(actual, expected)
|
| 2289 |
+
|
| 2290 |
+
|
| 2291 |
+
def test_trace():
|
| 2292 |
+
# Here we only test if selected axes are compatible
|
| 2293 |
+
# with Array API (last two). Core implementation
|
| 2294 |
+
# of `trace` is tested in `test_multiarray.py`.
|
| 2295 |
+
x = np.arange(60).reshape((3, 4, 5))
|
| 2296 |
+
actual = np.linalg.trace(x)
|
| 2297 |
+
expected = np.array([36, 116, 196])
|
| 2298 |
+
|
| 2299 |
+
assert_equal(actual, expected)
|
| 2300 |
+
|
| 2301 |
+
|
| 2302 |
+
def test_cross():
|
| 2303 |
+
x = np.arange(9).reshape((3, 3))
|
| 2304 |
+
actual = np.linalg.cross(x, x + 1)
|
| 2305 |
+
expected = np.array([
|
| 2306 |
+
[-1, 2, -1],
|
| 2307 |
+
[-1, 2, -1],
|
| 2308 |
+
[-1, 2, -1],
|
| 2309 |
+
])
|
| 2310 |
+
|
| 2311 |
+
assert_equal(actual, expected)
|
| 2312 |
+
|
| 2313 |
+
# We test that lists are converted to arrays.
|
| 2314 |
+
u = [1, 2, 3]
|
| 2315 |
+
v = [4, 5, 6]
|
| 2316 |
+
actual = np.linalg.cross(u, v)
|
| 2317 |
+
expected = array([-3, 6, -3])
|
| 2318 |
+
|
| 2319 |
+
assert_equal(actual, expected)
|
| 2320 |
+
|
| 2321 |
+
with assert_raises_regex(
|
| 2322 |
+
ValueError,
|
| 2323 |
+
r"input arrays must be \(arrays of\) 3-dimensional vectors"
|
| 2324 |
+
):
|
| 2325 |
+
x_2dim = x[:, 1:]
|
| 2326 |
+
np.linalg.cross(x_2dim, x_2dim)
|
| 2327 |
+
|
| 2328 |
+
|
| 2329 |
+
def test_tensordot():
|
| 2330 |
+
# np.linalg.tensordot is just an alias for np.tensordot
|
| 2331 |
+
x = np.arange(6).reshape((2, 3))
|
| 2332 |
+
|
| 2333 |
+
assert np.linalg.tensordot(x, x) == 55
|
| 2334 |
+
assert np.linalg.tensordot(x, x, axes=[(0, 1), (0, 1)]) == 55
|
| 2335 |
+
|
| 2336 |
+
|
| 2337 |
+
def test_matmul():
|
| 2338 |
+
# np.linalg.matmul and np.matmul only differs in the number
|
| 2339 |
+
# of arguments in the signature
|
| 2340 |
+
x = np.arange(6).reshape((2, 3))
|
| 2341 |
+
actual = np.linalg.matmul(x, x.T)
|
| 2342 |
+
expected = np.array([[5, 14], [14, 50]])
|
| 2343 |
+
|
| 2344 |
+
assert_equal(actual, expected)
|
| 2345 |
+
|
| 2346 |
+
|
| 2347 |
+
def test_matrix_transpose():
|
| 2348 |
+
x = np.arange(6).reshape((2, 3))
|
| 2349 |
+
actual = np.linalg.matrix_transpose(x)
|
| 2350 |
+
expected = x.T
|
| 2351 |
+
|
| 2352 |
+
assert_equal(actual, expected)
|
| 2353 |
+
|
| 2354 |
+
with assert_raises_regex(
|
| 2355 |
+
ValueError, "array must be at least 2-dimensional"
|
| 2356 |
+
):
|
| 2357 |
+
np.linalg.matrix_transpose(x[:, 0])
|
| 2358 |
+
|
| 2359 |
+
|
| 2360 |
+
def test_matrix_norm():
|
| 2361 |
+
x = np.arange(9).reshape((3, 3))
|
| 2362 |
+
actual = np.linalg.matrix_norm(x)
|
| 2363 |
+
|
| 2364 |
+
assert_almost_equal(actual, np.float64(14.2828), double_decimal=3)
|
| 2365 |
+
|
| 2366 |
+
actual = np.linalg.matrix_norm(x, keepdims=True)
|
| 2367 |
+
|
| 2368 |
+
assert_almost_equal(actual, np.array([[14.2828]]), double_decimal=3)
|
| 2369 |
+
|
| 2370 |
+
|
| 2371 |
+
def test_vector_norm():
|
| 2372 |
+
x = np.arange(9).reshape((3, 3))
|
| 2373 |
+
actual = np.linalg.vector_norm(x)
|
| 2374 |
+
|
| 2375 |
+
assert_almost_equal(actual, np.float64(14.2828), double_decimal=3)
|
| 2376 |
+
|
| 2377 |
+
actual = np.linalg.vector_norm(x, axis=0)
|
| 2378 |
+
|
| 2379 |
+
assert_almost_equal(
|
| 2380 |
+
actual, np.array([6.7082, 8.124, 9.6436]), double_decimal=3
|
| 2381 |
+
)
|
| 2382 |
+
|
| 2383 |
+
actual = np.linalg.vector_norm(x, keepdims=True)
|
| 2384 |
+
expected = np.full((1, 1), 14.2828, dtype='float64')
|
| 2385 |
+
assert_equal(actual.shape, expected.shape)
|
| 2386 |
+
assert_almost_equal(actual, expected, double_decimal=3)
|