Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- ckpts/universal/global_step40/zero/15.attention.dense.weight/fp32.pt +3 -0
- ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/fp32.pt +3 -0
- ckpts/universal/global_step40/zero/23.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step40/zero/26.attention.dense.weight/exp_avg_sq.pt +3 -0
- ckpts/universal/global_step40/zero/26.attention.dense.weight/fp32.pt +3 -0
- ckpts/universal/global_step40/zero/26.attention.query_key_value.weight/exp_avg.pt +3 -0
- ckpts/universal/global_step40/zero/26.attention.query_key_value.weight/fp32.pt +3 -0
- venv/lib/python3.10/site-packages/scipy/fft/__init__.py +111 -0
- venv/lib/python3.10/site-packages/scipy/fft/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_backend.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_debug_backends.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_helper.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/_backend.py +196 -0
- venv/lib/python3.10/site-packages/scipy/fft/_basic.py +1630 -0
- venv/lib/python3.10/site-packages/scipy/fft/_basic_backend.py +176 -0
- venv/lib/python3.10/site-packages/scipy/fft/_debug_backends.py +22 -0
- venv/lib/python3.10/site-packages/scipy/fft/_fftlog.py +223 -0
- venv/lib/python3.10/site-packages/scipy/fft/_fftlog_backend.py +197 -0
- venv/lib/python3.10/site-packages/scipy/fft/_helper.py +313 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md +25 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py +9 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py +251 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py +221 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py +109 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__pycache__/test_basic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__pycache__/test_real_transforms.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py +1005 -0
- venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py +494 -0
- venv/lib/python3.10/site-packages/scipy/fft/_realtransforms.py +693 -0
- venv/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py +63 -0
- venv/lib/python3.10/site-packages/scipy/fft/tests/__init__.py +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/mock_backend.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_backend.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_basic.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_fftlog.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_multithreading.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_real_transforms.cpython-310.pyc +0 -0
- venv/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py +92 -0
ckpts/universal/global_step40/zero/15.attention.dense.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:38dff829c2020c3e39d7ad2bde4962c23ecac7722359bffc74bbb7c0440f0e03
|
3 |
+
size 16778317
|
ckpts/universal/global_step40/zero/15.post_attention_layernorm.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:aa18500e1a868374d4589a520c6866e200434fb5ba2ce6d22dfe29059ec0a734
|
3 |
+
size 9293
|
ckpts/universal/global_step40/zero/23.mlp.dense_h_to_4h_swiglu.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:b45220ac44735a023fe49d4f5c55544da02a11b0a036d77f28001c1494beb604
|
3 |
+
size 33555627
|
ckpts/universal/global_step40/zero/26.attention.dense.weight/exp_avg_sq.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:07974e68e74e5b4a0765c2cd3e34a0afa25d2ca6d1300111796fb0180f5fb441
|
3 |
+
size 16778411
|
ckpts/universal/global_step40/zero/26.attention.dense.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:e86bc6874312288703ca761702337f1044fdccfd6897ece2957914192e9d066b
|
3 |
+
size 16778317
|
ckpts/universal/global_step40/zero/26.attention.query_key_value.weight/exp_avg.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0914774ec02ad1de3d4ed79fd71a5ed2f2a8de00080c8a34ac9ee915a525c8fe
|
3 |
+
size 50332828
|
ckpts/universal/global_step40/zero/26.attention.query_key_value.weight/fp32.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:2678b103056818002b5276ddec83da875b705035299503ffe28a708027fd8c30
|
3 |
+
size 50332749
|
venv/lib/python3.10/site-packages/scipy/fft/__init__.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
==============================================
|
3 |
+
Discrete Fourier transforms (:mod:`scipy.fft`)
|
4 |
+
==============================================
|
5 |
+
|
6 |
+
.. currentmodule:: scipy.fft
|
7 |
+
|
8 |
+
Fast Fourier Transforms (FFTs)
|
9 |
+
==============================
|
10 |
+
|
11 |
+
.. autosummary::
|
12 |
+
:toctree: generated/
|
13 |
+
|
14 |
+
fft - Fast (discrete) Fourier Transform (FFT)
|
15 |
+
ifft - Inverse FFT
|
16 |
+
fft2 - 2-D FFT
|
17 |
+
ifft2 - 2-D inverse FFT
|
18 |
+
fftn - N-D FFT
|
19 |
+
ifftn - N-D inverse FFT
|
20 |
+
rfft - FFT of strictly real-valued sequence
|
21 |
+
irfft - Inverse of rfft
|
22 |
+
rfft2 - 2-D FFT of real sequence
|
23 |
+
irfft2 - Inverse of rfft2
|
24 |
+
rfftn - N-D FFT of real sequence
|
25 |
+
irfftn - Inverse of rfftn
|
26 |
+
hfft - FFT of a Hermitian sequence (real spectrum)
|
27 |
+
ihfft - Inverse of hfft
|
28 |
+
hfft2 - 2-D FFT of a Hermitian sequence
|
29 |
+
ihfft2 - Inverse of hfft2
|
30 |
+
hfftn - N-D FFT of a Hermitian sequence
|
31 |
+
ihfftn - Inverse of hfftn
|
32 |
+
|
33 |
+
Discrete Sin and Cosine Transforms (DST and DCT)
|
34 |
+
================================================
|
35 |
+
|
36 |
+
.. autosummary::
|
37 |
+
:toctree: generated/
|
38 |
+
|
39 |
+
dct - Discrete cosine transform
|
40 |
+
idct - Inverse discrete cosine transform
|
41 |
+
dctn - N-D Discrete cosine transform
|
42 |
+
idctn - N-D Inverse discrete cosine transform
|
43 |
+
dst - Discrete sine transform
|
44 |
+
idst - Inverse discrete sine transform
|
45 |
+
dstn - N-D Discrete sine transform
|
46 |
+
idstn - N-D Inverse discrete sine transform
|
47 |
+
|
48 |
+
Fast Hankel Transforms
|
49 |
+
======================
|
50 |
+
|
51 |
+
.. autosummary::
|
52 |
+
:toctree: generated/
|
53 |
+
|
54 |
+
fht - Fast Hankel transform
|
55 |
+
ifht - Inverse of fht
|
56 |
+
|
57 |
+
Helper functions
|
58 |
+
================
|
59 |
+
|
60 |
+
.. autosummary::
|
61 |
+
:toctree: generated/
|
62 |
+
|
63 |
+
fftshift - Shift the zero-frequency component to the center of the spectrum
|
64 |
+
ifftshift - The inverse of `fftshift`
|
65 |
+
fftfreq - Return the Discrete Fourier Transform sample frequencies
|
66 |
+
rfftfreq - DFT sample frequencies (for usage with rfft, irfft)
|
67 |
+
fhtoffset - Compute an optimal offset for the Fast Hankel Transform
|
68 |
+
next_fast_len - Find the optimal length to zero-pad an FFT for speed
|
69 |
+
set_workers - Context manager to set default number of workers
|
70 |
+
get_workers - Get the current default number of workers
|
71 |
+
|
72 |
+
Backend control
|
73 |
+
===============
|
74 |
+
|
75 |
+
.. autosummary::
|
76 |
+
:toctree: generated/
|
77 |
+
|
78 |
+
set_backend - Context manager to set the backend within a fixed scope
|
79 |
+
skip_backend - Context manager to skip a backend within a fixed scope
|
80 |
+
set_global_backend - Sets the global fft backend
|
81 |
+
register_backend - Register a backend for permanent use
|
82 |
+
|
83 |
+
"""
|
84 |
+
|
85 |
+
from ._basic import (
|
86 |
+
fft, ifft, fft2, ifft2, fftn, ifftn,
|
87 |
+
rfft, irfft, rfft2, irfft2, rfftn, irfftn,
|
88 |
+
hfft, ihfft, hfft2, ihfft2, hfftn, ihfftn)
|
89 |
+
from ._realtransforms import dct, idct, dst, idst, dctn, idctn, dstn, idstn
|
90 |
+
from ._fftlog import fht, ifht, fhtoffset
|
91 |
+
from ._helper import next_fast_len, fftfreq, rfftfreq, fftshift, ifftshift
|
92 |
+
from ._backend import (set_backend, skip_backend, set_global_backend,
|
93 |
+
register_backend)
|
94 |
+
from ._pocketfft.helper import set_workers, get_workers
|
95 |
+
|
96 |
+
__all__ = [
|
97 |
+
'fft', 'ifft', 'fft2', 'ifft2', 'fftn', 'ifftn',
|
98 |
+
'rfft', 'irfft', 'rfft2', 'irfft2', 'rfftn', 'irfftn',
|
99 |
+
'hfft', 'ihfft', 'hfft2', 'ihfft2', 'hfftn', 'ihfftn',
|
100 |
+
'fftfreq', 'rfftfreq', 'fftshift', 'ifftshift',
|
101 |
+
'next_fast_len',
|
102 |
+
'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn',
|
103 |
+
'fht', 'ifht',
|
104 |
+
'fhtoffset',
|
105 |
+
'set_backend', 'skip_backend', 'set_global_backend', 'register_backend',
|
106 |
+
'get_workers', 'set_workers']
|
107 |
+
|
108 |
+
|
109 |
+
from scipy._lib._testutils import PytestTester
|
110 |
+
test = PytestTester(__name__)
|
111 |
+
del PytestTester
|
venv/lib/python3.10/site-packages/scipy/fft/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (3.77 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_backend.cpython-310.pyc
ADDED
Binary file (6.82 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic.cpython-310.pyc
ADDED
Binary file (62.5 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_basic_backend.cpython-310.pyc
ADDED
Binary file (4.29 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_debug_backends.cpython-310.pyc
ADDED
Binary file (1.06 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog.cpython-310.pyc
ADDED
Binary file (8.18 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_fftlog_backend.cpython-310.pyc
ADDED
Binary file (4.32 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_helper.cpython-310.pyc
ADDED
Binary file (9.72 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc
ADDED
Binary file (25.3 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/__pycache__/_realtransforms_backend.cpython-310.pyc
ADDED
Binary file (1.78 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/_backend.py
ADDED
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import scipy._lib.uarray as ua
|
2 |
+
from . import _basic_backend
|
3 |
+
from . import _realtransforms_backend
|
4 |
+
from . import _fftlog_backend
|
5 |
+
|
6 |
+
|
7 |
+
class _ScipyBackend:
|
8 |
+
"""The default backend for fft calculations
|
9 |
+
|
10 |
+
Notes
|
11 |
+
-----
|
12 |
+
We use the domain ``numpy.scipy`` rather than ``scipy`` because ``uarray``
|
13 |
+
treats the domain as a hierarchy. This means the user can install a single
|
14 |
+
backend for ``numpy`` and have it implement ``numpy.scipy.fft`` as well.
|
15 |
+
"""
|
16 |
+
__ua_domain__ = "numpy.scipy.fft"
|
17 |
+
|
18 |
+
@staticmethod
|
19 |
+
def __ua_function__(method, args, kwargs):
|
20 |
+
|
21 |
+
fn = getattr(_basic_backend, method.__name__, None)
|
22 |
+
if fn is None:
|
23 |
+
fn = getattr(_realtransforms_backend, method.__name__, None)
|
24 |
+
if fn is None:
|
25 |
+
fn = getattr(_fftlog_backend, method.__name__, None)
|
26 |
+
if fn is None:
|
27 |
+
return NotImplemented
|
28 |
+
return fn(*args, **kwargs)
|
29 |
+
|
30 |
+
|
31 |
+
_named_backends = {
|
32 |
+
'scipy': _ScipyBackend,
|
33 |
+
}
|
34 |
+
|
35 |
+
|
36 |
+
def _backend_from_arg(backend):
|
37 |
+
"""Maps strings to known backends and validates the backend"""
|
38 |
+
|
39 |
+
if isinstance(backend, str):
|
40 |
+
try:
|
41 |
+
backend = _named_backends[backend]
|
42 |
+
except KeyError as e:
|
43 |
+
raise ValueError(f'Unknown backend {backend}') from e
|
44 |
+
|
45 |
+
if backend.__ua_domain__ != 'numpy.scipy.fft':
|
46 |
+
raise ValueError('Backend does not implement "numpy.scipy.fft"')
|
47 |
+
|
48 |
+
return backend
|
49 |
+
|
50 |
+
|
51 |
+
def set_global_backend(backend, coerce=False, only=False, try_last=False):
|
52 |
+
"""Sets the global fft backend
|
53 |
+
|
54 |
+
This utility method replaces the default backend for permanent use. It
|
55 |
+
will be tried in the list of backends automatically, unless the
|
56 |
+
``only`` flag is set on a backend. This will be the first tried
|
57 |
+
backend outside the :obj:`set_backend` context manager.
|
58 |
+
|
59 |
+
Parameters
|
60 |
+
----------
|
61 |
+
backend : {object, 'scipy'}
|
62 |
+
The backend to use.
|
63 |
+
Can either be a ``str`` containing the name of a known backend
|
64 |
+
{'scipy'} or an object that implements the uarray protocol.
|
65 |
+
coerce : bool
|
66 |
+
Whether to coerce input types when trying this backend.
|
67 |
+
only : bool
|
68 |
+
If ``True``, no more backends will be tried if this fails.
|
69 |
+
Implied by ``coerce=True``.
|
70 |
+
try_last : bool
|
71 |
+
If ``True``, the global backend is tried after registered backends.
|
72 |
+
|
73 |
+
Raises
|
74 |
+
------
|
75 |
+
ValueError: If the backend does not implement ``numpy.scipy.fft``.
|
76 |
+
|
77 |
+
Notes
|
78 |
+
-----
|
79 |
+
This will overwrite the previously set global backend, which, by default, is
|
80 |
+
the SciPy implementation.
|
81 |
+
|
82 |
+
Examples
|
83 |
+
--------
|
84 |
+
We can set the global fft backend:
|
85 |
+
|
86 |
+
>>> from scipy.fft import fft, set_global_backend
|
87 |
+
>>> set_global_backend("scipy") # Sets global backend (default is "scipy").
|
88 |
+
>>> fft([1]) # Calls the global backend
|
89 |
+
array([1.+0.j])
|
90 |
+
"""
|
91 |
+
backend = _backend_from_arg(backend)
|
92 |
+
ua.set_global_backend(backend, coerce=coerce, only=only, try_last=try_last)
|
93 |
+
|
94 |
+
|
95 |
+
def register_backend(backend):
|
96 |
+
"""
|
97 |
+
Register a backend for permanent use.
|
98 |
+
|
99 |
+
Registered backends have the lowest priority and will be tried after the
|
100 |
+
global backend.
|
101 |
+
|
102 |
+
Parameters
|
103 |
+
----------
|
104 |
+
backend : {object, 'scipy'}
|
105 |
+
The backend to use.
|
106 |
+
Can either be a ``str`` containing the name of a known backend
|
107 |
+
{'scipy'} or an object that implements the uarray protocol.
|
108 |
+
|
109 |
+
Raises
|
110 |
+
------
|
111 |
+
ValueError: If the backend does not implement ``numpy.scipy.fft``.
|
112 |
+
|
113 |
+
Examples
|
114 |
+
--------
|
115 |
+
We can register a new fft backend:
|
116 |
+
|
117 |
+
>>> from scipy.fft import fft, register_backend, set_global_backend
|
118 |
+
>>> class NoopBackend: # Define an invalid Backend
|
119 |
+
... __ua_domain__ = "numpy.scipy.fft"
|
120 |
+
... def __ua_function__(self, func, args, kwargs):
|
121 |
+
... return NotImplemented
|
122 |
+
>>> set_global_backend(NoopBackend()) # Set the invalid backend as global
|
123 |
+
>>> register_backend("scipy") # Register a new backend
|
124 |
+
# The registered backend is called because
|
125 |
+
# the global backend returns `NotImplemented`
|
126 |
+
>>> fft([1])
|
127 |
+
array([1.+0.j])
|
128 |
+
>>> set_global_backend("scipy") # Restore global backend to default
|
129 |
+
|
130 |
+
"""
|
131 |
+
backend = _backend_from_arg(backend)
|
132 |
+
ua.register_backend(backend)
|
133 |
+
|
134 |
+
|
135 |
+
def set_backend(backend, coerce=False, only=False):
|
136 |
+
"""Context manager to set the backend within a fixed scope.
|
137 |
+
|
138 |
+
Upon entering the ``with`` statement, the given backend will be added to
|
139 |
+
the list of available backends with the highest priority. Upon exit, the
|
140 |
+
backend is reset to the state before entering the scope.
|
141 |
+
|
142 |
+
Parameters
|
143 |
+
----------
|
144 |
+
backend : {object, 'scipy'}
|
145 |
+
The backend to use.
|
146 |
+
Can either be a ``str`` containing the name of a known backend
|
147 |
+
{'scipy'} or an object that implements the uarray protocol.
|
148 |
+
coerce : bool, optional
|
149 |
+
Whether to allow expensive conversions for the ``x`` parameter. e.g.,
|
150 |
+
copying a NumPy array to the GPU for a CuPy backend. Implies ``only``.
|
151 |
+
only : bool, optional
|
152 |
+
If only is ``True`` and this backend returns ``NotImplemented``, then a
|
153 |
+
BackendNotImplemented error will be raised immediately. Ignoring any
|
154 |
+
lower priority backends.
|
155 |
+
|
156 |
+
Examples
|
157 |
+
--------
|
158 |
+
>>> import scipy.fft as fft
|
159 |
+
>>> with fft.set_backend('scipy', only=True):
|
160 |
+
... fft.fft([1]) # Always calls the scipy implementation
|
161 |
+
array([1.+0.j])
|
162 |
+
"""
|
163 |
+
backend = _backend_from_arg(backend)
|
164 |
+
return ua.set_backend(backend, coerce=coerce, only=only)
|
165 |
+
|
166 |
+
|
167 |
+
def skip_backend(backend):
|
168 |
+
"""Context manager to skip a backend within a fixed scope.
|
169 |
+
|
170 |
+
Within the context of a ``with`` statement, the given backend will not be
|
171 |
+
called. This covers backends registered both locally and globally. Upon
|
172 |
+
exit, the backend will again be considered.
|
173 |
+
|
174 |
+
Parameters
|
175 |
+
----------
|
176 |
+
backend : {object, 'scipy'}
|
177 |
+
The backend to skip.
|
178 |
+
Can either be a ``str`` containing the name of a known backend
|
179 |
+
{'scipy'} or an object that implements the uarray protocol.
|
180 |
+
|
181 |
+
Examples
|
182 |
+
--------
|
183 |
+
>>> import scipy.fft as fft
|
184 |
+
>>> fft.fft([1]) # Calls default SciPy backend
|
185 |
+
array([1.+0.j])
|
186 |
+
>>> with fft.skip_backend('scipy'): # We explicitly skip the SciPy backend
|
187 |
+
... fft.fft([1]) # leaving no implementation available
|
188 |
+
Traceback (most recent call last):
|
189 |
+
...
|
190 |
+
BackendNotImplementedError: No selected backends had an implementation ...
|
191 |
+
"""
|
192 |
+
backend = _backend_from_arg(backend)
|
193 |
+
return ua.skip_backend(backend)
|
194 |
+
|
195 |
+
|
196 |
+
set_global_backend('scipy', try_last=True)
|
venv/lib/python3.10/site-packages/scipy/fft/_basic.py
ADDED
@@ -0,0 +1,1630 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from scipy._lib.uarray import generate_multimethod, Dispatchable
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
|
5 |
+
def _x_replacer(args, kwargs, dispatchables):
|
6 |
+
"""
|
7 |
+
uarray argument replacer to replace the transform input array (``x``)
|
8 |
+
"""
|
9 |
+
if len(args) > 0:
|
10 |
+
return (dispatchables[0],) + args[1:], kwargs
|
11 |
+
kw = kwargs.copy()
|
12 |
+
kw['x'] = dispatchables[0]
|
13 |
+
return args, kw
|
14 |
+
|
15 |
+
|
16 |
+
def _dispatch(func):
|
17 |
+
"""
|
18 |
+
Function annotation that creates a uarray multimethod from the function
|
19 |
+
"""
|
20 |
+
return generate_multimethod(func, _x_replacer, domain="numpy.scipy.fft")
|
21 |
+
|
22 |
+
|
23 |
+
@_dispatch
|
24 |
+
def fft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
|
25 |
+
plan=None):
|
26 |
+
"""
|
27 |
+
Compute the 1-D discrete Fourier Transform.
|
28 |
+
|
29 |
+
This function computes the 1-D *n*-point discrete Fourier
|
30 |
+
Transform (DFT) with the efficient Fast Fourier Transform (FFT)
|
31 |
+
algorithm [1]_.
|
32 |
+
|
33 |
+
Parameters
|
34 |
+
----------
|
35 |
+
x : array_like
|
36 |
+
Input array, can be complex.
|
37 |
+
n : int, optional
|
38 |
+
Length of the transformed axis of the output.
|
39 |
+
If `n` is smaller than the length of the input, the input is cropped.
|
40 |
+
If it is larger, the input is padded with zeros. If `n` is not given,
|
41 |
+
the length of the input along the axis specified by `axis` is used.
|
42 |
+
axis : int, optional
|
43 |
+
Axis over which to compute the FFT. If not given, the last axis is
|
44 |
+
used.
|
45 |
+
norm : {"backward", "ortho", "forward"}, optional
|
46 |
+
Normalization mode. Default is "backward", meaning no normalization on
|
47 |
+
the forward transforms and scaling by ``1/n`` on the `ifft`.
|
48 |
+
"forward" instead applies the ``1/n`` factor on the forward transform.
|
49 |
+
For ``norm="ortho"``, both directions are scaled by ``1/sqrt(n)``.
|
50 |
+
|
51 |
+
.. versionadded:: 1.6.0
|
52 |
+
``norm={"forward", "backward"}`` options were added
|
53 |
+
|
54 |
+
overwrite_x : bool, optional
|
55 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
56 |
+
See the notes below for more details.
|
57 |
+
workers : int, optional
|
58 |
+
Maximum number of workers to use for parallel computation. If negative,
|
59 |
+
the value wraps around from ``os.cpu_count()``. See below for more
|
60 |
+
details.
|
61 |
+
plan : object, optional
|
62 |
+
This argument is reserved for passing in a precomputed plan provided
|
63 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
64 |
+
|
65 |
+
.. versionadded:: 1.5.0
|
66 |
+
|
67 |
+
Returns
|
68 |
+
-------
|
69 |
+
out : complex ndarray
|
70 |
+
The truncated or zero-padded input, transformed along the axis
|
71 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
72 |
+
|
73 |
+
Raises
|
74 |
+
------
|
75 |
+
IndexError
|
76 |
+
if `axes` is larger than the last axis of `x`.
|
77 |
+
|
78 |
+
See Also
|
79 |
+
--------
|
80 |
+
ifft : The inverse of `fft`.
|
81 |
+
fft2 : The 2-D FFT.
|
82 |
+
fftn : The N-D FFT.
|
83 |
+
rfftn : The N-D FFT of real input.
|
84 |
+
fftfreq : Frequency bins for given FFT parameters.
|
85 |
+
next_fast_len : Size to pad input to for most efficient transforms
|
86 |
+
|
87 |
+
Notes
|
88 |
+
-----
|
89 |
+
FFT (Fast Fourier Transform) refers to a way the discrete Fourier Transform
|
90 |
+
(DFT) can be calculated efficiently, by using symmetries in the calculated
|
91 |
+
terms. The symmetry is highest when `n` is a power of 2, and the transform
|
92 |
+
is therefore most efficient for these sizes. For poorly factorizable sizes,
|
93 |
+
`scipy.fft` uses Bluestein's algorithm [2]_ and so is never worse than
|
94 |
+
O(`n` log `n`). Further performance improvements may be seen by zero-padding
|
95 |
+
the input using `next_fast_len`.
|
96 |
+
|
97 |
+
If ``x`` is a 1d array, then the `fft` is equivalent to ::
|
98 |
+
|
99 |
+
y[k] = np.sum(x * np.exp(-2j * np.pi * k * np.arange(n)/n))
|
100 |
+
|
101 |
+
The frequency term ``f=k/n`` is found at ``y[k]``. At ``y[n/2]`` we reach
|
102 |
+
the Nyquist frequency and wrap around to the negative-frequency terms. So,
|
103 |
+
for an 8-point transform, the frequencies of the result are
|
104 |
+
[0, 1, 2, 3, -4, -3, -2, -1]. To rearrange the fft output so that the
|
105 |
+
zero-frequency component is centered, like [-4, -3, -2, -1, 0, 1, 2, 3],
|
106 |
+
use `fftshift`.
|
107 |
+
|
108 |
+
Transforms can be done in single, double, or extended precision (long
|
109 |
+
double) floating point. Half precision inputs will be converted to single
|
110 |
+
precision and non-floating-point inputs will be converted to double
|
111 |
+
precision.
|
112 |
+
|
113 |
+
If the data type of ``x`` is real, a "real FFT" algorithm is automatically
|
114 |
+
used, which roughly halves the computation time. To increase efficiency
|
115 |
+
a little further, use `rfft`, which does the same calculation, but only
|
116 |
+
outputs half of the symmetrical spectrum. If the data are both real and
|
117 |
+
symmetrical, the `dct` can again double the efficiency, by generating
|
118 |
+
half of the spectrum from half of the signal.
|
119 |
+
|
120 |
+
When ``overwrite_x=True`` is specified, the memory referenced by ``x`` may
|
121 |
+
be used by the implementation in any way. This may include reusing the
|
122 |
+
memory for the result, but this is in no way guaranteed. You should not
|
123 |
+
rely on the contents of ``x`` after the transform as this may change in
|
124 |
+
future without warning.
|
125 |
+
|
126 |
+
The ``workers`` argument specifies the maximum number of parallel jobs to
|
127 |
+
split the FFT computation into. This will execute independent 1-D
|
128 |
+
FFTs within ``x``. So, ``x`` must be at least 2-D and the
|
129 |
+
non-transformed axes must be large enough to split into chunks. If ``x`` is
|
130 |
+
too small, fewer jobs may be used than requested.
|
131 |
+
|
132 |
+
References
|
133 |
+
----------
|
134 |
+
.. [1] Cooley, James W., and John W. Tukey, 1965, "An algorithm for the
|
135 |
+
machine calculation of complex Fourier series," *Math. Comput.*
|
136 |
+
19: 297-301.
|
137 |
+
.. [2] Bluestein, L., 1970, "A linear filtering approach to the
|
138 |
+
computation of discrete Fourier transform". *IEEE Transactions on
|
139 |
+
Audio and Electroacoustics.* 18 (4): 451-455.
|
140 |
+
|
141 |
+
Examples
|
142 |
+
--------
|
143 |
+
>>> import scipy.fft
|
144 |
+
>>> import numpy as np
|
145 |
+
>>> scipy.fft.fft(np.exp(2j * np.pi * np.arange(8) / 8))
|
146 |
+
array([-2.33486982e-16+1.14423775e-17j, 8.00000000e+00-1.25557246e-15j,
|
147 |
+
2.33486982e-16+2.33486982e-16j, 0.00000000e+00+1.22464680e-16j,
|
148 |
+
-1.14423775e-17+2.33486982e-16j, 0.00000000e+00+5.20784380e-16j,
|
149 |
+
1.14423775e-17+1.14423775e-17j, 0.00000000e+00+1.22464680e-16j])
|
150 |
+
|
151 |
+
In this example, real input has an FFT which is Hermitian, i.e., symmetric
|
152 |
+
in the real part and anti-symmetric in the imaginary part:
|
153 |
+
|
154 |
+
>>> from scipy.fft import fft, fftfreq, fftshift
|
155 |
+
>>> import matplotlib.pyplot as plt
|
156 |
+
>>> t = np.arange(256)
|
157 |
+
>>> sp = fftshift(fft(np.sin(t)))
|
158 |
+
>>> freq = fftshift(fftfreq(t.shape[-1]))
|
159 |
+
>>> plt.plot(freq, sp.real, freq, sp.imag)
|
160 |
+
[<matplotlib.lines.Line2D object at 0x...>,
|
161 |
+
<matplotlib.lines.Line2D object at 0x...>]
|
162 |
+
>>> plt.show()
|
163 |
+
|
164 |
+
"""
|
165 |
+
return (Dispatchable(x, np.ndarray),)
|
166 |
+
|
167 |
+
|
168 |
+
@_dispatch
|
169 |
+
def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
|
170 |
+
plan=None):
|
171 |
+
"""
|
172 |
+
Compute the 1-D inverse discrete Fourier Transform.
|
173 |
+
|
174 |
+
This function computes the inverse of the 1-D *n*-point
|
175 |
+
discrete Fourier transform computed by `fft`. In other words,
|
176 |
+
``ifft(fft(x)) == x`` to within numerical accuracy.
|
177 |
+
|
178 |
+
The input should be ordered in the same way as is returned by `fft`,
|
179 |
+
i.e.,
|
180 |
+
|
181 |
+
* ``x[0]`` should contain the zero frequency term,
|
182 |
+
* ``x[1:n//2]`` should contain the positive-frequency terms,
|
183 |
+
* ``x[n//2 + 1:]`` should contain the negative-frequency terms, in
|
184 |
+
increasing order starting from the most negative frequency.
|
185 |
+
|
186 |
+
For an even number of input points, ``x[n//2]`` represents the sum of
|
187 |
+
the values at the positive and negative Nyquist frequencies, as the two
|
188 |
+
are aliased together. See `fft` for details.
|
189 |
+
|
190 |
+
Parameters
|
191 |
+
----------
|
192 |
+
x : array_like
|
193 |
+
Input array, can be complex.
|
194 |
+
n : int, optional
|
195 |
+
Length of the transformed axis of the output.
|
196 |
+
If `n` is smaller than the length of the input, the input is cropped.
|
197 |
+
If it is larger, the input is padded with zeros. If `n` is not given,
|
198 |
+
the length of the input along the axis specified by `axis` is used.
|
199 |
+
See notes about padding issues.
|
200 |
+
axis : int, optional
|
201 |
+
Axis over which to compute the inverse DFT. If not given, the last
|
202 |
+
axis is used.
|
203 |
+
norm : {"backward", "ortho", "forward"}, optional
|
204 |
+
Normalization mode (see `fft`). Default is "backward".
|
205 |
+
overwrite_x : bool, optional
|
206 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
207 |
+
See :func:`fft` for more details.
|
208 |
+
workers : int, optional
|
209 |
+
Maximum number of workers to use for parallel computation. If negative,
|
210 |
+
the value wraps around from ``os.cpu_count()``.
|
211 |
+
See :func:`~scipy.fft.fft` for more details.
|
212 |
+
plan : object, optional
|
213 |
+
This argument is reserved for passing in a precomputed plan provided
|
214 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
215 |
+
|
216 |
+
.. versionadded:: 1.5.0
|
217 |
+
|
218 |
+
Returns
|
219 |
+
-------
|
220 |
+
out : complex ndarray
|
221 |
+
The truncated or zero-padded input, transformed along the axis
|
222 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
223 |
+
|
224 |
+
Raises
|
225 |
+
------
|
226 |
+
IndexError
|
227 |
+
If `axes` is larger than the last axis of `x`.
|
228 |
+
|
229 |
+
See Also
|
230 |
+
--------
|
231 |
+
fft : The 1-D (forward) FFT, of which `ifft` is the inverse.
|
232 |
+
ifft2 : The 2-D inverse FFT.
|
233 |
+
ifftn : The N-D inverse FFT.
|
234 |
+
|
235 |
+
Notes
|
236 |
+
-----
|
237 |
+
If the input parameter `n` is larger than the size of the input, the input
|
238 |
+
is padded by appending zeros at the end. Even though this is the common
|
239 |
+
approach, it might lead to surprising results. If a different padding is
|
240 |
+
desired, it must be performed before calling `ifft`.
|
241 |
+
|
242 |
+
If ``x`` is a 1-D array, then the `ifft` is equivalent to ::
|
243 |
+
|
244 |
+
y[k] = np.sum(x * np.exp(2j * np.pi * k * np.arange(n)/n)) / len(x)
|
245 |
+
|
246 |
+
As with `fft`, `ifft` has support for all floating point types and is
|
247 |
+
optimized for real input.
|
248 |
+
|
249 |
+
Examples
|
250 |
+
--------
|
251 |
+
>>> import scipy.fft
|
252 |
+
>>> import numpy as np
|
253 |
+
>>> scipy.fft.ifft([0, 4, 0, 0])
|
254 |
+
array([ 1.+0.j, 0.+1.j, -1.+0.j, 0.-1.j]) # may vary
|
255 |
+
|
256 |
+
Create and plot a band-limited signal with random phases:
|
257 |
+
|
258 |
+
>>> import matplotlib.pyplot as plt
|
259 |
+
>>> rng = np.random.default_rng()
|
260 |
+
>>> t = np.arange(400)
|
261 |
+
>>> n = np.zeros((400,), dtype=complex)
|
262 |
+
>>> n[40:60] = np.exp(1j*rng.uniform(0, 2*np.pi, (20,)))
|
263 |
+
>>> s = scipy.fft.ifft(n)
|
264 |
+
>>> plt.plot(t, s.real, 'b-', t, s.imag, 'r--')
|
265 |
+
[<matplotlib.lines.Line2D object at ...>, <matplotlib.lines.Line2D object at ...>]
|
266 |
+
>>> plt.legend(('real', 'imaginary'))
|
267 |
+
<matplotlib.legend.Legend object at ...>
|
268 |
+
>>> plt.show()
|
269 |
+
|
270 |
+
"""
|
271 |
+
return (Dispatchable(x, np.ndarray),)
|
272 |
+
|
273 |
+
|
274 |
+
@_dispatch
|
275 |
+
def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
|
276 |
+
plan=None):
|
277 |
+
"""
|
278 |
+
Compute the 1-D discrete Fourier Transform for real input.
|
279 |
+
|
280 |
+
This function computes the 1-D *n*-point discrete Fourier
|
281 |
+
Transform (DFT) of a real-valued array by means of an efficient algorithm
|
282 |
+
called the Fast Fourier Transform (FFT).
|
283 |
+
|
284 |
+
Parameters
|
285 |
+
----------
|
286 |
+
x : array_like
|
287 |
+
Input array
|
288 |
+
n : int, optional
|
289 |
+
Number of points along transformation axis in the input to use.
|
290 |
+
If `n` is smaller than the length of the input, the input is cropped.
|
291 |
+
If it is larger, the input is padded with zeros. If `n` is not given,
|
292 |
+
the length of the input along the axis specified by `axis` is used.
|
293 |
+
axis : int, optional
|
294 |
+
Axis over which to compute the FFT. If not given, the last axis is
|
295 |
+
used.
|
296 |
+
norm : {"backward", "ortho", "forward"}, optional
|
297 |
+
Normalization mode (see `fft`). Default is "backward".
|
298 |
+
overwrite_x : bool, optional
|
299 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
300 |
+
See :func:`fft` for more details.
|
301 |
+
workers : int, optional
|
302 |
+
Maximum number of workers to use for parallel computation. If negative,
|
303 |
+
the value wraps around from ``os.cpu_count()``.
|
304 |
+
See :func:`~scipy.fft.fft` for more details.
|
305 |
+
plan : object, optional
|
306 |
+
This argument is reserved for passing in a precomputed plan provided
|
307 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
308 |
+
|
309 |
+
.. versionadded:: 1.5.0
|
310 |
+
|
311 |
+
Returns
|
312 |
+
-------
|
313 |
+
out : complex ndarray
|
314 |
+
The truncated or zero-padded input, transformed along the axis
|
315 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
316 |
+
If `n` is even, the length of the transformed axis is ``(n/2)+1``.
|
317 |
+
If `n` is odd, the length is ``(n+1)/2``.
|
318 |
+
|
319 |
+
Raises
|
320 |
+
------
|
321 |
+
IndexError
|
322 |
+
If `axis` is larger than the last axis of `a`.
|
323 |
+
|
324 |
+
See Also
|
325 |
+
--------
|
326 |
+
irfft : The inverse of `rfft`.
|
327 |
+
fft : The 1-D FFT of general (complex) input.
|
328 |
+
fftn : The N-D FFT.
|
329 |
+
rfft2 : The 2-D FFT of real input.
|
330 |
+
rfftn : The N-D FFT of real input.
|
331 |
+
|
332 |
+
Notes
|
333 |
+
-----
|
334 |
+
When the DFT is computed for purely real input, the output is
|
335 |
+
Hermitian-symmetric, i.e., the negative frequency terms are just the complex
|
336 |
+
conjugates of the corresponding positive-frequency terms, and the
|
337 |
+
negative-frequency terms are therefore redundant. This function does not
|
338 |
+
compute the negative frequency terms, and the length of the transformed
|
339 |
+
axis of the output is therefore ``n//2 + 1``.
|
340 |
+
|
341 |
+
When ``X = rfft(x)`` and fs is the sampling frequency, ``X[0]`` contains
|
342 |
+
the zero-frequency term 0*fs, which is real due to Hermitian symmetry.
|
343 |
+
|
344 |
+
If `n` is even, ``A[-1]`` contains the term representing both positive
|
345 |
+
and negative Nyquist frequency (+fs/2 and -fs/2), and must also be purely
|
346 |
+
real. If `n` is odd, there is no term at fs/2; ``A[-1]`` contains
|
347 |
+
the largest positive frequency (fs/2*(n-1)/n), and is complex in the
|
348 |
+
general case.
|
349 |
+
|
350 |
+
If the input `a` contains an imaginary part, it is silently discarded.
|
351 |
+
|
352 |
+
Examples
|
353 |
+
--------
|
354 |
+
>>> import scipy.fft
|
355 |
+
>>> scipy.fft.fft([0, 1, 0, 0])
|
356 |
+
array([ 1.+0.j, 0.-1.j, -1.+0.j, 0.+1.j]) # may vary
|
357 |
+
>>> scipy.fft.rfft([0, 1, 0, 0])
|
358 |
+
array([ 1.+0.j, 0.-1.j, -1.+0.j]) # may vary
|
359 |
+
|
360 |
+
Notice how the final element of the `fft` output is the complex conjugate
|
361 |
+
of the second element, for real input. For `rfft`, this symmetry is
|
362 |
+
exploited to compute only the non-negative frequency terms.
|
363 |
+
|
364 |
+
"""
|
365 |
+
return (Dispatchable(x, np.ndarray),)
|
366 |
+
|
367 |
+
|
368 |
+
@_dispatch
|
369 |
+
def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
|
370 |
+
plan=None):
|
371 |
+
"""
|
372 |
+
Computes the inverse of `rfft`.
|
373 |
+
|
374 |
+
This function computes the inverse of the 1-D *n*-point
|
375 |
+
discrete Fourier Transform of real input computed by `rfft`.
|
376 |
+
In other words, ``irfft(rfft(x), len(x)) == x`` to within numerical
|
377 |
+
accuracy. (See Notes below for why ``len(a)`` is necessary here.)
|
378 |
+
|
379 |
+
The input is expected to be in the form returned by `rfft`, i.e., the
|
380 |
+
real zero-frequency term followed by the complex positive frequency terms
|
381 |
+
in order of increasing frequency. Since the discrete Fourier Transform of
|
382 |
+
real input is Hermitian-symmetric, the negative frequency terms are taken
|
383 |
+
to be the complex conjugates of the corresponding positive frequency terms.
|
384 |
+
|
385 |
+
Parameters
|
386 |
+
----------
|
387 |
+
x : array_like
|
388 |
+
The input array.
|
389 |
+
n : int, optional
|
390 |
+
Length of the transformed axis of the output.
|
391 |
+
For `n` output points, ``n//2+1`` input points are necessary. If the
|
392 |
+
input is longer than this, it is cropped. If it is shorter than this,
|
393 |
+
it is padded with zeros. If `n` is not given, it is taken to be
|
394 |
+
``2*(m-1)``, where ``m`` is the length of the input along the axis
|
395 |
+
specified by `axis`.
|
396 |
+
axis : int, optional
|
397 |
+
Axis over which to compute the inverse FFT. If not given, the last
|
398 |
+
axis is used.
|
399 |
+
norm : {"backward", "ortho", "forward"}, optional
|
400 |
+
Normalization mode (see `fft`). Default is "backward".
|
401 |
+
overwrite_x : bool, optional
|
402 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
403 |
+
See :func:`fft` for more details.
|
404 |
+
workers : int, optional
|
405 |
+
Maximum number of workers to use for parallel computation. If negative,
|
406 |
+
the value wraps around from ``os.cpu_count()``.
|
407 |
+
See :func:`~scipy.fft.fft` for more details.
|
408 |
+
plan : object, optional
|
409 |
+
This argument is reserved for passing in a precomputed plan provided
|
410 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
411 |
+
|
412 |
+
.. versionadded:: 1.5.0
|
413 |
+
|
414 |
+
Returns
|
415 |
+
-------
|
416 |
+
out : ndarray
|
417 |
+
The truncated or zero-padded input, transformed along the axis
|
418 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
419 |
+
The length of the transformed axis is `n`, or, if `n` is not given,
|
420 |
+
``2*(m-1)`` where ``m`` is the length of the transformed axis of the
|
421 |
+
input. To get an odd number of output points, `n` must be specified.
|
422 |
+
|
423 |
+
Raises
|
424 |
+
------
|
425 |
+
IndexError
|
426 |
+
If `axis` is larger than the last axis of `x`.
|
427 |
+
|
428 |
+
See Also
|
429 |
+
--------
|
430 |
+
rfft : The 1-D FFT of real input, of which `irfft` is inverse.
|
431 |
+
fft : The 1-D FFT.
|
432 |
+
irfft2 : The inverse of the 2-D FFT of real input.
|
433 |
+
irfftn : The inverse of the N-D FFT of real input.
|
434 |
+
|
435 |
+
Notes
|
436 |
+
-----
|
437 |
+
Returns the real valued `n`-point inverse discrete Fourier transform
|
438 |
+
of `x`, where `x` contains the non-negative frequency terms of a
|
439 |
+
Hermitian-symmetric sequence. `n` is the length of the result, not the
|
440 |
+
input.
|
441 |
+
|
442 |
+
If you specify an `n` such that `a` must be zero-padded or truncated, the
|
443 |
+
extra/removed values will be added/removed at high frequencies. One can
|
444 |
+
thus resample a series to `m` points via Fourier interpolation by:
|
445 |
+
``a_resamp = irfft(rfft(a), m)``.
|
446 |
+
|
447 |
+
The default value of `n` assumes an even output length. By the Hermitian
|
448 |
+
symmetry, the last imaginary component must be 0 and so is ignored. To
|
449 |
+
avoid losing information, the correct length of the real input *must* be
|
450 |
+
given.
|
451 |
+
|
452 |
+
Examples
|
453 |
+
--------
|
454 |
+
>>> import scipy.fft
|
455 |
+
>>> scipy.fft.ifft([1, -1j, -1, 1j])
|
456 |
+
array([0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]) # may vary
|
457 |
+
>>> scipy.fft.irfft([1, -1j, -1])
|
458 |
+
array([0., 1., 0., 0.])
|
459 |
+
|
460 |
+
Notice how the last term in the input to the ordinary `ifft` is the
|
461 |
+
complex conjugate of the second term, and the output has zero imaginary
|
462 |
+
part everywhere. When calling `irfft`, the negative frequencies are not
|
463 |
+
specified, and the output array is purely real.
|
464 |
+
|
465 |
+
"""
|
466 |
+
return (Dispatchable(x, np.ndarray),)
|
467 |
+
|
468 |
+
|
469 |
+
@_dispatch
|
470 |
+
def hfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
|
471 |
+
plan=None):
|
472 |
+
"""
|
473 |
+
Compute the FFT of a signal that has Hermitian symmetry, i.e., a real
|
474 |
+
spectrum.
|
475 |
+
|
476 |
+
Parameters
|
477 |
+
----------
|
478 |
+
x : array_like
|
479 |
+
The input array.
|
480 |
+
n : int, optional
|
481 |
+
Length of the transformed axis of the output. For `n` output
|
482 |
+
points, ``n//2 + 1`` input points are necessary. If the input is
|
483 |
+
longer than this, it is cropped. If it is shorter than this, it is
|
484 |
+
padded with zeros. If `n` is not given, it is taken to be ``2*(m-1)``,
|
485 |
+
where ``m`` is the length of the input along the axis specified by
|
486 |
+
`axis`.
|
487 |
+
axis : int, optional
|
488 |
+
Axis over which to compute the FFT. If not given, the last
|
489 |
+
axis is used.
|
490 |
+
norm : {"backward", "ortho", "forward"}, optional
|
491 |
+
Normalization mode (see `fft`). Default is "backward".
|
492 |
+
overwrite_x : bool, optional
|
493 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
494 |
+
See `fft` for more details.
|
495 |
+
workers : int, optional
|
496 |
+
Maximum number of workers to use for parallel computation. If negative,
|
497 |
+
the value wraps around from ``os.cpu_count()``.
|
498 |
+
See :func:`~scipy.fft.fft` for more details.
|
499 |
+
plan : object, optional
|
500 |
+
This argument is reserved for passing in a precomputed plan provided
|
501 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
502 |
+
|
503 |
+
.. versionadded:: 1.5.0
|
504 |
+
|
505 |
+
Returns
|
506 |
+
-------
|
507 |
+
out : ndarray
|
508 |
+
The truncated or zero-padded input, transformed along the axis
|
509 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
510 |
+
The length of the transformed axis is `n`, or, if `n` is not given,
|
511 |
+
``2*m - 2``, where ``m`` is the length of the transformed axis of
|
512 |
+
the input. To get an odd number of output points, `n` must be
|
513 |
+
specified, for instance, as ``2*m - 1`` in the typical case,
|
514 |
+
|
515 |
+
Raises
|
516 |
+
------
|
517 |
+
IndexError
|
518 |
+
If `axis` is larger than the last axis of `a`.
|
519 |
+
|
520 |
+
See Also
|
521 |
+
--------
|
522 |
+
rfft : Compute the 1-D FFT for real input.
|
523 |
+
ihfft : The inverse of `hfft`.
|
524 |
+
hfftn : Compute the N-D FFT of a Hermitian signal.
|
525 |
+
|
526 |
+
Notes
|
527 |
+
-----
|
528 |
+
`hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
|
529 |
+
opposite case: here the signal has Hermitian symmetry in the time
|
530 |
+
domain and is real in the frequency domain. So, here, it's `hfft`, for
|
531 |
+
which you must supply the length of the result if it is to be odd.
|
532 |
+
* even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
|
533 |
+
* odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
|
534 |
+
|
535 |
+
Examples
|
536 |
+
--------
|
537 |
+
>>> from scipy.fft import fft, hfft
|
538 |
+
>>> import numpy as np
|
539 |
+
>>> a = 2 * np.pi * np.arange(10) / 10
|
540 |
+
>>> signal = np.cos(a) + 3j * np.sin(3 * a)
|
541 |
+
>>> fft(signal).round(10)
|
542 |
+
array([ -0.+0.j, 5.+0.j, -0.+0.j, 15.-0.j, 0.+0.j, 0.+0.j,
|
543 |
+
-0.+0.j, -15.-0.j, 0.+0.j, 5.+0.j])
|
544 |
+
>>> hfft(signal[:6]).round(10) # Input first half of signal
|
545 |
+
array([ 0., 5., 0., 15., -0., 0., 0., -15., -0., 5.])
|
546 |
+
>>> hfft(signal, 10) # Input entire signal and truncate
|
547 |
+
array([ 0., 5., 0., 15., -0., 0., 0., -15., -0., 5.])
|
548 |
+
"""
|
549 |
+
return (Dispatchable(x, np.ndarray),)
|
550 |
+
|
551 |
+
|
552 |
+
@_dispatch
|
553 |
+
def ihfft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
|
554 |
+
plan=None):
|
555 |
+
"""
|
556 |
+
Compute the inverse FFT of a signal that has Hermitian symmetry.
|
557 |
+
|
558 |
+
Parameters
|
559 |
+
----------
|
560 |
+
x : array_like
|
561 |
+
Input array.
|
562 |
+
n : int, optional
|
563 |
+
Length of the inverse FFT, the number of points along
|
564 |
+
transformation axis in the input to use. If `n` is smaller than
|
565 |
+
the length of the input, the input is cropped. If it is larger,
|
566 |
+
the input is padded with zeros. If `n` is not given, the length of
|
567 |
+
the input along the axis specified by `axis` is used.
|
568 |
+
axis : int, optional
|
569 |
+
Axis over which to compute the inverse FFT. If not given, the last
|
570 |
+
axis is used.
|
571 |
+
norm : {"backward", "ortho", "forward"}, optional
|
572 |
+
Normalization mode (see `fft`). Default is "backward".
|
573 |
+
overwrite_x : bool, optional
|
574 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
575 |
+
See `fft` for more details.
|
576 |
+
workers : int, optional
|
577 |
+
Maximum number of workers to use for parallel computation. If negative,
|
578 |
+
the value wraps around from ``os.cpu_count()``.
|
579 |
+
See :func:`~scipy.fft.fft` for more details.
|
580 |
+
plan : object, optional
|
581 |
+
This argument is reserved for passing in a precomputed plan provided
|
582 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
583 |
+
|
584 |
+
.. versionadded:: 1.5.0
|
585 |
+
|
586 |
+
Returns
|
587 |
+
-------
|
588 |
+
out : complex ndarray
|
589 |
+
The truncated or zero-padded input, transformed along the axis
|
590 |
+
indicated by `axis`, or the last one if `axis` is not specified.
|
591 |
+
The length of the transformed axis is ``n//2 + 1``.
|
592 |
+
|
593 |
+
See Also
|
594 |
+
--------
|
595 |
+
hfft, irfft
|
596 |
+
|
597 |
+
Notes
|
598 |
+
-----
|
599 |
+
`hfft`/`ihfft` are a pair analogous to `rfft`/`irfft`, but for the
|
600 |
+
opposite case: here, the signal has Hermitian symmetry in the time
|
601 |
+
domain and is real in the frequency domain. So, here, it's `hfft`, for
|
602 |
+
which you must supply the length of the result if it is to be odd:
|
603 |
+
* even: ``ihfft(hfft(a, 2*len(a) - 2) == a``, within roundoff error,
|
604 |
+
* odd: ``ihfft(hfft(a, 2*len(a) - 1) == a``, within roundoff error.
|
605 |
+
|
606 |
+
Examples
|
607 |
+
--------
|
608 |
+
>>> from scipy.fft import ifft, ihfft
|
609 |
+
>>> import numpy as np
|
610 |
+
>>> spectrum = np.array([ 15, -4, 0, -1, 0, -4])
|
611 |
+
>>> ifft(spectrum)
|
612 |
+
array([1.+0.j, 2.+0.j, 3.+0.j, 4.+0.j, 3.+0.j, 2.+0.j]) # may vary
|
613 |
+
>>> ihfft(spectrum)
|
614 |
+
array([ 1.-0.j, 2.-0.j, 3.-0.j, 4.-0.j]) # may vary
|
615 |
+
"""
|
616 |
+
return (Dispatchable(x, np.ndarray),)
|
617 |
+
|
618 |
+
|
619 |
+
@_dispatch
|
620 |
+
def fftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
|
621 |
+
plan=None):
|
622 |
+
"""
|
623 |
+
Compute the N-D discrete Fourier Transform.
|
624 |
+
|
625 |
+
This function computes the N-D discrete Fourier Transform over
|
626 |
+
any number of axes in an M-D array by means of the Fast Fourier
|
627 |
+
Transform (FFT).
|
628 |
+
|
629 |
+
Parameters
|
630 |
+
----------
|
631 |
+
x : array_like
|
632 |
+
Input array, can be complex.
|
633 |
+
s : sequence of ints, optional
|
634 |
+
Shape (length of each transformed axis) of the output
|
635 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
|
636 |
+
This corresponds to ``n`` for ``fft(x, n)``.
|
637 |
+
Along any axis, if the given shape is smaller than that of the input,
|
638 |
+
the input is cropped. If it is larger, the input is padded with zeros.
|
639 |
+
if `s` is not given, the shape of the input along the axes specified
|
640 |
+
by `axes` is used.
|
641 |
+
axes : sequence of ints, optional
|
642 |
+
Axes over which to compute the FFT. If not given, the last ``len(s)``
|
643 |
+
axes are used, or all axes if `s` is also not specified.
|
644 |
+
norm : {"backward", "ortho", "forward"}, optional
|
645 |
+
Normalization mode (see `fft`). Default is "backward".
|
646 |
+
overwrite_x : bool, optional
|
647 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
648 |
+
See :func:`fft` for more details.
|
649 |
+
workers : int, optional
|
650 |
+
Maximum number of workers to use for parallel computation. If negative,
|
651 |
+
the value wraps around from ``os.cpu_count()``.
|
652 |
+
See :func:`~scipy.fft.fft` for more details.
|
653 |
+
plan : object, optional
|
654 |
+
This argument is reserved for passing in a precomputed plan provided
|
655 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
656 |
+
|
657 |
+
.. versionadded:: 1.5.0
|
658 |
+
|
659 |
+
Returns
|
660 |
+
-------
|
661 |
+
out : complex ndarray
|
662 |
+
The truncated or zero-padded input, transformed along the axes
|
663 |
+
indicated by `axes`, or by a combination of `s` and `x`,
|
664 |
+
as explained in the parameters section above.
|
665 |
+
|
666 |
+
Raises
|
667 |
+
------
|
668 |
+
ValueError
|
669 |
+
If `s` and `axes` have different length.
|
670 |
+
IndexError
|
671 |
+
If an element of `axes` is larger than the number of axes of `x`.
|
672 |
+
|
673 |
+
See Also
|
674 |
+
--------
|
675 |
+
ifftn : The inverse of `fftn`, the inverse N-D FFT.
|
676 |
+
fft : The 1-D FFT, with definitions and conventions used.
|
677 |
+
rfftn : The N-D FFT of real input.
|
678 |
+
fft2 : The 2-D FFT.
|
679 |
+
fftshift : Shifts zero-frequency terms to centre of array.
|
680 |
+
|
681 |
+
Notes
|
682 |
+
-----
|
683 |
+
The output, analogously to `fft`, contains the term for zero frequency in
|
684 |
+
the low-order corner of all axes, the positive frequency terms in the
|
685 |
+
first half of all axes, the term for the Nyquist frequency in the middle
|
686 |
+
of all axes and the negative frequency terms in the second half of all
|
687 |
+
axes, in order of decreasingly negative frequency.
|
688 |
+
|
689 |
+
Examples
|
690 |
+
--------
|
691 |
+
>>> import scipy.fft
|
692 |
+
>>> import numpy as np
|
693 |
+
>>> x = np.mgrid[:3, :3, :3][0]
|
694 |
+
>>> scipy.fft.fftn(x, axes=(1, 2))
|
695 |
+
array([[[ 0.+0.j, 0.+0.j, 0.+0.j], # may vary
|
696 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j],
|
697 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j]],
|
698 |
+
[[ 9.+0.j, 0.+0.j, 0.+0.j],
|
699 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j],
|
700 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j]],
|
701 |
+
[[18.+0.j, 0.+0.j, 0.+0.j],
|
702 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j],
|
703 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j]]])
|
704 |
+
>>> scipy.fft.fftn(x, (2, 2), axes=(0, 1))
|
705 |
+
array([[[ 2.+0.j, 2.+0.j, 2.+0.j], # may vary
|
706 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j]],
|
707 |
+
[[-2.+0.j, -2.+0.j, -2.+0.j],
|
708 |
+
[ 0.+0.j, 0.+0.j, 0.+0.j]]])
|
709 |
+
|
710 |
+
>>> import matplotlib.pyplot as plt
|
711 |
+
>>> rng = np.random.default_rng()
|
712 |
+
>>> [X, Y] = np.meshgrid(2 * np.pi * np.arange(200) / 12,
|
713 |
+
... 2 * np.pi * np.arange(200) / 34)
|
714 |
+
>>> S = np.sin(X) + np.cos(Y) + rng.uniform(0, 1, X.shape)
|
715 |
+
>>> FS = scipy.fft.fftn(S)
|
716 |
+
>>> plt.imshow(np.log(np.abs(scipy.fft.fftshift(FS))**2))
|
717 |
+
<matplotlib.image.AxesImage object at 0x...>
|
718 |
+
>>> plt.show()
|
719 |
+
|
720 |
+
"""
|
721 |
+
return (Dispatchable(x, np.ndarray),)
|
722 |
+
|
723 |
+
|
724 |
+
@_dispatch
|
725 |
+
def ifftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
|
726 |
+
plan=None):
|
727 |
+
"""
|
728 |
+
Compute the N-D inverse discrete Fourier Transform.
|
729 |
+
|
730 |
+
This function computes the inverse of the N-D discrete
|
731 |
+
Fourier Transform over any number of axes in an M-D array by
|
732 |
+
means of the Fast Fourier Transform (FFT). In other words,
|
733 |
+
``ifftn(fftn(x)) == x`` to within numerical accuracy.
|
734 |
+
|
735 |
+
The input, analogously to `ifft`, should be ordered in the same way as is
|
736 |
+
returned by `fftn`, i.e., it should have the term for zero frequency
|
737 |
+
in all axes in the low-order corner, the positive frequency terms in the
|
738 |
+
first half of all axes, the term for the Nyquist frequency in the middle
|
739 |
+
of all axes and the negative frequency terms in the second half of all
|
740 |
+
axes, in order of decreasingly negative frequency.
|
741 |
+
|
742 |
+
Parameters
|
743 |
+
----------
|
744 |
+
x : array_like
|
745 |
+
Input array, can be complex.
|
746 |
+
s : sequence of ints, optional
|
747 |
+
Shape (length of each transformed axis) of the output
|
748 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
|
749 |
+
This corresponds to ``n`` for ``ifft(x, n)``.
|
750 |
+
Along any axis, if the given shape is smaller than that of the input,
|
751 |
+
the input is cropped. If it is larger, the input is padded with zeros.
|
752 |
+
if `s` is not given, the shape of the input along the axes specified
|
753 |
+
by `axes` is used. See notes for issue on `ifft` zero padding.
|
754 |
+
axes : sequence of ints, optional
|
755 |
+
Axes over which to compute the IFFT. If not given, the last ``len(s)``
|
756 |
+
axes are used, or all axes if `s` is also not specified.
|
757 |
+
norm : {"backward", "ortho", "forward"}, optional
|
758 |
+
Normalization mode (see `fft`). Default is "backward".
|
759 |
+
overwrite_x : bool, optional
|
760 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
761 |
+
See :func:`fft` for more details.
|
762 |
+
workers : int, optional
|
763 |
+
Maximum number of workers to use for parallel computation. If negative,
|
764 |
+
the value wraps around from ``os.cpu_count()``.
|
765 |
+
See :func:`~scipy.fft.fft` for more details.
|
766 |
+
plan : object, optional
|
767 |
+
This argument is reserved for passing in a precomputed plan provided
|
768 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
769 |
+
|
770 |
+
.. versionadded:: 1.5.0
|
771 |
+
|
772 |
+
Returns
|
773 |
+
-------
|
774 |
+
out : complex ndarray
|
775 |
+
The truncated or zero-padded input, transformed along the axes
|
776 |
+
indicated by `axes`, or by a combination of `s` or `x`,
|
777 |
+
as explained in the parameters section above.
|
778 |
+
|
779 |
+
Raises
|
780 |
+
------
|
781 |
+
ValueError
|
782 |
+
If `s` and `axes` have different length.
|
783 |
+
IndexError
|
784 |
+
If an element of `axes` is larger than the number of axes of `x`.
|
785 |
+
|
786 |
+
See Also
|
787 |
+
--------
|
788 |
+
fftn : The forward N-D FFT, of which `ifftn` is the inverse.
|
789 |
+
ifft : The 1-D inverse FFT.
|
790 |
+
ifft2 : The 2-D inverse FFT.
|
791 |
+
ifftshift : Undoes `fftshift`, shifts zero-frequency terms to beginning
|
792 |
+
of array.
|
793 |
+
|
794 |
+
Notes
|
795 |
+
-----
|
796 |
+
Zero-padding, analogously with `ifft`, is performed by appending zeros to
|
797 |
+
the input along the specified dimension. Although this is the common
|
798 |
+
approach, it might lead to surprising results. If another form of zero
|
799 |
+
padding is desired, it must be performed before `ifftn` is called.
|
800 |
+
|
801 |
+
Examples
|
802 |
+
--------
|
803 |
+
>>> import scipy.fft
|
804 |
+
>>> import numpy as np
|
805 |
+
>>> x = np.eye(4)
|
806 |
+
>>> scipy.fft.ifftn(scipy.fft.fftn(x, axes=(0,)), axes=(1,))
|
807 |
+
array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary
|
808 |
+
[0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j],
|
809 |
+
[0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
|
810 |
+
[0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]])
|
811 |
+
|
812 |
+
|
813 |
+
Create and plot an image with band-limited frequency content:
|
814 |
+
|
815 |
+
>>> import matplotlib.pyplot as plt
|
816 |
+
>>> rng = np.random.default_rng()
|
817 |
+
>>> n = np.zeros((200,200), dtype=complex)
|
818 |
+
>>> n[60:80, 20:40] = np.exp(1j*rng.uniform(0, 2*np.pi, (20, 20)))
|
819 |
+
>>> im = scipy.fft.ifftn(n).real
|
820 |
+
>>> plt.imshow(im)
|
821 |
+
<matplotlib.image.AxesImage object at 0x...>
|
822 |
+
>>> plt.show()
|
823 |
+
|
824 |
+
"""
|
825 |
+
return (Dispatchable(x, np.ndarray),)
|
826 |
+
|
827 |
+
|
828 |
+
@_dispatch
|
829 |
+
def fft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
|
830 |
+
plan=None):
|
831 |
+
"""
|
832 |
+
Compute the 2-D discrete Fourier Transform
|
833 |
+
|
834 |
+
This function computes the N-D discrete Fourier Transform
|
835 |
+
over any axes in an M-D array by means of the
|
836 |
+
Fast Fourier Transform (FFT). By default, the transform is computed over
|
837 |
+
the last two axes of the input array, i.e., a 2-dimensional FFT.
|
838 |
+
|
839 |
+
Parameters
|
840 |
+
----------
|
841 |
+
x : array_like
|
842 |
+
Input array, can be complex
|
843 |
+
s : sequence of ints, optional
|
844 |
+
Shape (length of each transformed axis) of the output
|
845 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
|
846 |
+
This corresponds to ``n`` for ``fft(x, n)``.
|
847 |
+
Along each axis, if the given shape is smaller than that of the input,
|
848 |
+
the input is cropped. If it is larger, the input is padded with zeros.
|
849 |
+
if `s` is not given, the shape of the input along the axes specified
|
850 |
+
by `axes` is used.
|
851 |
+
axes : sequence of ints, optional
|
852 |
+
Axes over which to compute the FFT. If not given, the last two axes are
|
853 |
+
used.
|
854 |
+
norm : {"backward", "ortho", "forward"}, optional
|
855 |
+
Normalization mode (see `fft`). Default is "backward".
|
856 |
+
overwrite_x : bool, optional
|
857 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
858 |
+
See :func:`fft` for more details.
|
859 |
+
workers : int, optional
|
860 |
+
Maximum number of workers to use for parallel computation. If negative,
|
861 |
+
the value wraps around from ``os.cpu_count()``.
|
862 |
+
See :func:`~scipy.fft.fft` for more details.
|
863 |
+
plan : object, optional
|
864 |
+
This argument is reserved for passing in a precomputed plan provided
|
865 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
866 |
+
|
867 |
+
.. versionadded:: 1.5.0
|
868 |
+
|
869 |
+
Returns
|
870 |
+
-------
|
871 |
+
out : complex ndarray
|
872 |
+
The truncated or zero-padded input, transformed along the axes
|
873 |
+
indicated by `axes`, or the last two axes if `axes` is not given.
|
874 |
+
|
875 |
+
Raises
|
876 |
+
------
|
877 |
+
ValueError
|
878 |
+
If `s` and `axes` have different length, or `axes` not given and
|
879 |
+
``len(s) != 2``.
|
880 |
+
IndexError
|
881 |
+
If an element of `axes` is larger than the number of axes of `x`.
|
882 |
+
|
883 |
+
See Also
|
884 |
+
--------
|
885 |
+
ifft2 : The inverse 2-D FFT.
|
886 |
+
fft : The 1-D FFT.
|
887 |
+
fftn : The N-D FFT.
|
888 |
+
fftshift : Shifts zero-frequency terms to the center of the array.
|
889 |
+
For 2-D input, swaps first and third quadrants, and second
|
890 |
+
and fourth quadrants.
|
891 |
+
|
892 |
+
Notes
|
893 |
+
-----
|
894 |
+
`fft2` is just `fftn` with a different default for `axes`.
|
895 |
+
|
896 |
+
The output, analogously to `fft`, contains the term for zero frequency in
|
897 |
+
the low-order corner of the transformed axes, the positive frequency terms
|
898 |
+
in the first half of these axes, the term for the Nyquist frequency in the
|
899 |
+
middle of the axes and the negative frequency terms in the second half of
|
900 |
+
the axes, in order of decreasingly negative frequency.
|
901 |
+
|
902 |
+
See `fftn` for details and a plotting example, and `fft` for
|
903 |
+
definitions and conventions used.
|
904 |
+
|
905 |
+
|
906 |
+
Examples
|
907 |
+
--------
|
908 |
+
>>> import scipy.fft
|
909 |
+
>>> import numpy as np
|
910 |
+
>>> x = np.mgrid[:5, :5][0]
|
911 |
+
>>> scipy.fft.fft2(x)
|
912 |
+
array([[ 50. +0.j , 0. +0.j , 0. +0.j , # may vary
|
913 |
+
0. +0.j , 0. +0.j ],
|
914 |
+
[-12.5+17.20477401j, 0. +0.j , 0. +0.j ,
|
915 |
+
0. +0.j , 0. +0.j ],
|
916 |
+
[-12.5 +4.0614962j , 0. +0.j , 0. +0.j ,
|
917 |
+
0. +0.j , 0. +0.j ],
|
918 |
+
[-12.5 -4.0614962j , 0. +0.j , 0. +0.j ,
|
919 |
+
0. +0.j , 0. +0.j ],
|
920 |
+
[-12.5-17.20477401j, 0. +0.j , 0. +0.j ,
|
921 |
+
0. +0.j , 0. +0.j ]])
|
922 |
+
|
923 |
+
"""
|
924 |
+
return (Dispatchable(x, np.ndarray),)
|
925 |
+
|
926 |
+
|
927 |
+
@_dispatch
|
928 |
+
def ifft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
|
929 |
+
plan=None):
|
930 |
+
"""
|
931 |
+
Compute the 2-D inverse discrete Fourier Transform.
|
932 |
+
|
933 |
+
This function computes the inverse of the 2-D discrete Fourier
|
934 |
+
Transform over any number of axes in an M-D array by means of
|
935 |
+
the Fast Fourier Transform (FFT). In other words, ``ifft2(fft2(x)) == x``
|
936 |
+
to within numerical accuracy. By default, the inverse transform is
|
937 |
+
computed over the last two axes of the input array.
|
938 |
+
|
939 |
+
The input, analogously to `ifft`, should be ordered in the same way as is
|
940 |
+
returned by `fft2`, i.e., it should have the term for zero frequency
|
941 |
+
in the low-order corner of the two axes, the positive frequency terms in
|
942 |
+
the first half of these axes, the term for the Nyquist frequency in the
|
943 |
+
middle of the axes and the negative frequency terms in the second half of
|
944 |
+
both axes, in order of decreasingly negative frequency.
|
945 |
+
|
946 |
+
Parameters
|
947 |
+
----------
|
948 |
+
x : array_like
|
949 |
+
Input array, can be complex.
|
950 |
+
s : sequence of ints, optional
|
951 |
+
Shape (length of each axis) of the output (``s[0]`` refers to axis 0,
|
952 |
+
``s[1]`` to axis 1, etc.). This corresponds to `n` for ``ifft(x, n)``.
|
953 |
+
Along each axis, if the given shape is smaller than that of the input,
|
954 |
+
the input is cropped. If it is larger, the input is padded with zeros.
|
955 |
+
if `s` is not given, the shape of the input along the axes specified
|
956 |
+
by `axes` is used. See notes for issue on `ifft` zero padding.
|
957 |
+
axes : sequence of ints, optional
|
958 |
+
Axes over which to compute the FFT. If not given, the last two
|
959 |
+
axes are used.
|
960 |
+
norm : {"backward", "ortho", "forward"}, optional
|
961 |
+
Normalization mode (see `fft`). Default is "backward".
|
962 |
+
overwrite_x : bool, optional
|
963 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
964 |
+
See :func:`fft` for more details.
|
965 |
+
workers : int, optional
|
966 |
+
Maximum number of workers to use for parallel computation. If negative,
|
967 |
+
the value wraps around from ``os.cpu_count()``.
|
968 |
+
See :func:`~scipy.fft.fft` for more details.
|
969 |
+
plan : object, optional
|
970 |
+
This argument is reserved for passing in a precomputed plan provided
|
971 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
972 |
+
|
973 |
+
.. versionadded:: 1.5.0
|
974 |
+
|
975 |
+
Returns
|
976 |
+
-------
|
977 |
+
out : complex ndarray
|
978 |
+
The truncated or zero-padded input, transformed along the axes
|
979 |
+
indicated by `axes`, or the last two axes if `axes` is not given.
|
980 |
+
|
981 |
+
Raises
|
982 |
+
------
|
983 |
+
ValueError
|
984 |
+
If `s` and `axes` have different length, or `axes` not given and
|
985 |
+
``len(s) != 2``.
|
986 |
+
IndexError
|
987 |
+
If an element of `axes` is larger than the number of axes of `x`.
|
988 |
+
|
989 |
+
See Also
|
990 |
+
--------
|
991 |
+
fft2 : The forward 2-D FFT, of which `ifft2` is the inverse.
|
992 |
+
ifftn : The inverse of the N-D FFT.
|
993 |
+
fft : The 1-D FFT.
|
994 |
+
ifft : The 1-D inverse FFT.
|
995 |
+
|
996 |
+
Notes
|
997 |
+
-----
|
998 |
+
`ifft2` is just `ifftn` with a different default for `axes`.
|
999 |
+
|
1000 |
+
See `ifftn` for details and a plotting example, and `fft` for
|
1001 |
+
definition and conventions used.
|
1002 |
+
|
1003 |
+
Zero-padding, analogously with `ifft`, is performed by appending zeros to
|
1004 |
+
the input along the specified dimension. Although this is the common
|
1005 |
+
approach, it might lead to surprising results. If another form of zero
|
1006 |
+
padding is desired, it must be performed before `ifft2` is called.
|
1007 |
+
|
1008 |
+
Examples
|
1009 |
+
--------
|
1010 |
+
>>> import scipy.fft
|
1011 |
+
>>> import numpy as np
|
1012 |
+
>>> x = 4 * np.eye(4)
|
1013 |
+
>>> scipy.fft.ifft2(x)
|
1014 |
+
array([[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], # may vary
|
1015 |
+
[0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j],
|
1016 |
+
[0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j],
|
1017 |
+
[0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j]])
|
1018 |
+
|
1019 |
+
"""
|
1020 |
+
return (Dispatchable(x, np.ndarray),)
|
1021 |
+
|
1022 |
+
|
1023 |
+
@_dispatch
|
1024 |
+
def rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
|
1025 |
+
plan=None):
|
1026 |
+
"""
|
1027 |
+
Compute the N-D discrete Fourier Transform for real input.
|
1028 |
+
|
1029 |
+
This function computes the N-D discrete Fourier Transform over
|
1030 |
+
any number of axes in an M-D real array by means of the Fast
|
1031 |
+
Fourier Transform (FFT). By default, all axes are transformed, with the
|
1032 |
+
real transform performed over the last axis, while the remaining
|
1033 |
+
transforms are complex.
|
1034 |
+
|
1035 |
+
Parameters
|
1036 |
+
----------
|
1037 |
+
x : array_like
|
1038 |
+
Input array, taken to be real.
|
1039 |
+
s : sequence of ints, optional
|
1040 |
+
Shape (length along each transformed axis) to use from the input.
|
1041 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
|
1042 |
+
The final element of `s` corresponds to `n` for ``rfft(x, n)``, while
|
1043 |
+
for the remaining axes, it corresponds to `n` for ``fft(x, n)``.
|
1044 |
+
Along any axis, if the given shape is smaller than that of the input,
|
1045 |
+
the input is cropped. If it is larger, the input is padded with zeros.
|
1046 |
+
if `s` is not given, the shape of the input along the axes specified
|
1047 |
+
by `axes` is used.
|
1048 |
+
axes : sequence of ints, optional
|
1049 |
+
Axes over which to compute the FFT. If not given, the last ``len(s)``
|
1050 |
+
axes are used, or all axes if `s` is also not specified.
|
1051 |
+
norm : {"backward", "ortho", "forward"}, optional
|
1052 |
+
Normalization mode (see `fft`). Default is "backward".
|
1053 |
+
overwrite_x : bool, optional
|
1054 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
1055 |
+
See :func:`fft` for more details.
|
1056 |
+
workers : int, optional
|
1057 |
+
Maximum number of workers to use for parallel computation. If negative,
|
1058 |
+
the value wraps around from ``os.cpu_count()``.
|
1059 |
+
See :func:`~scipy.fft.fft` for more details.
|
1060 |
+
plan : object, optional
|
1061 |
+
This argument is reserved for passing in a precomputed plan provided
|
1062 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
1063 |
+
|
1064 |
+
.. versionadded:: 1.5.0
|
1065 |
+
|
1066 |
+
Returns
|
1067 |
+
-------
|
1068 |
+
out : complex ndarray
|
1069 |
+
The truncated or zero-padded input, transformed along the axes
|
1070 |
+
indicated by `axes`, or by a combination of `s` and `x`,
|
1071 |
+
as explained in the parameters section above.
|
1072 |
+
The length of the last axis transformed will be ``s[-1]//2+1``,
|
1073 |
+
while the remaining transformed axes will have lengths according to
|
1074 |
+
`s`, or unchanged from the input.
|
1075 |
+
|
1076 |
+
Raises
|
1077 |
+
------
|
1078 |
+
ValueError
|
1079 |
+
If `s` and `axes` have different length.
|
1080 |
+
IndexError
|
1081 |
+
If an element of `axes` is larger than the number of axes of `x`.
|
1082 |
+
|
1083 |
+
See Also
|
1084 |
+
--------
|
1085 |
+
irfftn : The inverse of `rfftn`, i.e., the inverse of the N-D FFT
|
1086 |
+
of real input.
|
1087 |
+
fft : The 1-D FFT, with definitions and conventions used.
|
1088 |
+
rfft : The 1-D FFT of real input.
|
1089 |
+
fftn : The N-D FFT.
|
1090 |
+
rfft2 : The 2-D FFT of real input.
|
1091 |
+
|
1092 |
+
Notes
|
1093 |
+
-----
|
1094 |
+
The transform for real input is performed over the last transformation
|
1095 |
+
axis, as by `rfft`, then the transform over the remaining axes is
|
1096 |
+
performed as by `fftn`. The order of the output is as for `rfft` for the
|
1097 |
+
final transformation axis, and as for `fftn` for the remaining
|
1098 |
+
transformation axes.
|
1099 |
+
|
1100 |
+
See `fft` for details, definitions and conventions used.
|
1101 |
+
|
1102 |
+
Examples
|
1103 |
+
--------
|
1104 |
+
>>> import scipy.fft
|
1105 |
+
>>> import numpy as np
|
1106 |
+
>>> x = np.ones((2, 2, 2))
|
1107 |
+
>>> scipy.fft.rfftn(x)
|
1108 |
+
array([[[8.+0.j, 0.+0.j], # may vary
|
1109 |
+
[0.+0.j, 0.+0.j]],
|
1110 |
+
[[0.+0.j, 0.+0.j],
|
1111 |
+
[0.+0.j, 0.+0.j]]])
|
1112 |
+
|
1113 |
+
>>> scipy.fft.rfftn(x, axes=(2, 0))
|
1114 |
+
array([[[4.+0.j, 0.+0.j], # may vary
|
1115 |
+
[4.+0.j, 0.+0.j]],
|
1116 |
+
[[0.+0.j, 0.+0.j],
|
1117 |
+
[0.+0.j, 0.+0.j]]])
|
1118 |
+
|
1119 |
+
"""
|
1120 |
+
return (Dispatchable(x, np.ndarray),)
|
1121 |
+
|
1122 |
+
|
1123 |
+
@_dispatch
|
1124 |
+
def rfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
|
1125 |
+
plan=None):
|
1126 |
+
"""
|
1127 |
+
Compute the 2-D FFT of a real array.
|
1128 |
+
|
1129 |
+
Parameters
|
1130 |
+
----------
|
1131 |
+
x : array
|
1132 |
+
Input array, taken to be real.
|
1133 |
+
s : sequence of ints, optional
|
1134 |
+
Shape of the FFT.
|
1135 |
+
axes : sequence of ints, optional
|
1136 |
+
Axes over which to compute the FFT.
|
1137 |
+
norm : {"backward", "ortho", "forward"}, optional
|
1138 |
+
Normalization mode (see `fft`). Default is "backward".
|
1139 |
+
overwrite_x : bool, optional
|
1140 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
1141 |
+
See :func:`fft` for more details.
|
1142 |
+
workers : int, optional
|
1143 |
+
Maximum number of workers to use for parallel computation. If negative,
|
1144 |
+
the value wraps around from ``os.cpu_count()``.
|
1145 |
+
See :func:`~scipy.fft.fft` for more details.
|
1146 |
+
plan : object, optional
|
1147 |
+
This argument is reserved for passing in a precomputed plan provided
|
1148 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
1149 |
+
|
1150 |
+
.. versionadded:: 1.5.0
|
1151 |
+
|
1152 |
+
Returns
|
1153 |
+
-------
|
1154 |
+
out : ndarray
|
1155 |
+
The result of the real 2-D FFT.
|
1156 |
+
|
1157 |
+
See Also
|
1158 |
+
--------
|
1159 |
+
irfft2 : The inverse of the 2-D FFT of real input.
|
1160 |
+
rfft : The 1-D FFT of real input.
|
1161 |
+
rfftn : Compute the N-D discrete Fourier Transform for real
|
1162 |
+
input.
|
1163 |
+
|
1164 |
+
Notes
|
1165 |
+
-----
|
1166 |
+
This is really just `rfftn` with different default behavior.
|
1167 |
+
For more details see `rfftn`.
|
1168 |
+
|
1169 |
+
"""
|
1170 |
+
return (Dispatchable(x, np.ndarray),)
|
1171 |
+
|
1172 |
+
|
1173 |
+
@_dispatch
|
1174 |
+
def irfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
|
1175 |
+
plan=None):
|
1176 |
+
"""
|
1177 |
+
Computes the inverse of `rfftn`
|
1178 |
+
|
1179 |
+
This function computes the inverse of the N-D discrete
|
1180 |
+
Fourier Transform for real input over any number of axes in an
|
1181 |
+
M-D array by means of the Fast Fourier Transform (FFT). In
|
1182 |
+
other words, ``irfftn(rfftn(x), x.shape) == x`` to within numerical
|
1183 |
+
accuracy. (The ``a.shape`` is necessary like ``len(a)`` is for `irfft`,
|
1184 |
+
and for the same reason.)
|
1185 |
+
|
1186 |
+
The input should be ordered in the same way as is returned by `rfftn`,
|
1187 |
+
i.e., as for `irfft` for the final transformation axis, and as for `ifftn`
|
1188 |
+
along all the other axes.
|
1189 |
+
|
1190 |
+
Parameters
|
1191 |
+
----------
|
1192 |
+
x : array_like
|
1193 |
+
Input array.
|
1194 |
+
s : sequence of ints, optional
|
1195 |
+
Shape (length of each transformed axis) of the output
|
1196 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
|
1197 |
+
number of input points used along this axis, except for the last axis,
|
1198 |
+
where ``s[-1]//2+1`` points of the input are used.
|
1199 |
+
Along any axis, if the shape indicated by `s` is smaller than that of
|
1200 |
+
the input, the input is cropped. If it is larger, the input is padded
|
1201 |
+
with zeros. If `s` is not given, the shape of the input along the axes
|
1202 |
+
specified by axes is used. Except for the last axis which is taken to be
|
1203 |
+
``2*(m-1)``, where ``m`` is the length of the input along that axis.
|
1204 |
+
axes : sequence of ints, optional
|
1205 |
+
Axes over which to compute the inverse FFT. If not given, the last
|
1206 |
+
`len(s)` axes are used, or all axes if `s` is also not specified.
|
1207 |
+
norm : {"backward", "ortho", "forward"}, optional
|
1208 |
+
Normalization mode (see `fft`). Default is "backward".
|
1209 |
+
overwrite_x : bool, optional
|
1210 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
1211 |
+
See :func:`fft` for more details.
|
1212 |
+
workers : int, optional
|
1213 |
+
Maximum number of workers to use for parallel computation. If negative,
|
1214 |
+
the value wraps around from ``os.cpu_count()``.
|
1215 |
+
See :func:`~scipy.fft.fft` for more details.
|
1216 |
+
plan : object, optional
|
1217 |
+
This argument is reserved for passing in a precomputed plan provided
|
1218 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
1219 |
+
|
1220 |
+
.. versionadded:: 1.5.0
|
1221 |
+
|
1222 |
+
Returns
|
1223 |
+
-------
|
1224 |
+
out : ndarray
|
1225 |
+
The truncated or zero-padded input, transformed along the axes
|
1226 |
+
indicated by `axes`, or by a combination of `s` or `x`,
|
1227 |
+
as explained in the parameters section above.
|
1228 |
+
The length of each transformed axis is as given by the corresponding
|
1229 |
+
element of `s`, or the length of the input in every axis except for the
|
1230 |
+
last one if `s` is not given. In the final transformed axis the length
|
1231 |
+
of the output when `s` is not given is ``2*(m-1)``, where ``m`` is the
|
1232 |
+
length of the final transformed axis of the input. To get an odd
|
1233 |
+
number of output points in the final axis, `s` must be specified.
|
1234 |
+
|
1235 |
+
Raises
|
1236 |
+
------
|
1237 |
+
ValueError
|
1238 |
+
If `s` and `axes` have different length.
|
1239 |
+
IndexError
|
1240 |
+
If an element of `axes` is larger than the number of axes of `x`.
|
1241 |
+
|
1242 |
+
See Also
|
1243 |
+
--------
|
1244 |
+
rfftn : The forward N-D FFT of real input,
|
1245 |
+
of which `ifftn` is the inverse.
|
1246 |
+
fft : The 1-D FFT, with definitions and conventions used.
|
1247 |
+
irfft : The inverse of the 1-D FFT of real input.
|
1248 |
+
irfft2 : The inverse of the 2-D FFT of real input.
|
1249 |
+
|
1250 |
+
Notes
|
1251 |
+
-----
|
1252 |
+
See `fft` for definitions and conventions used.
|
1253 |
+
|
1254 |
+
See `rfft` for definitions and conventions used for real input.
|
1255 |
+
|
1256 |
+
The default value of `s` assumes an even output length in the final
|
1257 |
+
transformation axis. When performing the final complex to real
|
1258 |
+
transformation, the Hermitian symmetry requires that the last imaginary
|
1259 |
+
component along that axis must be 0 and so it is ignored. To avoid losing
|
1260 |
+
information, the correct length of the real input *must* be given.
|
1261 |
+
|
1262 |
+
Examples
|
1263 |
+
--------
|
1264 |
+
>>> import scipy.fft
|
1265 |
+
>>> import numpy as np
|
1266 |
+
>>> x = np.zeros((3, 2, 2))
|
1267 |
+
>>> x[0, 0, 0] = 3 * 2 * 2
|
1268 |
+
>>> scipy.fft.irfftn(x)
|
1269 |
+
array([[[1., 1.],
|
1270 |
+
[1., 1.]],
|
1271 |
+
[[1., 1.],
|
1272 |
+
[1., 1.]],
|
1273 |
+
[[1., 1.],
|
1274 |
+
[1., 1.]]])
|
1275 |
+
|
1276 |
+
"""
|
1277 |
+
return (Dispatchable(x, np.ndarray),)
|
1278 |
+
|
1279 |
+
|
1280 |
+
@_dispatch
|
1281 |
+
def irfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
|
1282 |
+
plan=None):
|
1283 |
+
"""
|
1284 |
+
Computes the inverse of `rfft2`
|
1285 |
+
|
1286 |
+
Parameters
|
1287 |
+
----------
|
1288 |
+
x : array_like
|
1289 |
+
The input array
|
1290 |
+
s : sequence of ints, optional
|
1291 |
+
Shape of the real output to the inverse FFT.
|
1292 |
+
axes : sequence of ints, optional
|
1293 |
+
The axes over which to compute the inverse fft.
|
1294 |
+
Default is the last two axes.
|
1295 |
+
norm : {"backward", "ortho", "forward"}, optional
|
1296 |
+
Normalization mode (see `fft`). Default is "backward".
|
1297 |
+
overwrite_x : bool, optional
|
1298 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
1299 |
+
See :func:`fft` for more details.
|
1300 |
+
workers : int, optional
|
1301 |
+
Maximum number of workers to use for parallel computation. If negative,
|
1302 |
+
the value wraps around from ``os.cpu_count()``.
|
1303 |
+
See :func:`~scipy.fft.fft` for more details.
|
1304 |
+
plan : object, optional
|
1305 |
+
This argument is reserved for passing in a precomputed plan provided
|
1306 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
1307 |
+
|
1308 |
+
.. versionadded:: 1.5.0
|
1309 |
+
|
1310 |
+
Returns
|
1311 |
+
-------
|
1312 |
+
out : ndarray
|
1313 |
+
The result of the inverse real 2-D FFT.
|
1314 |
+
|
1315 |
+
See Also
|
1316 |
+
--------
|
1317 |
+
rfft2 : The 2-D FFT of real input.
|
1318 |
+
irfft : The inverse of the 1-D FFT of real input.
|
1319 |
+
irfftn : The inverse of the N-D FFT of real input.
|
1320 |
+
|
1321 |
+
Notes
|
1322 |
+
-----
|
1323 |
+
This is really `irfftn` with different defaults.
|
1324 |
+
For more details see `irfftn`.
|
1325 |
+
|
1326 |
+
"""
|
1327 |
+
return (Dispatchable(x, np.ndarray),)
|
1328 |
+
|
1329 |
+
|
1330 |
+
@_dispatch
|
1331 |
+
def hfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
|
1332 |
+
plan=None):
|
1333 |
+
"""
|
1334 |
+
Compute the N-D FFT of Hermitian symmetric complex input, i.e., a
|
1335 |
+
signal with a real spectrum.
|
1336 |
+
|
1337 |
+
This function computes the N-D discrete Fourier Transform for a
|
1338 |
+
Hermitian symmetric complex input over any number of axes in an
|
1339 |
+
M-D array by means of the Fast Fourier Transform (FFT). In other
|
1340 |
+
words, ``ihfftn(hfftn(x, s)) == x`` to within numerical accuracy. (``s``
|
1341 |
+
here is ``x.shape`` with ``s[-1] = x.shape[-1] * 2 - 1``, this is necessary
|
1342 |
+
for the same reason ``x.shape`` would be necessary for `irfft`.)
|
1343 |
+
|
1344 |
+
Parameters
|
1345 |
+
----------
|
1346 |
+
x : array_like
|
1347 |
+
Input array.
|
1348 |
+
s : sequence of ints, optional
|
1349 |
+
Shape (length of each transformed axis) of the output
|
1350 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.). `s` is also the
|
1351 |
+
number of input points used along this axis, except for the last axis,
|
1352 |
+
where ``s[-1]//2+1`` points of the input are used.
|
1353 |
+
Along any axis, if the shape indicated by `s` is smaller than that of
|
1354 |
+
the input, the input is cropped. If it is larger, the input is padded
|
1355 |
+
with zeros. If `s` is not given, the shape of the input along the axes
|
1356 |
+
specified by axes is used. Except for the last axis which is taken to be
|
1357 |
+
``2*(m-1)`` where ``m`` is the length of the input along that axis.
|
1358 |
+
axes : sequence of ints, optional
|
1359 |
+
Axes over which to compute the inverse FFT. If not given, the last
|
1360 |
+
`len(s)` axes are used, or all axes if `s` is also not specified.
|
1361 |
+
norm : {"backward", "ortho", "forward"}, optional
|
1362 |
+
Normalization mode (see `fft`). Default is "backward".
|
1363 |
+
overwrite_x : bool, optional
|
1364 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
1365 |
+
See :func:`fft` for more details.
|
1366 |
+
workers : int, optional
|
1367 |
+
Maximum number of workers to use for parallel computation. If negative,
|
1368 |
+
the value wraps around from ``os.cpu_count()``.
|
1369 |
+
See :func:`~scipy.fft.fft` for more details.
|
1370 |
+
plan : object, optional
|
1371 |
+
This argument is reserved for passing in a precomputed plan provided
|
1372 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
1373 |
+
|
1374 |
+
.. versionadded:: 1.5.0
|
1375 |
+
|
1376 |
+
Returns
|
1377 |
+
-------
|
1378 |
+
out : ndarray
|
1379 |
+
The truncated or zero-padded input, transformed along the axes
|
1380 |
+
indicated by `axes`, or by a combination of `s` or `x`,
|
1381 |
+
as explained in the parameters section above.
|
1382 |
+
The length of each transformed axis is as given by the corresponding
|
1383 |
+
element of `s`, or the length of the input in every axis except for the
|
1384 |
+
last one if `s` is not given. In the final transformed axis the length
|
1385 |
+
of the output when `s` is not given is ``2*(m-1)`` where ``m`` is the
|
1386 |
+
length of the final transformed axis of the input. To get an odd
|
1387 |
+
number of output points in the final axis, `s` must be specified.
|
1388 |
+
|
1389 |
+
Raises
|
1390 |
+
------
|
1391 |
+
ValueError
|
1392 |
+
If `s` and `axes` have different length.
|
1393 |
+
IndexError
|
1394 |
+
If an element of `axes` is larger than the number of axes of `x`.
|
1395 |
+
|
1396 |
+
See Also
|
1397 |
+
--------
|
1398 |
+
ihfftn : The inverse N-D FFT with real spectrum. Inverse of `hfftn`.
|
1399 |
+
fft : The 1-D FFT, with definitions and conventions used.
|
1400 |
+
rfft : Forward FFT of real input.
|
1401 |
+
|
1402 |
+
Notes
|
1403 |
+
-----
|
1404 |
+
For a 1-D signal ``x`` to have a real spectrum, it must satisfy
|
1405 |
+
the Hermitian property::
|
1406 |
+
|
1407 |
+
x[i] == np.conj(x[-i]) for all i
|
1408 |
+
|
1409 |
+
This generalizes into higher dimensions by reflecting over each axis in
|
1410 |
+
turn::
|
1411 |
+
|
1412 |
+
x[i, j, k, ...] == np.conj(x[-i, -j, -k, ...]) for all i, j, k, ...
|
1413 |
+
|
1414 |
+
This should not be confused with a Hermitian matrix, for which the
|
1415 |
+
transpose is its own conjugate::
|
1416 |
+
|
1417 |
+
x[i, j] == np.conj(x[j, i]) for all i, j
|
1418 |
+
|
1419 |
+
|
1420 |
+
The default value of `s` assumes an even output length in the final
|
1421 |
+
transformation axis. When performing the final complex to real
|
1422 |
+
transformation, the Hermitian symmetry requires that the last imaginary
|
1423 |
+
component along that axis must be 0 and so it is ignored. To avoid losing
|
1424 |
+
information, the correct length of the real input *must* be given.
|
1425 |
+
|
1426 |
+
Examples
|
1427 |
+
--------
|
1428 |
+
>>> import scipy.fft
|
1429 |
+
>>> import numpy as np
|
1430 |
+
>>> x = np.ones((3, 2, 2))
|
1431 |
+
>>> scipy.fft.hfftn(x)
|
1432 |
+
array([[[12., 0.],
|
1433 |
+
[ 0., 0.]],
|
1434 |
+
[[ 0., 0.],
|
1435 |
+
[ 0., 0.]],
|
1436 |
+
[[ 0., 0.],
|
1437 |
+
[ 0., 0.]]])
|
1438 |
+
|
1439 |
+
"""
|
1440 |
+
return (Dispatchable(x, np.ndarray),)
|
1441 |
+
|
1442 |
+
|
1443 |
+
@_dispatch
|
1444 |
+
def hfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
|
1445 |
+
plan=None):
|
1446 |
+
"""
|
1447 |
+
Compute the 2-D FFT of a Hermitian complex array.
|
1448 |
+
|
1449 |
+
Parameters
|
1450 |
+
----------
|
1451 |
+
x : array
|
1452 |
+
Input array, taken to be Hermitian complex.
|
1453 |
+
s : sequence of ints, optional
|
1454 |
+
Shape of the real output.
|
1455 |
+
axes : sequence of ints, optional
|
1456 |
+
Axes over which to compute the FFT.
|
1457 |
+
norm : {"backward", "ortho", "forward"}, optional
|
1458 |
+
Normalization mode (see `fft`). Default is "backward".
|
1459 |
+
overwrite_x : bool, optional
|
1460 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
1461 |
+
See `fft` for more details.
|
1462 |
+
workers : int, optional
|
1463 |
+
Maximum number of workers to use for parallel computation. If negative,
|
1464 |
+
the value wraps around from ``os.cpu_count()``.
|
1465 |
+
See :func:`~scipy.fft.fft` for more details.
|
1466 |
+
plan : object, optional
|
1467 |
+
This argument is reserved for passing in a precomputed plan provided
|
1468 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
1469 |
+
|
1470 |
+
.. versionadded:: 1.5.0
|
1471 |
+
|
1472 |
+
Returns
|
1473 |
+
-------
|
1474 |
+
out : ndarray
|
1475 |
+
The real result of the 2-D Hermitian complex real FFT.
|
1476 |
+
|
1477 |
+
See Also
|
1478 |
+
--------
|
1479 |
+
hfftn : Compute the N-D discrete Fourier Transform for Hermitian
|
1480 |
+
complex input.
|
1481 |
+
|
1482 |
+
Notes
|
1483 |
+
-----
|
1484 |
+
This is really just `hfftn` with different default behavior.
|
1485 |
+
For more details see `hfftn`.
|
1486 |
+
|
1487 |
+
"""
|
1488 |
+
return (Dispatchable(x, np.ndarray),)
|
1489 |
+
|
1490 |
+
|
1491 |
+
@_dispatch
|
1492 |
+
def ihfftn(x, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *,
|
1493 |
+
plan=None):
|
1494 |
+
"""
|
1495 |
+
Compute the N-D inverse discrete Fourier Transform for a real
|
1496 |
+
spectrum.
|
1497 |
+
|
1498 |
+
This function computes the N-D inverse discrete Fourier Transform
|
1499 |
+
over any number of axes in an M-D real array by means of the Fast
|
1500 |
+
Fourier Transform (FFT). By default, all axes are transformed, with the
|
1501 |
+
real transform performed over the last axis, while the remaining transforms
|
1502 |
+
are complex.
|
1503 |
+
|
1504 |
+
Parameters
|
1505 |
+
----------
|
1506 |
+
x : array_like
|
1507 |
+
Input array, taken to be real.
|
1508 |
+
s : sequence of ints, optional
|
1509 |
+
Shape (length along each transformed axis) to use from the input.
|
1510 |
+
(``s[0]`` refers to axis 0, ``s[1]`` to axis 1, etc.).
|
1511 |
+
Along any axis, if the given shape is smaller than that of the input,
|
1512 |
+
the input is cropped. If it is larger, the input is padded with zeros.
|
1513 |
+
if `s` is not given, the shape of the input along the axes specified
|
1514 |
+
by `axes` is used.
|
1515 |
+
axes : sequence of ints, optional
|
1516 |
+
Axes over which to compute the FFT. If not given, the last ``len(s)``
|
1517 |
+
axes are used, or all axes if `s` is also not specified.
|
1518 |
+
norm : {"backward", "ortho", "forward"}, optional
|
1519 |
+
Normalization mode (see `fft`). Default is "backward".
|
1520 |
+
overwrite_x : bool, optional
|
1521 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
1522 |
+
See :func:`fft` for more details.
|
1523 |
+
workers : int, optional
|
1524 |
+
Maximum number of workers to use for parallel computation. If negative,
|
1525 |
+
the value wraps around from ``os.cpu_count()``.
|
1526 |
+
See :func:`~scipy.fft.fft` for more details.
|
1527 |
+
plan : object, optional
|
1528 |
+
This argument is reserved for passing in a precomputed plan provided
|
1529 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
1530 |
+
|
1531 |
+
.. versionadded:: 1.5.0
|
1532 |
+
|
1533 |
+
Returns
|
1534 |
+
-------
|
1535 |
+
out : complex ndarray
|
1536 |
+
The truncated or zero-padded input, transformed along the axes
|
1537 |
+
indicated by `axes`, or by a combination of `s` and `x`,
|
1538 |
+
as explained in the parameters section above.
|
1539 |
+
The length of the last axis transformed will be ``s[-1]//2+1``,
|
1540 |
+
while the remaining transformed axes will have lengths according to
|
1541 |
+
`s`, or unchanged from the input.
|
1542 |
+
|
1543 |
+
Raises
|
1544 |
+
------
|
1545 |
+
ValueError
|
1546 |
+
If `s` and `axes` have different length.
|
1547 |
+
IndexError
|
1548 |
+
If an element of `axes` is larger than the number of axes of `x`.
|
1549 |
+
|
1550 |
+
See Also
|
1551 |
+
--------
|
1552 |
+
hfftn : The forward N-D FFT of Hermitian input.
|
1553 |
+
hfft : The 1-D FFT of Hermitian input.
|
1554 |
+
fft : The 1-D FFT, with definitions and conventions used.
|
1555 |
+
fftn : The N-D FFT.
|
1556 |
+
hfft2 : The 2-D FFT of Hermitian input.
|
1557 |
+
|
1558 |
+
Notes
|
1559 |
+
-----
|
1560 |
+
The transform for real input is performed over the last transformation
|
1561 |
+
axis, as by `ihfft`, then the transform over the remaining axes is
|
1562 |
+
performed as by `ifftn`. The order of the output is the positive part of
|
1563 |
+
the Hermitian output signal, in the same format as `rfft`.
|
1564 |
+
|
1565 |
+
Examples
|
1566 |
+
--------
|
1567 |
+
>>> import scipy.fft
|
1568 |
+
>>> import numpy as np
|
1569 |
+
>>> x = np.ones((2, 2, 2))
|
1570 |
+
>>> scipy.fft.ihfftn(x)
|
1571 |
+
array([[[1.+0.j, 0.+0.j], # may vary
|
1572 |
+
[0.+0.j, 0.+0.j]],
|
1573 |
+
[[0.+0.j, 0.+0.j],
|
1574 |
+
[0.+0.j, 0.+0.j]]])
|
1575 |
+
>>> scipy.fft.ihfftn(x, axes=(2, 0))
|
1576 |
+
array([[[1.+0.j, 0.+0.j], # may vary
|
1577 |
+
[1.+0.j, 0.+0.j]],
|
1578 |
+
[[0.+0.j, 0.+0.j],
|
1579 |
+
[0.+0.j, 0.+0.j]]])
|
1580 |
+
|
1581 |
+
"""
|
1582 |
+
return (Dispatchable(x, np.ndarray),)
|
1583 |
+
|
1584 |
+
|
1585 |
+
@_dispatch
|
1586 |
+
def ihfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, workers=None, *,
|
1587 |
+
plan=None):
|
1588 |
+
"""
|
1589 |
+
Compute the 2-D inverse FFT of a real spectrum.
|
1590 |
+
|
1591 |
+
Parameters
|
1592 |
+
----------
|
1593 |
+
x : array_like
|
1594 |
+
The input array
|
1595 |
+
s : sequence of ints, optional
|
1596 |
+
Shape of the real input to the inverse FFT.
|
1597 |
+
axes : sequence of ints, optional
|
1598 |
+
The axes over which to compute the inverse fft.
|
1599 |
+
Default is the last two axes.
|
1600 |
+
norm : {"backward", "ortho", "forward"}, optional
|
1601 |
+
Normalization mode (see `fft`). Default is "backward".
|
1602 |
+
overwrite_x : bool, optional
|
1603 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
1604 |
+
See :func:`fft` for more details.
|
1605 |
+
workers : int, optional
|
1606 |
+
Maximum number of workers to use for parallel computation. If negative,
|
1607 |
+
the value wraps around from ``os.cpu_count()``.
|
1608 |
+
See :func:`~scipy.fft.fft` for more details.
|
1609 |
+
plan : object, optional
|
1610 |
+
This argument is reserved for passing in a precomputed plan provided
|
1611 |
+
by downstream FFT vendors. It is currently not used in SciPy.
|
1612 |
+
|
1613 |
+
.. versionadded:: 1.5.0
|
1614 |
+
|
1615 |
+
Returns
|
1616 |
+
-------
|
1617 |
+
out : ndarray
|
1618 |
+
The result of the inverse real 2-D FFT.
|
1619 |
+
|
1620 |
+
See Also
|
1621 |
+
--------
|
1622 |
+
ihfftn : Compute the inverse of the N-D FFT of Hermitian input.
|
1623 |
+
|
1624 |
+
Notes
|
1625 |
+
-----
|
1626 |
+
This is really `ihfftn` with different defaults.
|
1627 |
+
For more details see `ihfftn`.
|
1628 |
+
|
1629 |
+
"""
|
1630 |
+
return (Dispatchable(x, np.ndarray),)
|
venv/lib/python3.10/site-packages/scipy/fft/_basic_backend.py
ADDED
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from scipy._lib._array_api import (
|
2 |
+
array_namespace, is_numpy, xp_unsupported_param_msg, is_complex
|
3 |
+
)
|
4 |
+
from . import _pocketfft
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
|
8 |
+
def _validate_fft_args(workers, plan, norm):
|
9 |
+
if workers is not None:
|
10 |
+
raise ValueError(xp_unsupported_param_msg("workers"))
|
11 |
+
if plan is not None:
|
12 |
+
raise ValueError(xp_unsupported_param_msg("plan"))
|
13 |
+
if norm is None:
|
14 |
+
norm = 'backward'
|
15 |
+
return norm
|
16 |
+
|
17 |
+
|
18 |
+
# pocketfft is used whenever SCIPY_ARRAY_API is not set,
|
19 |
+
# or x is a NumPy array or array-like.
|
20 |
+
# When SCIPY_ARRAY_API is set, we try to use xp.fft for CuPy arrays,
|
21 |
+
# PyTorch arrays and other array API standard supporting objects.
|
22 |
+
# If xp.fft does not exist, we attempt to convert to np and back to use pocketfft.
|
23 |
+
|
24 |
+
def _execute_1D(func_str, pocketfft_func, x, n, axis, norm, overwrite_x, workers, plan):
|
25 |
+
xp = array_namespace(x)
|
26 |
+
|
27 |
+
if is_numpy(xp):
|
28 |
+
return pocketfft_func(x, n=n, axis=axis, norm=norm,
|
29 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
30 |
+
|
31 |
+
norm = _validate_fft_args(workers, plan, norm)
|
32 |
+
if hasattr(xp, 'fft'):
|
33 |
+
xp_func = getattr(xp.fft, func_str)
|
34 |
+
return xp_func(x, n=n, axis=axis, norm=norm)
|
35 |
+
|
36 |
+
x = np.asarray(x)
|
37 |
+
y = pocketfft_func(x, n=n, axis=axis, norm=norm)
|
38 |
+
return xp.asarray(y)
|
39 |
+
|
40 |
+
|
41 |
+
def _execute_nD(func_str, pocketfft_func, x, s, axes, norm, overwrite_x, workers, plan):
|
42 |
+
xp = array_namespace(x)
|
43 |
+
|
44 |
+
if is_numpy(xp):
|
45 |
+
return pocketfft_func(x, s=s, axes=axes, norm=norm,
|
46 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
47 |
+
|
48 |
+
norm = _validate_fft_args(workers, plan, norm)
|
49 |
+
if hasattr(xp, 'fft'):
|
50 |
+
xp_func = getattr(xp.fft, func_str)
|
51 |
+
return xp_func(x, s=s, axes=axes, norm=norm)
|
52 |
+
|
53 |
+
x = np.asarray(x)
|
54 |
+
y = pocketfft_func(x, s=s, axes=axes, norm=norm)
|
55 |
+
return xp.asarray(y)
|
56 |
+
|
57 |
+
|
58 |
+
def fft(x, n=None, axis=-1, norm=None,
|
59 |
+
overwrite_x=False, workers=None, *, plan=None):
|
60 |
+
return _execute_1D('fft', _pocketfft.fft, x, n=n, axis=axis, norm=norm,
|
61 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
62 |
+
|
63 |
+
|
64 |
+
def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, workers=None, *,
|
65 |
+
plan=None):
|
66 |
+
return _execute_1D('ifft', _pocketfft.ifft, x, n=n, axis=axis, norm=norm,
|
67 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
68 |
+
|
69 |
+
|
70 |
+
def rfft(x, n=None, axis=-1, norm=None,
|
71 |
+
overwrite_x=False, workers=None, *, plan=None):
|
72 |
+
return _execute_1D('rfft', _pocketfft.rfft, x, n=n, axis=axis, norm=norm,
|
73 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
74 |
+
|
75 |
+
|
76 |
+
def irfft(x, n=None, axis=-1, norm=None,
|
77 |
+
overwrite_x=False, workers=None, *, plan=None):
|
78 |
+
return _execute_1D('irfft', _pocketfft.irfft, x, n=n, axis=axis, norm=norm,
|
79 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
80 |
+
|
81 |
+
|
82 |
+
def hfft(x, n=None, axis=-1, norm=None,
|
83 |
+
overwrite_x=False, workers=None, *, plan=None):
|
84 |
+
return _execute_1D('hfft', _pocketfft.hfft, x, n=n, axis=axis, norm=norm,
|
85 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
86 |
+
|
87 |
+
|
88 |
+
def ihfft(x, n=None, axis=-1, norm=None,
|
89 |
+
overwrite_x=False, workers=None, *, plan=None):
|
90 |
+
return _execute_1D('ihfft', _pocketfft.ihfft, x, n=n, axis=axis, norm=norm,
|
91 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
92 |
+
|
93 |
+
|
94 |
+
def fftn(x, s=None, axes=None, norm=None,
|
95 |
+
overwrite_x=False, workers=None, *, plan=None):
|
96 |
+
return _execute_nD('fftn', _pocketfft.fftn, x, s=s, axes=axes, norm=norm,
|
97 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
98 |
+
|
99 |
+
|
100 |
+
|
101 |
+
def ifftn(x, s=None, axes=None, norm=None,
|
102 |
+
overwrite_x=False, workers=None, *, plan=None):
|
103 |
+
return _execute_nD('ifftn', _pocketfft.ifftn, x, s=s, axes=axes, norm=norm,
|
104 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
105 |
+
|
106 |
+
|
107 |
+
def fft2(x, s=None, axes=(-2, -1), norm=None,
|
108 |
+
overwrite_x=False, workers=None, *, plan=None):
|
109 |
+
return fftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
|
110 |
+
|
111 |
+
|
112 |
+
def ifft2(x, s=None, axes=(-2, -1), norm=None,
|
113 |
+
overwrite_x=False, workers=None, *, plan=None):
|
114 |
+
return ifftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
|
115 |
+
|
116 |
+
|
117 |
+
def rfftn(x, s=None, axes=None, norm=None,
|
118 |
+
overwrite_x=False, workers=None, *, plan=None):
|
119 |
+
return _execute_nD('rfftn', _pocketfft.rfftn, x, s=s, axes=axes, norm=norm,
|
120 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
121 |
+
|
122 |
+
|
123 |
+
def rfft2(x, s=None, axes=(-2, -1), norm=None,
|
124 |
+
overwrite_x=False, workers=None, *, plan=None):
|
125 |
+
return rfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
|
126 |
+
|
127 |
+
|
128 |
+
def irfftn(x, s=None, axes=None, norm=None,
|
129 |
+
overwrite_x=False, workers=None, *, plan=None):
|
130 |
+
return _execute_nD('irfftn', _pocketfft.irfftn, x, s=s, axes=axes, norm=norm,
|
131 |
+
overwrite_x=overwrite_x, workers=workers, plan=plan)
|
132 |
+
|
133 |
+
|
134 |
+
def irfft2(x, s=None, axes=(-2, -1), norm=None,
|
135 |
+
overwrite_x=False, workers=None, *, plan=None):
|
136 |
+
return irfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
|
137 |
+
|
138 |
+
|
139 |
+
def _swap_direction(norm):
|
140 |
+
if norm in (None, 'backward'):
|
141 |
+
norm = 'forward'
|
142 |
+
elif norm == 'forward':
|
143 |
+
norm = 'backward'
|
144 |
+
elif norm != 'ortho':
|
145 |
+
raise ValueError('Invalid norm value %s; should be "backward", '
|
146 |
+
'"ortho", or "forward".' % norm)
|
147 |
+
return norm
|
148 |
+
|
149 |
+
|
150 |
+
def hfftn(x, s=None, axes=None, norm=None,
|
151 |
+
overwrite_x=False, workers=None, *, plan=None):
|
152 |
+
xp = array_namespace(x)
|
153 |
+
if is_numpy(xp):
|
154 |
+
return _pocketfft.hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
|
155 |
+
if is_complex(x, xp):
|
156 |
+
x = xp.conj(x)
|
157 |
+
return irfftn(x, s, axes, _swap_direction(norm),
|
158 |
+
overwrite_x, workers, plan=plan)
|
159 |
+
|
160 |
+
|
161 |
+
def hfft2(x, s=None, axes=(-2, -1), norm=None,
|
162 |
+
overwrite_x=False, workers=None, *, plan=None):
|
163 |
+
return hfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
|
164 |
+
|
165 |
+
|
166 |
+
def ihfftn(x, s=None, axes=None, norm=None,
|
167 |
+
overwrite_x=False, workers=None, *, plan=None):
|
168 |
+
xp = array_namespace(x)
|
169 |
+
if is_numpy(xp):
|
170 |
+
return _pocketfft.ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
|
171 |
+
return xp.conj(rfftn(x, s, axes, _swap_direction(norm),
|
172 |
+
overwrite_x, workers, plan=plan))
|
173 |
+
|
174 |
+
def ihfft2(x, s=None, axes=(-2, -1), norm=None,
|
175 |
+
overwrite_x=False, workers=None, *, plan=None):
|
176 |
+
return ihfftn(x, s, axes, norm, overwrite_x, workers, plan=plan)
|
venv/lib/python3.10/site-packages/scipy/fft/_debug_backends.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
|
3 |
+
class NumPyBackend:
|
4 |
+
"""Backend that uses numpy.fft"""
|
5 |
+
__ua_domain__ = "numpy.scipy.fft"
|
6 |
+
|
7 |
+
@staticmethod
|
8 |
+
def __ua_function__(method, args, kwargs):
|
9 |
+
kwargs.pop("overwrite_x", None)
|
10 |
+
|
11 |
+
fn = getattr(np.fft, method.__name__, None)
|
12 |
+
return (NotImplemented if fn is None
|
13 |
+
else fn(*args, **kwargs))
|
14 |
+
|
15 |
+
|
16 |
+
class EchoBackend:
|
17 |
+
"""Backend that just prints the __ua_function__ arguments"""
|
18 |
+
__ua_domain__ = "numpy.scipy.fft"
|
19 |
+
|
20 |
+
@staticmethod
|
21 |
+
def __ua_function__(method, args, kwargs):
|
22 |
+
print(method, args, kwargs, sep='\n')
|
venv/lib/python3.10/site-packages/scipy/fft/_fftlog.py
ADDED
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Fast Hankel transforms using the FFTLog algorithm.
|
2 |
+
|
3 |
+
The implementation closely follows the Fortran code of Hamilton (2000).
|
4 |
+
|
5 |
+
added: 14/11/2020 Nicolas Tessore <[email protected]>
|
6 |
+
"""
|
7 |
+
|
8 |
+
from ._basic import _dispatch
|
9 |
+
from scipy._lib.uarray import Dispatchable
|
10 |
+
from ._fftlog_backend import fhtoffset
|
11 |
+
import numpy as np
|
12 |
+
|
13 |
+
__all__ = ['fht', 'ifht', 'fhtoffset']
|
14 |
+
|
15 |
+
|
16 |
+
@_dispatch
|
17 |
+
def fht(a, dln, mu, offset=0.0, bias=0.0):
|
18 |
+
r'''Compute the fast Hankel transform.
|
19 |
+
|
20 |
+
Computes the discrete Hankel transform of a logarithmically spaced periodic
|
21 |
+
sequence using the FFTLog algorithm [1]_, [2]_.
|
22 |
+
|
23 |
+
Parameters
|
24 |
+
----------
|
25 |
+
a : array_like (..., n)
|
26 |
+
Real periodic input array, uniformly logarithmically spaced. For
|
27 |
+
multidimensional input, the transform is performed over the last axis.
|
28 |
+
dln : float
|
29 |
+
Uniform logarithmic spacing of the input array.
|
30 |
+
mu : float
|
31 |
+
Order of the Hankel transform, any positive or negative real number.
|
32 |
+
offset : float, optional
|
33 |
+
Offset of the uniform logarithmic spacing of the output array.
|
34 |
+
bias : float, optional
|
35 |
+
Exponent of power law bias, any positive or negative real number.
|
36 |
+
|
37 |
+
Returns
|
38 |
+
-------
|
39 |
+
A : array_like (..., n)
|
40 |
+
The transformed output array, which is real, periodic, uniformly
|
41 |
+
logarithmically spaced, and of the same shape as the input array.
|
42 |
+
|
43 |
+
See Also
|
44 |
+
--------
|
45 |
+
ifht : The inverse of `fht`.
|
46 |
+
fhtoffset : Return an optimal offset for `fht`.
|
47 |
+
|
48 |
+
Notes
|
49 |
+
-----
|
50 |
+
This function computes a discrete version of the Hankel transform
|
51 |
+
|
52 |
+
.. math::
|
53 |
+
|
54 |
+
A(k) = \int_{0}^{\infty} \! a(r) \, J_\mu(kr) \, k \, dr \;,
|
55 |
+
|
56 |
+
where :math:`J_\mu` is the Bessel function of order :math:`\mu`. The index
|
57 |
+
:math:`\mu` may be any real number, positive or negative. Note that the
|
58 |
+
numerical Hankel transform uses an integrand of :math:`k \, dr`, while the
|
59 |
+
mathematical Hankel transform is commonly defined using :math:`r \, dr`.
|
60 |
+
|
61 |
+
The input array `a` is a periodic sequence of length :math:`n`, uniformly
|
62 |
+
logarithmically spaced with spacing `dln`,
|
63 |
+
|
64 |
+
.. math::
|
65 |
+
|
66 |
+
a_j = a(r_j) \;, \quad
|
67 |
+
r_j = r_c \exp[(j-j_c) \, \mathtt{dln}]
|
68 |
+
|
69 |
+
centred about the point :math:`r_c`. Note that the central index
|
70 |
+
:math:`j_c = (n-1)/2` is half-integral if :math:`n` is even, so that
|
71 |
+
:math:`r_c` falls between two input elements. Similarly, the output
|
72 |
+
array `A` is a periodic sequence of length :math:`n`, also uniformly
|
73 |
+
logarithmically spaced with spacing `dln`
|
74 |
+
|
75 |
+
.. math::
|
76 |
+
|
77 |
+
A_j = A(k_j) \;, \quad
|
78 |
+
k_j = k_c \exp[(j-j_c) \, \mathtt{dln}]
|
79 |
+
|
80 |
+
centred about the point :math:`k_c`.
|
81 |
+
|
82 |
+
The centre points :math:`r_c` and :math:`k_c` of the periodic intervals may
|
83 |
+
be chosen arbitrarily, but it would be usual to choose the product
|
84 |
+
:math:`k_c r_c = k_j r_{n-1-j} = k_{n-1-j} r_j` to be unity. This can be
|
85 |
+
changed using the `offset` parameter, which controls the logarithmic offset
|
86 |
+
:math:`\log(k_c) = \mathtt{offset} - \log(r_c)` of the output array.
|
87 |
+
Choosing an optimal value for `offset` may reduce ringing of the discrete
|
88 |
+
Hankel transform.
|
89 |
+
|
90 |
+
If the `bias` parameter is nonzero, this function computes a discrete
|
91 |
+
version of the biased Hankel transform
|
92 |
+
|
93 |
+
.. math::
|
94 |
+
|
95 |
+
A(k) = \int_{0}^{\infty} \! a_q(r) \, (kr)^q \, J_\mu(kr) \, k \, dr
|
96 |
+
|
97 |
+
where :math:`q` is the value of `bias`, and a power law bias
|
98 |
+
:math:`a_q(r) = a(r) \, (kr)^{-q}` is applied to the input sequence.
|
99 |
+
Biasing the transform can help approximate the continuous transform of
|
100 |
+
:math:`a(r)` if there is a value :math:`q` such that :math:`a_q(r)` is
|
101 |
+
close to a periodic sequence, in which case the resulting :math:`A(k)` will
|
102 |
+
be close to the continuous transform.
|
103 |
+
|
104 |
+
References
|
105 |
+
----------
|
106 |
+
.. [1] Talman J. D., 1978, J. Comp. Phys., 29, 35
|
107 |
+
.. [2] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
|
108 |
+
|
109 |
+
Examples
|
110 |
+
--------
|
111 |
+
|
112 |
+
This example is the adapted version of ``fftlogtest.f`` which is provided
|
113 |
+
in [2]_. It evaluates the integral
|
114 |
+
|
115 |
+
.. math::
|
116 |
+
|
117 |
+
\int^\infty_0 r^{\mu+1} \exp(-r^2/2) J_\mu(k, r) k dr
|
118 |
+
= k^{\mu+1} \exp(-k^2/2) .
|
119 |
+
|
120 |
+
>>> import numpy as np
|
121 |
+
>>> from scipy import fft
|
122 |
+
>>> import matplotlib.pyplot as plt
|
123 |
+
|
124 |
+
Parameters for the transform.
|
125 |
+
|
126 |
+
>>> mu = 0.0 # Order mu of Bessel function
|
127 |
+
>>> r = np.logspace(-7, 1, 128) # Input evaluation points
|
128 |
+
>>> dln = np.log(r[1]/r[0]) # Step size
|
129 |
+
>>> offset = fft.fhtoffset(dln, initial=-6*np.log(10), mu=mu)
|
130 |
+
>>> k = np.exp(offset)/r[::-1] # Output evaluation points
|
131 |
+
|
132 |
+
Define the analytical function.
|
133 |
+
|
134 |
+
>>> def f(x, mu):
|
135 |
+
... """Analytical function: x^(mu+1) exp(-x^2/2)."""
|
136 |
+
... return x**(mu + 1)*np.exp(-x**2/2)
|
137 |
+
|
138 |
+
Evaluate the function at ``r`` and compute the corresponding values at
|
139 |
+
``k`` using FFTLog.
|
140 |
+
|
141 |
+
>>> a_r = f(r, mu)
|
142 |
+
>>> fht = fft.fht(a_r, dln, mu=mu, offset=offset)
|
143 |
+
|
144 |
+
For this example we can actually compute the analytical response (which in
|
145 |
+
this case is the same as the input function) for comparison and compute the
|
146 |
+
relative error.
|
147 |
+
|
148 |
+
>>> a_k = f(k, mu)
|
149 |
+
>>> rel_err = abs((fht-a_k)/a_k)
|
150 |
+
|
151 |
+
Plot the result.
|
152 |
+
|
153 |
+
>>> figargs = {'sharex': True, 'sharey': True, 'constrained_layout': True}
|
154 |
+
>>> fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), **figargs)
|
155 |
+
>>> ax1.set_title(r'$r^{\mu+1}\ \exp(-r^2/2)$')
|
156 |
+
>>> ax1.loglog(r, a_r, 'k', lw=2)
|
157 |
+
>>> ax1.set_xlabel('r')
|
158 |
+
>>> ax2.set_title(r'$k^{\mu+1} \exp(-k^2/2)$')
|
159 |
+
>>> ax2.loglog(k, a_k, 'k', lw=2, label='Analytical')
|
160 |
+
>>> ax2.loglog(k, fht, 'C3--', lw=2, label='FFTLog')
|
161 |
+
>>> ax2.set_xlabel('k')
|
162 |
+
>>> ax2.legend(loc=3, framealpha=1)
|
163 |
+
>>> ax2.set_ylim([1e-10, 1e1])
|
164 |
+
>>> ax2b = ax2.twinx()
|
165 |
+
>>> ax2b.loglog(k, rel_err, 'C0', label='Rel. Error (-)')
|
166 |
+
>>> ax2b.set_ylabel('Rel. Error (-)', color='C0')
|
167 |
+
>>> ax2b.tick_params(axis='y', labelcolor='C0')
|
168 |
+
>>> ax2b.legend(loc=4, framealpha=1)
|
169 |
+
>>> ax2b.set_ylim([1e-9, 1e-3])
|
170 |
+
>>> plt.show()
|
171 |
+
|
172 |
+
'''
|
173 |
+
return (Dispatchable(a, np.ndarray),)
|
174 |
+
|
175 |
+
|
176 |
+
@_dispatch
|
177 |
+
def ifht(A, dln, mu, offset=0.0, bias=0.0):
|
178 |
+
r"""Compute the inverse fast Hankel transform.
|
179 |
+
|
180 |
+
Computes the discrete inverse Hankel transform of a logarithmically spaced
|
181 |
+
periodic sequence. This is the inverse operation to `fht`.
|
182 |
+
|
183 |
+
Parameters
|
184 |
+
----------
|
185 |
+
A : array_like (..., n)
|
186 |
+
Real periodic input array, uniformly logarithmically spaced. For
|
187 |
+
multidimensional input, the transform is performed over the last axis.
|
188 |
+
dln : float
|
189 |
+
Uniform logarithmic spacing of the input array.
|
190 |
+
mu : float
|
191 |
+
Order of the Hankel transform, any positive or negative real number.
|
192 |
+
offset : float, optional
|
193 |
+
Offset of the uniform logarithmic spacing of the output array.
|
194 |
+
bias : float, optional
|
195 |
+
Exponent of power law bias, any positive or negative real number.
|
196 |
+
|
197 |
+
Returns
|
198 |
+
-------
|
199 |
+
a : array_like (..., n)
|
200 |
+
The transformed output array, which is real, periodic, uniformly
|
201 |
+
logarithmically spaced, and of the same shape as the input array.
|
202 |
+
|
203 |
+
See Also
|
204 |
+
--------
|
205 |
+
fht : Definition of the fast Hankel transform.
|
206 |
+
fhtoffset : Return an optimal offset for `ifht`.
|
207 |
+
|
208 |
+
Notes
|
209 |
+
-----
|
210 |
+
This function computes a discrete version of the Hankel transform
|
211 |
+
|
212 |
+
.. math::
|
213 |
+
|
214 |
+
a(r) = \int_{0}^{\infty} \! A(k) \, J_\mu(kr) \, r \, dk \;,
|
215 |
+
|
216 |
+
where :math:`J_\mu` is the Bessel function of order :math:`\mu`. The index
|
217 |
+
:math:`\mu` may be any real number, positive or negative. Note that the
|
218 |
+
numerical inverse Hankel transform uses an integrand of :math:`r \, dk`, while the
|
219 |
+
mathematical inverse Hankel transform is commonly defined using :math:`k \, dk`.
|
220 |
+
|
221 |
+
See `fht` for further details.
|
222 |
+
"""
|
223 |
+
return (Dispatchable(A, np.ndarray),)
|
venv/lib/python3.10/site-packages/scipy/fft/_fftlog_backend.py
ADDED
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from warnings import warn
|
3 |
+
from ._basic import rfft, irfft
|
4 |
+
from ..special import loggamma, poch
|
5 |
+
|
6 |
+
from scipy._lib._array_api import array_namespace, copy
|
7 |
+
|
8 |
+
__all__ = ['fht', 'ifht', 'fhtoffset']
|
9 |
+
|
10 |
+
# constants
|
11 |
+
LN_2 = np.log(2)
|
12 |
+
|
13 |
+
|
14 |
+
def fht(a, dln, mu, offset=0.0, bias=0.0):
|
15 |
+
xp = array_namespace(a)
|
16 |
+
|
17 |
+
# size of transform
|
18 |
+
n = a.shape[-1]
|
19 |
+
|
20 |
+
# bias input array
|
21 |
+
if bias != 0:
|
22 |
+
# a_q(r) = a(r) (r/r_c)^{-q}
|
23 |
+
j_c = (n-1)/2
|
24 |
+
j = xp.arange(n, dtype=xp.float64)
|
25 |
+
a = a * xp.exp(-bias*(j - j_c)*dln)
|
26 |
+
|
27 |
+
# compute FHT coefficients
|
28 |
+
u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias))
|
29 |
+
|
30 |
+
# transform
|
31 |
+
A = _fhtq(a, u, xp=xp)
|
32 |
+
|
33 |
+
# bias output array
|
34 |
+
if bias != 0:
|
35 |
+
# A(k) = A_q(k) (k/k_c)^{-q} (k_c r_c)^{-q}
|
36 |
+
A *= xp.exp(-bias*((j - j_c)*dln + offset))
|
37 |
+
|
38 |
+
return A
|
39 |
+
|
40 |
+
|
41 |
+
def ifht(A, dln, mu, offset=0.0, bias=0.0):
|
42 |
+
xp = array_namespace(A)
|
43 |
+
|
44 |
+
# size of transform
|
45 |
+
n = A.shape[-1]
|
46 |
+
|
47 |
+
# bias input array
|
48 |
+
if bias != 0:
|
49 |
+
# A_q(k) = A(k) (k/k_c)^{q} (k_c r_c)^{q}
|
50 |
+
j_c = (n-1)/2
|
51 |
+
j = xp.arange(n, dtype=xp.float64)
|
52 |
+
A = A * xp.exp(bias*((j - j_c)*dln + offset))
|
53 |
+
|
54 |
+
# compute FHT coefficients
|
55 |
+
u = xp.asarray(fhtcoeff(n, dln, mu, offset=offset, bias=bias, inverse=True))
|
56 |
+
|
57 |
+
# transform
|
58 |
+
a = _fhtq(A, u, inverse=True, xp=xp)
|
59 |
+
|
60 |
+
# bias output array
|
61 |
+
if bias != 0:
|
62 |
+
# a(r) = a_q(r) (r/r_c)^{q}
|
63 |
+
a /= xp.exp(-bias*(j - j_c)*dln)
|
64 |
+
|
65 |
+
return a
|
66 |
+
|
67 |
+
|
68 |
+
def fhtcoeff(n, dln, mu, offset=0.0, bias=0.0, inverse=False):
|
69 |
+
"""Compute the coefficient array for a fast Hankel transform."""
|
70 |
+
lnkr, q = offset, bias
|
71 |
+
|
72 |
+
# Hankel transform coefficients
|
73 |
+
# u_m = (kr)^{-i 2m pi/(n dlnr)} U_mu(q + i 2m pi/(n dlnr))
|
74 |
+
# with U_mu(x) = 2^x Gamma((mu+1+x)/2)/Gamma((mu+1-x)/2)
|
75 |
+
xp = (mu+1+q)/2
|
76 |
+
xm = (mu+1-q)/2
|
77 |
+
y = np.linspace(0, np.pi*(n//2)/(n*dln), n//2+1)
|
78 |
+
u = np.empty(n//2+1, dtype=complex)
|
79 |
+
v = np.empty(n//2+1, dtype=complex)
|
80 |
+
u.imag[:] = y
|
81 |
+
u.real[:] = xm
|
82 |
+
loggamma(u, out=v)
|
83 |
+
u.real[:] = xp
|
84 |
+
loggamma(u, out=u)
|
85 |
+
y *= 2*(LN_2 - lnkr)
|
86 |
+
u.real -= v.real
|
87 |
+
u.real += LN_2*q
|
88 |
+
u.imag += v.imag
|
89 |
+
u.imag += y
|
90 |
+
np.exp(u, out=u)
|
91 |
+
|
92 |
+
# fix last coefficient to be real
|
93 |
+
u.imag[-1] = 0
|
94 |
+
|
95 |
+
# deal with special cases
|
96 |
+
if not np.isfinite(u[0]):
|
97 |
+
# write u_0 = 2^q Gamma(xp)/Gamma(xm) = 2^q poch(xm, xp-xm)
|
98 |
+
# poch() handles special cases for negative integers correctly
|
99 |
+
u[0] = 2**q * poch(xm, xp-xm)
|
100 |
+
# the coefficient may be inf or 0, meaning the transform or the
|
101 |
+
# inverse transform, respectively, is singular
|
102 |
+
|
103 |
+
# check for singular transform or singular inverse transform
|
104 |
+
if np.isinf(u[0]) and not inverse:
|
105 |
+
warn('singular transform; consider changing the bias', stacklevel=3)
|
106 |
+
# fix coefficient to obtain (potentially correct) transform anyway
|
107 |
+
u = copy(u)
|
108 |
+
u[0] = 0
|
109 |
+
elif u[0] == 0 and inverse:
|
110 |
+
warn('singular inverse transform; consider changing the bias', stacklevel=3)
|
111 |
+
# fix coefficient to obtain (potentially correct) inverse anyway
|
112 |
+
u = copy(u)
|
113 |
+
u[0] = np.inf
|
114 |
+
|
115 |
+
return u
|
116 |
+
|
117 |
+
|
118 |
+
def fhtoffset(dln, mu, initial=0.0, bias=0.0):
|
119 |
+
"""Return optimal offset for a fast Hankel transform.
|
120 |
+
|
121 |
+
Returns an offset close to `initial` that fulfils the low-ringing
|
122 |
+
condition of [1]_ for the fast Hankel transform `fht` with logarithmic
|
123 |
+
spacing `dln`, order `mu` and bias `bias`.
|
124 |
+
|
125 |
+
Parameters
|
126 |
+
----------
|
127 |
+
dln : float
|
128 |
+
Uniform logarithmic spacing of the transform.
|
129 |
+
mu : float
|
130 |
+
Order of the Hankel transform, any positive or negative real number.
|
131 |
+
initial : float, optional
|
132 |
+
Initial value for the offset. Returns the closest value that fulfils
|
133 |
+
the low-ringing condition.
|
134 |
+
bias : float, optional
|
135 |
+
Exponent of power law bias, any positive or negative real number.
|
136 |
+
|
137 |
+
Returns
|
138 |
+
-------
|
139 |
+
offset : float
|
140 |
+
Optimal offset of the uniform logarithmic spacing of the transform that
|
141 |
+
fulfils a low-ringing condition.
|
142 |
+
|
143 |
+
Examples
|
144 |
+
--------
|
145 |
+
>>> from scipy.fft import fhtoffset
|
146 |
+
>>> dln = 0.1
|
147 |
+
>>> mu = 2.0
|
148 |
+
>>> initial = 0.5
|
149 |
+
>>> bias = 0.0
|
150 |
+
>>> offset = fhtoffset(dln, mu, initial, bias)
|
151 |
+
>>> offset
|
152 |
+
0.5454581477676637
|
153 |
+
|
154 |
+
See Also
|
155 |
+
--------
|
156 |
+
fht : Definition of the fast Hankel transform.
|
157 |
+
|
158 |
+
References
|
159 |
+
----------
|
160 |
+
.. [1] Hamilton A. J. S., 2000, MNRAS, 312, 257 (astro-ph/9905191)
|
161 |
+
|
162 |
+
"""
|
163 |
+
|
164 |
+
lnkr, q = initial, bias
|
165 |
+
|
166 |
+
xp = (mu+1+q)/2
|
167 |
+
xm = (mu+1-q)/2
|
168 |
+
y = np.pi/(2*dln)
|
169 |
+
zp = loggamma(xp + 1j*y)
|
170 |
+
zm = loggamma(xm + 1j*y)
|
171 |
+
arg = (LN_2 - lnkr)/dln + (zp.imag + zm.imag)/np.pi
|
172 |
+
return lnkr + (arg - np.round(arg))*dln
|
173 |
+
|
174 |
+
|
175 |
+
def _fhtq(a, u, inverse=False, *, xp=None):
|
176 |
+
"""Compute the biased fast Hankel transform.
|
177 |
+
|
178 |
+
This is the basic FFTLog routine.
|
179 |
+
"""
|
180 |
+
if xp is None:
|
181 |
+
xp = np
|
182 |
+
|
183 |
+
# size of transform
|
184 |
+
n = a.shape[-1]
|
185 |
+
|
186 |
+
# biased fast Hankel transform via real FFT
|
187 |
+
A = rfft(a, axis=-1)
|
188 |
+
if not inverse:
|
189 |
+
# forward transform
|
190 |
+
A *= u
|
191 |
+
else:
|
192 |
+
# backward transform
|
193 |
+
A /= xp.conj(u)
|
194 |
+
A = irfft(A, n, axis=-1)
|
195 |
+
A = xp.flip(A, axis=-1)
|
196 |
+
|
197 |
+
return A
|
venv/lib/python3.10/site-packages/scipy/fft/_helper.py
ADDED
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import update_wrapper, lru_cache
|
2 |
+
import inspect
|
3 |
+
|
4 |
+
from ._pocketfft import helper as _helper
|
5 |
+
|
6 |
+
import numpy as np
|
7 |
+
from scipy._lib._array_api import array_namespace
|
8 |
+
|
9 |
+
|
10 |
+
def next_fast_len(target, real=False):
|
11 |
+
"""Find the next fast size of input data to ``fft``, for zero-padding, etc.
|
12 |
+
|
13 |
+
SciPy's FFT algorithms gain their speed by a recursive divide and conquer
|
14 |
+
strategy. This relies on efficient functions for small prime factors of the
|
15 |
+
input length. Thus, the transforms are fastest when using composites of the
|
16 |
+
prime factors handled by the fft implementation. If there are efficient
|
17 |
+
functions for all radices <= `n`, then the result will be a number `x`
|
18 |
+
>= ``target`` with only prime factors < `n`. (Also known as `n`-smooth
|
19 |
+
numbers)
|
20 |
+
|
21 |
+
Parameters
|
22 |
+
----------
|
23 |
+
target : int
|
24 |
+
Length to start searching from. Must be a positive integer.
|
25 |
+
real : bool, optional
|
26 |
+
True if the FFT involves real input or output (e.g., `rfft` or `hfft`
|
27 |
+
but not `fft`). Defaults to False.
|
28 |
+
|
29 |
+
Returns
|
30 |
+
-------
|
31 |
+
out : int
|
32 |
+
The smallest fast length greater than or equal to ``target``.
|
33 |
+
|
34 |
+
Notes
|
35 |
+
-----
|
36 |
+
The result of this function may change in future as performance
|
37 |
+
considerations change, for example, if new prime factors are added.
|
38 |
+
|
39 |
+
Calling `fft` or `ifft` with real input data performs an ``'R2C'``
|
40 |
+
transform internally.
|
41 |
+
|
42 |
+
Examples
|
43 |
+
--------
|
44 |
+
On a particular machine, an FFT of prime length takes 11.4 ms:
|
45 |
+
|
46 |
+
>>> from scipy import fft
|
47 |
+
>>> import numpy as np
|
48 |
+
>>> rng = np.random.default_rng()
|
49 |
+
>>> min_len = 93059 # prime length is worst case for speed
|
50 |
+
>>> a = rng.standard_normal(min_len)
|
51 |
+
>>> b = fft.fft(a)
|
52 |
+
|
53 |
+
Zero-padding to the next regular length reduces computation time to
|
54 |
+
1.6 ms, a speedup of 7.3 times:
|
55 |
+
|
56 |
+
>>> fft.next_fast_len(min_len, real=True)
|
57 |
+
93312
|
58 |
+
>>> b = fft.fft(a, 93312)
|
59 |
+
|
60 |
+
Rounding up to the next power of 2 is not optimal, taking 3.0 ms to
|
61 |
+
compute; 1.9 times longer than the size given by ``next_fast_len``:
|
62 |
+
|
63 |
+
>>> b = fft.fft(a, 131072)
|
64 |
+
|
65 |
+
"""
|
66 |
+
pass
|
67 |
+
|
68 |
+
|
69 |
+
# Directly wrap the c-function good_size but take the docstring etc., from the
|
70 |
+
# next_fast_len function above
|
71 |
+
_sig = inspect.signature(next_fast_len)
|
72 |
+
next_fast_len = update_wrapper(lru_cache(_helper.good_size), next_fast_len)
|
73 |
+
next_fast_len.__wrapped__ = _helper.good_size
|
74 |
+
next_fast_len.__signature__ = _sig
|
75 |
+
|
76 |
+
|
77 |
+
def _init_nd_shape_and_axes(x, shape, axes):
|
78 |
+
"""Handle shape and axes arguments for N-D transforms.
|
79 |
+
|
80 |
+
Returns the shape and axes in a standard form, taking into account negative
|
81 |
+
values and checking for various potential errors.
|
82 |
+
|
83 |
+
Parameters
|
84 |
+
----------
|
85 |
+
x : array_like
|
86 |
+
The input array.
|
87 |
+
shape : int or array_like of ints or None
|
88 |
+
The shape of the result. If both `shape` and `axes` (see below) are
|
89 |
+
None, `shape` is ``x.shape``; if `shape` is None but `axes` is
|
90 |
+
not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
|
91 |
+
If `shape` is -1, the size of the corresponding dimension of `x` is
|
92 |
+
used.
|
93 |
+
axes : int or array_like of ints or None
|
94 |
+
Axes along which the calculation is computed.
|
95 |
+
The default is over all axes.
|
96 |
+
Negative indices are automatically converted to their positive
|
97 |
+
counterparts.
|
98 |
+
|
99 |
+
Returns
|
100 |
+
-------
|
101 |
+
shape : tuple
|
102 |
+
The shape of the result as a tuple of integers.
|
103 |
+
axes : list
|
104 |
+
Axes along which the calculation is computed, as a list of integers.
|
105 |
+
|
106 |
+
"""
|
107 |
+
x = np.asarray(x)
|
108 |
+
return _helper._init_nd_shape_and_axes(x, shape, axes)
|
109 |
+
|
110 |
+
|
111 |
+
def fftfreq(n, d=1.0, *, xp=None, device=None):
|
112 |
+
"""Return the Discrete Fourier Transform sample frequencies.
|
113 |
+
|
114 |
+
The returned float array `f` contains the frequency bin centers in cycles
|
115 |
+
per unit of the sample spacing (with zero at the start). For instance, if
|
116 |
+
the sample spacing is in seconds, then the frequency unit is cycles/second.
|
117 |
+
|
118 |
+
Given a window length `n` and a sample spacing `d`::
|
119 |
+
|
120 |
+
f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is even
|
121 |
+
f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd
|
122 |
+
|
123 |
+
Parameters
|
124 |
+
----------
|
125 |
+
n : int
|
126 |
+
Window length.
|
127 |
+
d : scalar, optional
|
128 |
+
Sample spacing (inverse of the sampling rate). Defaults to 1.
|
129 |
+
xp : array_namespace, optional
|
130 |
+
The namespace for the return array. Default is None, where NumPy is used.
|
131 |
+
device : device, optional
|
132 |
+
The device for the return array.
|
133 |
+
Only valid when `xp.fft.fftfreq` implements the device parameter.
|
134 |
+
|
135 |
+
Returns
|
136 |
+
-------
|
137 |
+
f : ndarray
|
138 |
+
Array of length `n` containing the sample frequencies.
|
139 |
+
|
140 |
+
Examples
|
141 |
+
--------
|
142 |
+
>>> import numpy as np
|
143 |
+
>>> import scipy.fft
|
144 |
+
>>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
|
145 |
+
>>> fourier = scipy.fft.fft(signal)
|
146 |
+
>>> n = signal.size
|
147 |
+
>>> timestep = 0.1
|
148 |
+
>>> freq = scipy.fft.fftfreq(n, d=timestep)
|
149 |
+
>>> freq
|
150 |
+
array([ 0. , 1.25, 2.5 , ..., -3.75, -2.5 , -1.25])
|
151 |
+
|
152 |
+
"""
|
153 |
+
xp = np if xp is None else xp
|
154 |
+
# numpy does not yet support the `device` keyword
|
155 |
+
# `xp.__name__ != 'numpy'` should be removed when numpy is compatible
|
156 |
+
if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
|
157 |
+
return xp.fft.fftfreq(n, d=d, device=device)
|
158 |
+
if device is not None:
|
159 |
+
raise ValueError('device parameter is not supported for input array type')
|
160 |
+
return np.fft.fftfreq(n, d=d)
|
161 |
+
|
162 |
+
|
163 |
+
def rfftfreq(n, d=1.0, *, xp=None, device=None):
|
164 |
+
"""Return the Discrete Fourier Transform sample frequencies
|
165 |
+
(for usage with rfft, irfft).
|
166 |
+
|
167 |
+
The returned float array `f` contains the frequency bin centers in cycles
|
168 |
+
per unit of the sample spacing (with zero at the start). For instance, if
|
169 |
+
the sample spacing is in seconds, then the frequency unit is cycles/second.
|
170 |
+
|
171 |
+
Given a window length `n` and a sample spacing `d`::
|
172 |
+
|
173 |
+
f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even
|
174 |
+
f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd
|
175 |
+
|
176 |
+
Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`)
|
177 |
+
the Nyquist frequency component is considered to be positive.
|
178 |
+
|
179 |
+
Parameters
|
180 |
+
----------
|
181 |
+
n : int
|
182 |
+
Window length.
|
183 |
+
d : scalar, optional
|
184 |
+
Sample spacing (inverse of the sampling rate). Defaults to 1.
|
185 |
+
xp : array_namespace, optional
|
186 |
+
The namespace for the return array. Default is None, where NumPy is used.
|
187 |
+
device : device, optional
|
188 |
+
The device for the return array.
|
189 |
+
Only valid when `xp.fft.rfftfreq` implements the device parameter.
|
190 |
+
|
191 |
+
Returns
|
192 |
+
-------
|
193 |
+
f : ndarray
|
194 |
+
Array of length ``n//2 + 1`` containing the sample frequencies.
|
195 |
+
|
196 |
+
Examples
|
197 |
+
--------
|
198 |
+
>>> import numpy as np
|
199 |
+
>>> import scipy.fft
|
200 |
+
>>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
|
201 |
+
>>> fourier = scipy.fft.rfft(signal)
|
202 |
+
>>> n = signal.size
|
203 |
+
>>> sample_rate = 100
|
204 |
+
>>> freq = scipy.fft.fftfreq(n, d=1./sample_rate)
|
205 |
+
>>> freq
|
206 |
+
array([ 0., 10., 20., ..., -30., -20., -10.])
|
207 |
+
>>> freq = scipy.fft.rfftfreq(n, d=1./sample_rate)
|
208 |
+
>>> freq
|
209 |
+
array([ 0., 10., 20., 30., 40., 50.])
|
210 |
+
|
211 |
+
"""
|
212 |
+
xp = np if xp is None else xp
|
213 |
+
# numpy does not yet support the `device` keyword
|
214 |
+
# `xp.__name__ != 'numpy'` should be removed when numpy is compatible
|
215 |
+
if hasattr(xp, 'fft') and xp.__name__ != 'numpy':
|
216 |
+
return xp.fft.rfftfreq(n, d=d, device=device)
|
217 |
+
if device is not None:
|
218 |
+
raise ValueError('device parameter is not supported for input array type')
|
219 |
+
return np.fft.rfftfreq(n, d=d)
|
220 |
+
|
221 |
+
|
222 |
+
def fftshift(x, axes=None):
|
223 |
+
"""Shift the zero-frequency component to the center of the spectrum.
|
224 |
+
|
225 |
+
This function swaps half-spaces for all axes listed (defaults to all).
|
226 |
+
Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even.
|
227 |
+
|
228 |
+
Parameters
|
229 |
+
----------
|
230 |
+
x : array_like
|
231 |
+
Input array.
|
232 |
+
axes : int or shape tuple, optional
|
233 |
+
Axes over which to shift. Default is None, which shifts all axes.
|
234 |
+
|
235 |
+
Returns
|
236 |
+
-------
|
237 |
+
y : ndarray
|
238 |
+
The shifted array.
|
239 |
+
|
240 |
+
See Also
|
241 |
+
--------
|
242 |
+
ifftshift : The inverse of `fftshift`.
|
243 |
+
|
244 |
+
Examples
|
245 |
+
--------
|
246 |
+
>>> import numpy as np
|
247 |
+
>>> freqs = np.fft.fftfreq(10, 0.1)
|
248 |
+
>>> freqs
|
249 |
+
array([ 0., 1., 2., ..., -3., -2., -1.])
|
250 |
+
>>> np.fft.fftshift(freqs)
|
251 |
+
array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.])
|
252 |
+
|
253 |
+
Shift the zero-frequency component only along the second axis:
|
254 |
+
|
255 |
+
>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
|
256 |
+
>>> freqs
|
257 |
+
array([[ 0., 1., 2.],
|
258 |
+
[ 3., 4., -4.],
|
259 |
+
[-3., -2., -1.]])
|
260 |
+
>>> np.fft.fftshift(freqs, axes=(1,))
|
261 |
+
array([[ 2., 0., 1.],
|
262 |
+
[-4., 3., 4.],
|
263 |
+
[-1., -3., -2.]])
|
264 |
+
|
265 |
+
"""
|
266 |
+
xp = array_namespace(x)
|
267 |
+
if hasattr(xp, 'fft'):
|
268 |
+
return xp.fft.fftshift(x, axes=axes)
|
269 |
+
x = np.asarray(x)
|
270 |
+
y = np.fft.fftshift(x, axes=axes)
|
271 |
+
return xp.asarray(y)
|
272 |
+
|
273 |
+
|
274 |
+
def ifftshift(x, axes=None):
|
275 |
+
"""The inverse of `fftshift`. Although identical for even-length `x`, the
|
276 |
+
functions differ by one sample for odd-length `x`.
|
277 |
+
|
278 |
+
Parameters
|
279 |
+
----------
|
280 |
+
x : array_like
|
281 |
+
Input array.
|
282 |
+
axes : int or shape tuple, optional
|
283 |
+
Axes over which to calculate. Defaults to None, which shifts all axes.
|
284 |
+
|
285 |
+
Returns
|
286 |
+
-------
|
287 |
+
y : ndarray
|
288 |
+
The shifted array.
|
289 |
+
|
290 |
+
See Also
|
291 |
+
--------
|
292 |
+
fftshift : Shift zero-frequency component to the center of the spectrum.
|
293 |
+
|
294 |
+
Examples
|
295 |
+
--------
|
296 |
+
>>> import numpy as np
|
297 |
+
>>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3)
|
298 |
+
>>> freqs
|
299 |
+
array([[ 0., 1., 2.],
|
300 |
+
[ 3., 4., -4.],
|
301 |
+
[-3., -2., -1.]])
|
302 |
+
>>> np.fft.ifftshift(np.fft.fftshift(freqs))
|
303 |
+
array([[ 0., 1., 2.],
|
304 |
+
[ 3., 4., -4.],
|
305 |
+
[-3., -2., -1.]])
|
306 |
+
|
307 |
+
"""
|
308 |
+
xp = array_namespace(x)
|
309 |
+
if hasattr(xp, 'fft'):
|
310 |
+
return xp.fft.ifftshift(x, axes=axes)
|
311 |
+
x = np.asarray(x)
|
312 |
+
y = np.fft.ifftshift(x, axes=axes)
|
313 |
+
return xp.asarray(y)
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/LICENSE.md
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright (C) 2010-2019 Max-Planck-Society
|
2 |
+
All rights reserved.
|
3 |
+
|
4 |
+
Redistribution and use in source and binary forms, with or without modification,
|
5 |
+
are permitted provided that the following conditions are met:
|
6 |
+
|
7 |
+
* Redistributions of source code must retain the above copyright notice, this
|
8 |
+
list of conditions and the following disclaimer.
|
9 |
+
* Redistributions in binary form must reproduce the above copyright notice, this
|
10 |
+
list of conditions and the following disclaimer in the documentation and/or
|
11 |
+
other materials provided with the distribution.
|
12 |
+
* Neither the name of the copyright holder nor the names of its contributors may
|
13 |
+
be used to endorse or promote products derived from this software without
|
14 |
+
specific prior written permission.
|
15 |
+
|
16 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
17 |
+
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
+
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
19 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
20 |
+
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
21 |
+
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
22 |
+
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
23 |
+
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
24 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
25 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__init__.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" FFT backend using pypocketfft """
|
2 |
+
|
3 |
+
from .basic import *
|
4 |
+
from .realtransforms import *
|
5 |
+
from .helper import *
|
6 |
+
|
7 |
+
from scipy._lib._testutils import PytestTester
|
8 |
+
test = PytestTester(__name__)
|
9 |
+
del PytestTester
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (395 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/basic.cpython-310.pyc
ADDED
Binary file (5.29 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/helper.cpython-310.pyc
ADDED
Binary file (6.06 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/__pycache__/realtransforms.cpython-310.pyc
ADDED
Binary file (2.46 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/basic.py
ADDED
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Discrete Fourier Transforms - basic.py
|
3 |
+
"""
|
4 |
+
import numpy as np
|
5 |
+
import functools
|
6 |
+
from . import pypocketfft as pfft
|
7 |
+
from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied,
|
8 |
+
_fix_shape, _fix_shape_1d, _normalization,
|
9 |
+
_workers)
|
10 |
+
|
11 |
+
def c2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
|
12 |
+
workers=None, *, plan=None):
|
13 |
+
""" Return discrete Fourier transform of real or complex sequence. """
|
14 |
+
if plan is not None:
|
15 |
+
raise NotImplementedError('Passing a precomputed plan is not yet '
|
16 |
+
'supported by scipy.fft functions')
|
17 |
+
tmp = _asfarray(x)
|
18 |
+
overwrite_x = overwrite_x or _datacopied(tmp, x)
|
19 |
+
norm = _normalization(norm, forward)
|
20 |
+
workers = _workers(workers)
|
21 |
+
|
22 |
+
if n is not None:
|
23 |
+
tmp, copied = _fix_shape_1d(tmp, n, axis)
|
24 |
+
overwrite_x = overwrite_x or copied
|
25 |
+
elif tmp.shape[axis] < 1:
|
26 |
+
message = f"invalid number of data points ({tmp.shape[axis]}) specified"
|
27 |
+
raise ValueError(message)
|
28 |
+
|
29 |
+
out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None)
|
30 |
+
|
31 |
+
return pfft.c2c(tmp, (axis,), forward, norm, out, workers)
|
32 |
+
|
33 |
+
|
34 |
+
fft = functools.partial(c2c, True)
|
35 |
+
fft.__name__ = 'fft'
|
36 |
+
ifft = functools.partial(c2c, False)
|
37 |
+
ifft.__name__ = 'ifft'
|
38 |
+
|
39 |
+
|
40 |
+
def r2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
|
41 |
+
workers=None, *, plan=None):
|
42 |
+
"""
|
43 |
+
Discrete Fourier transform of a real sequence.
|
44 |
+
"""
|
45 |
+
if plan is not None:
|
46 |
+
raise NotImplementedError('Passing a precomputed plan is not yet '
|
47 |
+
'supported by scipy.fft functions')
|
48 |
+
tmp = _asfarray(x)
|
49 |
+
norm = _normalization(norm, forward)
|
50 |
+
workers = _workers(workers)
|
51 |
+
|
52 |
+
if not np.isrealobj(tmp):
|
53 |
+
raise TypeError("x must be a real sequence")
|
54 |
+
|
55 |
+
if n is not None:
|
56 |
+
tmp, _ = _fix_shape_1d(tmp, n, axis)
|
57 |
+
elif tmp.shape[axis] < 1:
|
58 |
+
raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
|
59 |
+
|
60 |
+
# Note: overwrite_x is not utilised
|
61 |
+
return pfft.r2c(tmp, (axis,), forward, norm, None, workers)
|
62 |
+
|
63 |
+
|
64 |
+
rfft = functools.partial(r2c, True)
|
65 |
+
rfft.__name__ = 'rfft'
|
66 |
+
ihfft = functools.partial(r2c, False)
|
67 |
+
ihfft.__name__ = 'ihfft'
|
68 |
+
|
69 |
+
|
70 |
+
def c2r(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
|
71 |
+
workers=None, *, plan=None):
|
72 |
+
"""
|
73 |
+
Return inverse discrete Fourier transform of real sequence x.
|
74 |
+
"""
|
75 |
+
if plan is not None:
|
76 |
+
raise NotImplementedError('Passing a precomputed plan is not yet '
|
77 |
+
'supported by scipy.fft functions')
|
78 |
+
tmp = _asfarray(x)
|
79 |
+
norm = _normalization(norm, forward)
|
80 |
+
workers = _workers(workers)
|
81 |
+
|
82 |
+
# TODO: Optimize for hermitian and real?
|
83 |
+
if np.isrealobj(tmp):
|
84 |
+
tmp = tmp + 0.j
|
85 |
+
|
86 |
+
# Last axis utilizes hermitian symmetry
|
87 |
+
if n is None:
|
88 |
+
n = (tmp.shape[axis] - 1) * 2
|
89 |
+
if n < 1:
|
90 |
+
raise ValueError(f"Invalid number of data points ({n}) specified")
|
91 |
+
else:
|
92 |
+
tmp, _ = _fix_shape_1d(tmp, (n//2) + 1, axis)
|
93 |
+
|
94 |
+
# Note: overwrite_x is not utilized
|
95 |
+
return pfft.c2r(tmp, (axis,), n, forward, norm, None, workers)
|
96 |
+
|
97 |
+
|
98 |
+
hfft = functools.partial(c2r, True)
|
99 |
+
hfft.__name__ = 'hfft'
|
100 |
+
irfft = functools.partial(c2r, False)
|
101 |
+
irfft.__name__ = 'irfft'
|
102 |
+
|
103 |
+
|
104 |
+
def hfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None,
|
105 |
+
*, plan=None):
|
106 |
+
"""
|
107 |
+
2-D discrete Fourier transform of a Hermitian sequence
|
108 |
+
"""
|
109 |
+
if plan is not None:
|
110 |
+
raise NotImplementedError('Passing a precomputed plan is not yet '
|
111 |
+
'supported by scipy.fft functions')
|
112 |
+
return hfftn(x, s, axes, norm, overwrite_x, workers)
|
113 |
+
|
114 |
+
|
115 |
+
def ihfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None,
|
116 |
+
*, plan=None):
|
117 |
+
"""
|
118 |
+
2-D discrete inverse Fourier transform of a Hermitian sequence
|
119 |
+
"""
|
120 |
+
if plan is not None:
|
121 |
+
raise NotImplementedError('Passing a precomputed plan is not yet '
|
122 |
+
'supported by scipy.fft functions')
|
123 |
+
return ihfftn(x, s, axes, norm, overwrite_x, workers)
|
124 |
+
|
125 |
+
|
126 |
+
def c2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
|
127 |
+
workers=None, *, plan=None):
|
128 |
+
"""
|
129 |
+
Return multidimensional discrete Fourier transform.
|
130 |
+
"""
|
131 |
+
if plan is not None:
|
132 |
+
raise NotImplementedError('Passing a precomputed plan is not yet '
|
133 |
+
'supported by scipy.fft functions')
|
134 |
+
tmp = _asfarray(x)
|
135 |
+
|
136 |
+
shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
|
137 |
+
overwrite_x = overwrite_x or _datacopied(tmp, x)
|
138 |
+
workers = _workers(workers)
|
139 |
+
|
140 |
+
if len(axes) == 0:
|
141 |
+
return x
|
142 |
+
|
143 |
+
tmp, copied = _fix_shape(tmp, shape, axes)
|
144 |
+
overwrite_x = overwrite_x or copied
|
145 |
+
|
146 |
+
norm = _normalization(norm, forward)
|
147 |
+
out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None)
|
148 |
+
|
149 |
+
return pfft.c2c(tmp, axes, forward, norm, out, workers)
|
150 |
+
|
151 |
+
|
152 |
+
fftn = functools.partial(c2cn, True)
|
153 |
+
fftn.__name__ = 'fftn'
|
154 |
+
ifftn = functools.partial(c2cn, False)
|
155 |
+
ifftn.__name__ = 'ifftn'
|
156 |
+
|
157 |
+
def r2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
|
158 |
+
workers=None, *, plan=None):
|
159 |
+
"""Return multidimensional discrete Fourier transform of real input"""
|
160 |
+
if plan is not None:
|
161 |
+
raise NotImplementedError('Passing a precomputed plan is not yet '
|
162 |
+
'supported by scipy.fft functions')
|
163 |
+
tmp = _asfarray(x)
|
164 |
+
|
165 |
+
if not np.isrealobj(tmp):
|
166 |
+
raise TypeError("x must be a real sequence")
|
167 |
+
|
168 |
+
shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
|
169 |
+
tmp, _ = _fix_shape(tmp, shape, axes)
|
170 |
+
norm = _normalization(norm, forward)
|
171 |
+
workers = _workers(workers)
|
172 |
+
|
173 |
+
if len(axes) == 0:
|
174 |
+
raise ValueError("at least 1 axis must be transformed")
|
175 |
+
|
176 |
+
# Note: overwrite_x is not utilized
|
177 |
+
return pfft.r2c(tmp, axes, forward, norm, None, workers)
|
178 |
+
|
179 |
+
|
180 |
+
rfftn = functools.partial(r2cn, True)
|
181 |
+
rfftn.__name__ = 'rfftn'
|
182 |
+
ihfftn = functools.partial(r2cn, False)
|
183 |
+
ihfftn.__name__ = 'ihfftn'
|
184 |
+
|
185 |
+
|
186 |
+
def c2rn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
|
187 |
+
workers=None, *, plan=None):
|
188 |
+
"""Multidimensional inverse discrete fourier transform with real output"""
|
189 |
+
if plan is not None:
|
190 |
+
raise NotImplementedError('Passing a precomputed plan is not yet '
|
191 |
+
'supported by scipy.fft functions')
|
192 |
+
tmp = _asfarray(x)
|
193 |
+
|
194 |
+
# TODO: Optimize for hermitian and real?
|
195 |
+
if np.isrealobj(tmp):
|
196 |
+
tmp = tmp + 0.j
|
197 |
+
|
198 |
+
noshape = s is None
|
199 |
+
shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
|
200 |
+
|
201 |
+
if len(axes) == 0:
|
202 |
+
raise ValueError("at least 1 axis must be transformed")
|
203 |
+
|
204 |
+
shape = list(shape)
|
205 |
+
if noshape:
|
206 |
+
shape[-1] = (x.shape[axes[-1]] - 1) * 2
|
207 |
+
|
208 |
+
norm = _normalization(norm, forward)
|
209 |
+
workers = _workers(workers)
|
210 |
+
|
211 |
+
# Last axis utilizes hermitian symmetry
|
212 |
+
lastsize = shape[-1]
|
213 |
+
shape[-1] = (shape[-1] // 2) + 1
|
214 |
+
|
215 |
+
tmp, _ = tuple(_fix_shape(tmp, shape, axes))
|
216 |
+
|
217 |
+
# Note: overwrite_x is not utilized
|
218 |
+
return pfft.c2r(tmp, axes, lastsize, forward, norm, None, workers)
|
219 |
+
|
220 |
+
|
221 |
+
hfftn = functools.partial(c2rn, True)
|
222 |
+
hfftn.__name__ = 'hfftn'
|
223 |
+
irfftn = functools.partial(c2rn, False)
|
224 |
+
irfftn.__name__ = 'irfftn'
|
225 |
+
|
226 |
+
|
227 |
+
def r2r_fftpack(forward, x, n=None, axis=-1, norm=None, overwrite_x=False):
|
228 |
+
"""FFT of a real sequence, returning fftpack half complex format"""
|
229 |
+
tmp = _asfarray(x)
|
230 |
+
overwrite_x = overwrite_x or _datacopied(tmp, x)
|
231 |
+
norm = _normalization(norm, forward)
|
232 |
+
workers = _workers(None)
|
233 |
+
|
234 |
+
if tmp.dtype.kind == 'c':
|
235 |
+
raise TypeError('x must be a real sequence')
|
236 |
+
|
237 |
+
if n is not None:
|
238 |
+
tmp, copied = _fix_shape_1d(tmp, n, axis)
|
239 |
+
overwrite_x = overwrite_x or copied
|
240 |
+
elif tmp.shape[axis] < 1:
|
241 |
+
raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
|
242 |
+
|
243 |
+
out = (tmp if overwrite_x else None)
|
244 |
+
|
245 |
+
return pfft.r2r_fftpack(tmp, (axis,), forward, forward, norm, out, workers)
|
246 |
+
|
247 |
+
|
248 |
+
rfft_fftpack = functools.partial(r2r_fftpack, True)
|
249 |
+
rfft_fftpack.__name__ = 'rfft_fftpack'
|
250 |
+
irfft_fftpack = functools.partial(r2r_fftpack, False)
|
251 |
+
irfft_fftpack.__name__ = 'irfft_fftpack'
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/helper.py
ADDED
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from numbers import Number
|
2 |
+
import operator
|
3 |
+
import os
|
4 |
+
import threading
|
5 |
+
import contextlib
|
6 |
+
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
from scipy._lib._util import copy_if_needed
|
10 |
+
|
11 |
+
# good_size is exposed (and used) from this import
|
12 |
+
from .pypocketfft import good_size
|
13 |
+
|
14 |
+
|
15 |
+
__all__ = ['good_size', 'set_workers', 'get_workers']
|
16 |
+
|
17 |
+
_config = threading.local()
|
18 |
+
_cpu_count = os.cpu_count()
|
19 |
+
|
20 |
+
|
21 |
+
def _iterable_of_int(x, name=None):
|
22 |
+
"""Convert ``x`` to an iterable sequence of int
|
23 |
+
|
24 |
+
Parameters
|
25 |
+
----------
|
26 |
+
x : value, or sequence of values, convertible to int
|
27 |
+
name : str, optional
|
28 |
+
Name of the argument being converted, only used in the error message
|
29 |
+
|
30 |
+
Returns
|
31 |
+
-------
|
32 |
+
y : ``List[int]``
|
33 |
+
"""
|
34 |
+
if isinstance(x, Number):
|
35 |
+
x = (x,)
|
36 |
+
|
37 |
+
try:
|
38 |
+
x = [operator.index(a) for a in x]
|
39 |
+
except TypeError as e:
|
40 |
+
name = name or "value"
|
41 |
+
raise ValueError(f"{name} must be a scalar or iterable of integers") from e
|
42 |
+
|
43 |
+
return x
|
44 |
+
|
45 |
+
|
46 |
+
def _init_nd_shape_and_axes(x, shape, axes):
|
47 |
+
"""Handles shape and axes arguments for nd transforms"""
|
48 |
+
noshape = shape is None
|
49 |
+
noaxes = axes is None
|
50 |
+
|
51 |
+
if not noaxes:
|
52 |
+
axes = _iterable_of_int(axes, 'axes')
|
53 |
+
axes = [a + x.ndim if a < 0 else a for a in axes]
|
54 |
+
|
55 |
+
if any(a >= x.ndim or a < 0 for a in axes):
|
56 |
+
raise ValueError("axes exceeds dimensionality of input")
|
57 |
+
if len(set(axes)) != len(axes):
|
58 |
+
raise ValueError("all axes must be unique")
|
59 |
+
|
60 |
+
if not noshape:
|
61 |
+
shape = _iterable_of_int(shape, 'shape')
|
62 |
+
|
63 |
+
if axes and len(axes) != len(shape):
|
64 |
+
raise ValueError("when given, axes and shape arguments"
|
65 |
+
" have to be of the same length")
|
66 |
+
if noaxes:
|
67 |
+
if len(shape) > x.ndim:
|
68 |
+
raise ValueError("shape requires more axes than are present")
|
69 |
+
axes = range(x.ndim - len(shape), x.ndim)
|
70 |
+
|
71 |
+
shape = [x.shape[a] if s == -1 else s for s, a in zip(shape, axes)]
|
72 |
+
elif noaxes:
|
73 |
+
shape = list(x.shape)
|
74 |
+
axes = range(x.ndim)
|
75 |
+
else:
|
76 |
+
shape = [x.shape[a] for a in axes]
|
77 |
+
|
78 |
+
if any(s < 1 for s in shape):
|
79 |
+
raise ValueError(
|
80 |
+
f"invalid number of data points ({shape}) specified")
|
81 |
+
|
82 |
+
return tuple(shape), list(axes)
|
83 |
+
|
84 |
+
|
85 |
+
def _asfarray(x):
|
86 |
+
"""
|
87 |
+
Convert to array with floating or complex dtype.
|
88 |
+
|
89 |
+
float16 values are also promoted to float32.
|
90 |
+
"""
|
91 |
+
if not hasattr(x, "dtype"):
|
92 |
+
x = np.asarray(x)
|
93 |
+
|
94 |
+
if x.dtype == np.float16:
|
95 |
+
return np.asarray(x, np.float32)
|
96 |
+
elif x.dtype.kind not in 'fc':
|
97 |
+
return np.asarray(x, np.float64)
|
98 |
+
|
99 |
+
# Require native byte order
|
100 |
+
dtype = x.dtype.newbyteorder('=')
|
101 |
+
# Always align input
|
102 |
+
copy = True if not x.flags['ALIGNED'] else copy_if_needed
|
103 |
+
return np.array(x, dtype=dtype, copy=copy)
|
104 |
+
|
105 |
+
def _datacopied(arr, original):
|
106 |
+
"""
|
107 |
+
Strict check for `arr` not sharing any data with `original`,
|
108 |
+
under the assumption that arr = asarray(original)
|
109 |
+
"""
|
110 |
+
if arr is original:
|
111 |
+
return False
|
112 |
+
if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
|
113 |
+
return False
|
114 |
+
return arr.base is None
|
115 |
+
|
116 |
+
|
117 |
+
def _fix_shape(x, shape, axes):
|
118 |
+
"""Internal auxiliary function for _raw_fft, _raw_fftnd."""
|
119 |
+
must_copy = False
|
120 |
+
|
121 |
+
# Build an nd slice with the dimensions to be read from x
|
122 |
+
index = [slice(None)]*x.ndim
|
123 |
+
for n, ax in zip(shape, axes):
|
124 |
+
if x.shape[ax] >= n:
|
125 |
+
index[ax] = slice(0, n)
|
126 |
+
else:
|
127 |
+
index[ax] = slice(0, x.shape[ax])
|
128 |
+
must_copy = True
|
129 |
+
|
130 |
+
index = tuple(index)
|
131 |
+
|
132 |
+
if not must_copy:
|
133 |
+
return x[index], False
|
134 |
+
|
135 |
+
s = list(x.shape)
|
136 |
+
for n, axis in zip(shape, axes):
|
137 |
+
s[axis] = n
|
138 |
+
|
139 |
+
z = np.zeros(s, x.dtype)
|
140 |
+
z[index] = x[index]
|
141 |
+
return z, True
|
142 |
+
|
143 |
+
|
144 |
+
def _fix_shape_1d(x, n, axis):
|
145 |
+
if n < 1:
|
146 |
+
raise ValueError(
|
147 |
+
f"invalid number of data points ({n}) specified")
|
148 |
+
|
149 |
+
return _fix_shape(x, (n,), (axis,))
|
150 |
+
|
151 |
+
|
152 |
+
_NORM_MAP = {None: 0, 'backward': 0, 'ortho': 1, 'forward': 2}
|
153 |
+
|
154 |
+
|
155 |
+
def _normalization(norm, forward):
|
156 |
+
"""Returns the pypocketfft normalization mode from the norm argument"""
|
157 |
+
try:
|
158 |
+
inorm = _NORM_MAP[norm]
|
159 |
+
return inorm if forward else (2 - inorm)
|
160 |
+
except KeyError:
|
161 |
+
raise ValueError(
|
162 |
+
f'Invalid norm value {norm!r}, should '
|
163 |
+
'be "backward", "ortho" or "forward"') from None
|
164 |
+
|
165 |
+
|
166 |
+
def _workers(workers):
|
167 |
+
if workers is None:
|
168 |
+
return getattr(_config, 'default_workers', 1)
|
169 |
+
|
170 |
+
if workers < 0:
|
171 |
+
if workers >= -_cpu_count:
|
172 |
+
workers += 1 + _cpu_count
|
173 |
+
else:
|
174 |
+
raise ValueError(f"workers value out of range; got {workers}, must not be"
|
175 |
+
f" less than {-_cpu_count}")
|
176 |
+
elif workers == 0:
|
177 |
+
raise ValueError("workers must not be zero")
|
178 |
+
|
179 |
+
return workers
|
180 |
+
|
181 |
+
|
182 |
+
@contextlib.contextmanager
|
183 |
+
def set_workers(workers):
|
184 |
+
"""Context manager for the default number of workers used in `scipy.fft`
|
185 |
+
|
186 |
+
Parameters
|
187 |
+
----------
|
188 |
+
workers : int
|
189 |
+
The default number of workers to use
|
190 |
+
|
191 |
+
Examples
|
192 |
+
--------
|
193 |
+
>>> import numpy as np
|
194 |
+
>>> from scipy import fft, signal
|
195 |
+
>>> rng = np.random.default_rng()
|
196 |
+
>>> x = rng.standard_normal((128, 64))
|
197 |
+
>>> with fft.set_workers(4):
|
198 |
+
... y = signal.fftconvolve(x, x)
|
199 |
+
|
200 |
+
"""
|
201 |
+
old_workers = get_workers()
|
202 |
+
_config.default_workers = _workers(operator.index(workers))
|
203 |
+
try:
|
204 |
+
yield
|
205 |
+
finally:
|
206 |
+
_config.default_workers = old_workers
|
207 |
+
|
208 |
+
|
209 |
+
def get_workers():
|
210 |
+
"""Returns the default number of workers within the current context
|
211 |
+
|
212 |
+
Examples
|
213 |
+
--------
|
214 |
+
>>> from scipy import fft
|
215 |
+
>>> fft.get_workers()
|
216 |
+
1
|
217 |
+
>>> with fft.set_workers(4):
|
218 |
+
... fft.get_workers()
|
219 |
+
4
|
220 |
+
"""
|
221 |
+
return getattr(_config, 'default_workers', 1)
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/realtransforms.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from . import pypocketfft as pfft
|
3 |
+
from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied,
|
4 |
+
_fix_shape, _fix_shape_1d, _normalization, _workers)
|
5 |
+
import functools
|
6 |
+
|
7 |
+
|
8 |
+
def _r2r(forward, transform, x, type=2, n=None, axis=-1, norm=None,
|
9 |
+
overwrite_x=False, workers=None, orthogonalize=None):
|
10 |
+
"""Forward or backward 1-D DCT/DST
|
11 |
+
|
12 |
+
Parameters
|
13 |
+
----------
|
14 |
+
forward : bool
|
15 |
+
Transform direction (determines type and normalisation)
|
16 |
+
transform : {pypocketfft.dct, pypocketfft.dst}
|
17 |
+
The transform to perform
|
18 |
+
"""
|
19 |
+
tmp = _asfarray(x)
|
20 |
+
overwrite_x = overwrite_x or _datacopied(tmp, x)
|
21 |
+
norm = _normalization(norm, forward)
|
22 |
+
workers = _workers(workers)
|
23 |
+
|
24 |
+
if not forward:
|
25 |
+
if type == 2:
|
26 |
+
type = 3
|
27 |
+
elif type == 3:
|
28 |
+
type = 2
|
29 |
+
|
30 |
+
if n is not None:
|
31 |
+
tmp, copied = _fix_shape_1d(tmp, n, axis)
|
32 |
+
overwrite_x = overwrite_x or copied
|
33 |
+
elif tmp.shape[axis] < 1:
|
34 |
+
raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
|
35 |
+
|
36 |
+
out = (tmp if overwrite_x else None)
|
37 |
+
|
38 |
+
# For complex input, transform real and imaginary components separably
|
39 |
+
if np.iscomplexobj(x):
|
40 |
+
out = np.empty_like(tmp) if out is None else out
|
41 |
+
transform(tmp.real, type, (axis,), norm, out.real, workers)
|
42 |
+
transform(tmp.imag, type, (axis,), norm, out.imag, workers)
|
43 |
+
return out
|
44 |
+
|
45 |
+
return transform(tmp, type, (axis,), norm, out, workers, orthogonalize)
|
46 |
+
|
47 |
+
|
48 |
+
dct = functools.partial(_r2r, True, pfft.dct)
|
49 |
+
dct.__name__ = 'dct'
|
50 |
+
idct = functools.partial(_r2r, False, pfft.dct)
|
51 |
+
idct.__name__ = 'idct'
|
52 |
+
|
53 |
+
dst = functools.partial(_r2r, True, pfft.dst)
|
54 |
+
dst.__name__ = 'dst'
|
55 |
+
idst = functools.partial(_r2r, False, pfft.dst)
|
56 |
+
idst.__name__ = 'idst'
|
57 |
+
|
58 |
+
|
59 |
+
def _r2rn(forward, transform, x, type=2, s=None, axes=None, norm=None,
|
60 |
+
overwrite_x=False, workers=None, orthogonalize=None):
|
61 |
+
"""Forward or backward nd DCT/DST
|
62 |
+
|
63 |
+
Parameters
|
64 |
+
----------
|
65 |
+
forward : bool
|
66 |
+
Transform direction (determines type and normalisation)
|
67 |
+
transform : {pypocketfft.dct, pypocketfft.dst}
|
68 |
+
The transform to perform
|
69 |
+
"""
|
70 |
+
tmp = _asfarray(x)
|
71 |
+
|
72 |
+
shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
|
73 |
+
overwrite_x = overwrite_x or _datacopied(tmp, x)
|
74 |
+
|
75 |
+
if len(axes) == 0:
|
76 |
+
return x
|
77 |
+
|
78 |
+
tmp, copied = _fix_shape(tmp, shape, axes)
|
79 |
+
overwrite_x = overwrite_x or copied
|
80 |
+
|
81 |
+
if not forward:
|
82 |
+
if type == 2:
|
83 |
+
type = 3
|
84 |
+
elif type == 3:
|
85 |
+
type = 2
|
86 |
+
|
87 |
+
norm = _normalization(norm, forward)
|
88 |
+
workers = _workers(workers)
|
89 |
+
out = (tmp if overwrite_x else None)
|
90 |
+
|
91 |
+
# For complex input, transform real and imaginary components separably
|
92 |
+
if np.iscomplexobj(x):
|
93 |
+
out = np.empty_like(tmp) if out is None else out
|
94 |
+
transform(tmp.real, type, axes, norm, out.real, workers)
|
95 |
+
transform(tmp.imag, type, axes, norm, out.imag, workers)
|
96 |
+
return out
|
97 |
+
|
98 |
+
return transform(tmp, type, axes, norm, out, workers, orthogonalize)
|
99 |
+
|
100 |
+
|
101 |
+
dctn = functools.partial(_r2rn, True, pfft.dct)
|
102 |
+
dctn.__name__ = 'dctn'
|
103 |
+
idctn = functools.partial(_r2rn, False, pfft.dct)
|
104 |
+
idctn.__name__ = 'idctn'
|
105 |
+
|
106 |
+
dstn = functools.partial(_r2rn, True, pfft.dst)
|
107 |
+
dstn.__name__ = 'dstn'
|
108 |
+
idstn = functools.partial(_r2rn, False, pfft.dst)
|
109 |
+
idstn.__name__ = 'idstn'
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (194 Bytes). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__pycache__/test_basic.cpython-310.pyc
ADDED
Binary file (32.9 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/__pycache__/test_real_transforms.cpython-310.pyc
ADDED
Binary file (14.1 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_basic.py
ADDED
@@ -0,0 +1,1005 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Created by Pearu Peterson, September 2002
|
2 |
+
|
3 |
+
from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
|
4 |
+
assert_array_almost_equal_nulp, assert_array_less,
|
5 |
+
assert_allclose)
|
6 |
+
import pytest
|
7 |
+
from pytest import raises as assert_raises
|
8 |
+
from scipy.fft._pocketfft import (ifft, fft, fftn, ifftn,
|
9 |
+
rfft, irfft, rfftn, irfftn,
|
10 |
+
hfft, ihfft, hfftn, ihfftn)
|
11 |
+
|
12 |
+
from numpy import (arange, array, asarray, zeros, dot, exp, pi,
|
13 |
+
swapaxes, cdouble)
|
14 |
+
import numpy as np
|
15 |
+
import numpy.fft
|
16 |
+
from numpy.random import rand
|
17 |
+
|
18 |
+
# "large" composite numbers supported by FFT._PYPOCKETFFT
|
19 |
+
LARGE_COMPOSITE_SIZES = [
|
20 |
+
2**13,
|
21 |
+
2**5 * 3**5,
|
22 |
+
2**3 * 3**3 * 5**2,
|
23 |
+
]
|
24 |
+
SMALL_COMPOSITE_SIZES = [
|
25 |
+
2,
|
26 |
+
2*3*5,
|
27 |
+
2*2*3*3,
|
28 |
+
]
|
29 |
+
# prime
|
30 |
+
LARGE_PRIME_SIZES = [
|
31 |
+
2011
|
32 |
+
]
|
33 |
+
SMALL_PRIME_SIZES = [
|
34 |
+
29
|
35 |
+
]
|
36 |
+
|
37 |
+
|
38 |
+
def _assert_close_in_norm(x, y, rtol, size, rdt):
|
39 |
+
# helper function for testing
|
40 |
+
err_msg = f"size: {size} rdt: {rdt}"
|
41 |
+
assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg)
|
42 |
+
|
43 |
+
|
44 |
+
def random(size):
|
45 |
+
return rand(*size)
|
46 |
+
|
47 |
+
def swap_byteorder(arr):
|
48 |
+
"""Returns the same array with swapped byteorder"""
|
49 |
+
dtype = arr.dtype.newbyteorder('S')
|
50 |
+
return arr.astype(dtype)
|
51 |
+
|
52 |
+
def direct_dft(x):
|
53 |
+
x = asarray(x)
|
54 |
+
n = len(x)
|
55 |
+
y = zeros(n, dtype=cdouble)
|
56 |
+
w = -arange(n)*(2j*pi/n)
|
57 |
+
for i in range(n):
|
58 |
+
y[i] = dot(exp(i*w), x)
|
59 |
+
return y
|
60 |
+
|
61 |
+
|
62 |
+
def direct_idft(x):
|
63 |
+
x = asarray(x)
|
64 |
+
n = len(x)
|
65 |
+
y = zeros(n, dtype=cdouble)
|
66 |
+
w = arange(n)*(2j*pi/n)
|
67 |
+
for i in range(n):
|
68 |
+
y[i] = dot(exp(i*w), x)/n
|
69 |
+
return y
|
70 |
+
|
71 |
+
|
72 |
+
def direct_dftn(x):
|
73 |
+
x = asarray(x)
|
74 |
+
for axis in range(x.ndim):
|
75 |
+
x = fft(x, axis=axis)
|
76 |
+
return x
|
77 |
+
|
78 |
+
|
79 |
+
def direct_idftn(x):
|
80 |
+
x = asarray(x)
|
81 |
+
for axis in range(x.ndim):
|
82 |
+
x = ifft(x, axis=axis)
|
83 |
+
return x
|
84 |
+
|
85 |
+
|
86 |
+
def direct_rdft(x):
|
87 |
+
x = asarray(x)
|
88 |
+
n = len(x)
|
89 |
+
w = -arange(n)*(2j*pi/n)
|
90 |
+
y = zeros(n//2+1, dtype=cdouble)
|
91 |
+
for i in range(n//2+1):
|
92 |
+
y[i] = dot(exp(i*w), x)
|
93 |
+
return y
|
94 |
+
|
95 |
+
|
96 |
+
def direct_irdft(x, n):
|
97 |
+
x = asarray(x)
|
98 |
+
x1 = zeros(n, dtype=cdouble)
|
99 |
+
for i in range(n//2+1):
|
100 |
+
x1[i] = x[i]
|
101 |
+
if i > 0 and 2*i < n:
|
102 |
+
x1[n-i] = np.conj(x[i])
|
103 |
+
return direct_idft(x1).real
|
104 |
+
|
105 |
+
|
106 |
+
def direct_rdftn(x):
|
107 |
+
return fftn(rfft(x), axes=range(x.ndim - 1))
|
108 |
+
|
109 |
+
|
110 |
+
class _TestFFTBase:
|
111 |
+
def setup_method(self):
|
112 |
+
self.cdt = None
|
113 |
+
self.rdt = None
|
114 |
+
np.random.seed(1234)
|
115 |
+
|
116 |
+
def test_definition(self):
|
117 |
+
x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt)
|
118 |
+
y = fft(x)
|
119 |
+
assert_equal(y.dtype, self.cdt)
|
120 |
+
y1 = direct_dft(x)
|
121 |
+
assert_array_almost_equal(y,y1)
|
122 |
+
x = np.array([1,2,3,4+0j,5], dtype=self.cdt)
|
123 |
+
assert_array_almost_equal(fft(x),direct_dft(x))
|
124 |
+
|
125 |
+
def test_n_argument_real(self):
|
126 |
+
x1 = np.array([1,2,3,4], dtype=self.rdt)
|
127 |
+
x2 = np.array([1,2,3,4], dtype=self.rdt)
|
128 |
+
y = fft([x1,x2],n=4)
|
129 |
+
assert_equal(y.dtype, self.cdt)
|
130 |
+
assert_equal(y.shape,(2,4))
|
131 |
+
assert_array_almost_equal(y[0],direct_dft(x1))
|
132 |
+
assert_array_almost_equal(y[1],direct_dft(x2))
|
133 |
+
|
134 |
+
def _test_n_argument_complex(self):
|
135 |
+
x1 = np.array([1,2,3,4+1j], dtype=self.cdt)
|
136 |
+
x2 = np.array([1,2,3,4+1j], dtype=self.cdt)
|
137 |
+
y = fft([x1,x2],n=4)
|
138 |
+
assert_equal(y.dtype, self.cdt)
|
139 |
+
assert_equal(y.shape,(2,4))
|
140 |
+
assert_array_almost_equal(y[0],direct_dft(x1))
|
141 |
+
assert_array_almost_equal(y[1],direct_dft(x2))
|
142 |
+
|
143 |
+
def test_djbfft(self):
|
144 |
+
for i in range(2,14):
|
145 |
+
n = 2**i
|
146 |
+
x = np.arange(n)
|
147 |
+
y = fft(x.astype(complex))
|
148 |
+
y2 = numpy.fft.fft(x)
|
149 |
+
assert_array_almost_equal(y,y2)
|
150 |
+
y = fft(x)
|
151 |
+
assert_array_almost_equal(y,y2)
|
152 |
+
|
153 |
+
def test_invalid_sizes(self):
|
154 |
+
assert_raises(ValueError, fft, [])
|
155 |
+
assert_raises(ValueError, fft, [[1,1],[2,2]], -5)
|
156 |
+
|
157 |
+
|
158 |
+
class TestLongDoubleFFT(_TestFFTBase):
|
159 |
+
def setup_method(self):
|
160 |
+
self.cdt = np.clongdouble
|
161 |
+
self.rdt = np.longdouble
|
162 |
+
|
163 |
+
|
164 |
+
class TestDoubleFFT(_TestFFTBase):
|
165 |
+
def setup_method(self):
|
166 |
+
self.cdt = np.cdouble
|
167 |
+
self.rdt = np.float64
|
168 |
+
|
169 |
+
|
170 |
+
class TestSingleFFT(_TestFFTBase):
|
171 |
+
def setup_method(self):
|
172 |
+
self.cdt = np.complex64
|
173 |
+
self.rdt = np.float32
|
174 |
+
|
175 |
+
|
176 |
+
class TestFloat16FFT:
|
177 |
+
|
178 |
+
def test_1_argument_real(self):
|
179 |
+
x1 = np.array([1, 2, 3, 4], dtype=np.float16)
|
180 |
+
y = fft(x1, n=4)
|
181 |
+
assert_equal(y.dtype, np.complex64)
|
182 |
+
assert_equal(y.shape, (4, ))
|
183 |
+
assert_array_almost_equal(y, direct_dft(x1.astype(np.float32)))
|
184 |
+
|
185 |
+
def test_n_argument_real(self):
|
186 |
+
x1 = np.array([1, 2, 3, 4], dtype=np.float16)
|
187 |
+
x2 = np.array([1, 2, 3, 4], dtype=np.float16)
|
188 |
+
y = fft([x1, x2], n=4)
|
189 |
+
assert_equal(y.dtype, np.complex64)
|
190 |
+
assert_equal(y.shape, (2, 4))
|
191 |
+
assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32)))
|
192 |
+
assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32)))
|
193 |
+
|
194 |
+
|
195 |
+
class _TestIFFTBase:
|
196 |
+
def setup_method(self):
|
197 |
+
np.random.seed(1234)
|
198 |
+
|
199 |
+
def test_definition(self):
|
200 |
+
x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt)
|
201 |
+
y = ifft(x)
|
202 |
+
y1 = direct_idft(x)
|
203 |
+
assert_equal(y.dtype, self.cdt)
|
204 |
+
assert_array_almost_equal(y,y1)
|
205 |
+
|
206 |
+
x = np.array([1,2,3,4+0j,5], self.cdt)
|
207 |
+
assert_array_almost_equal(ifft(x),direct_idft(x))
|
208 |
+
|
209 |
+
def test_definition_real(self):
|
210 |
+
x = np.array([1,2,3,4,1,2,3,4], self.rdt)
|
211 |
+
y = ifft(x)
|
212 |
+
assert_equal(y.dtype, self.cdt)
|
213 |
+
y1 = direct_idft(x)
|
214 |
+
assert_array_almost_equal(y,y1)
|
215 |
+
|
216 |
+
x = np.array([1,2,3,4,5], dtype=self.rdt)
|
217 |
+
assert_equal(y.dtype, self.cdt)
|
218 |
+
assert_array_almost_equal(ifft(x),direct_idft(x))
|
219 |
+
|
220 |
+
def test_djbfft(self):
|
221 |
+
for i in range(2,14):
|
222 |
+
n = 2**i
|
223 |
+
x = np.arange(n)
|
224 |
+
y = ifft(x.astype(self.cdt))
|
225 |
+
y2 = numpy.fft.ifft(x.astype(self.cdt))
|
226 |
+
assert_allclose(y,y2, rtol=self.rtol, atol=self.atol)
|
227 |
+
y = ifft(x)
|
228 |
+
assert_allclose(y,y2, rtol=self.rtol, atol=self.atol)
|
229 |
+
|
230 |
+
def test_random_complex(self):
|
231 |
+
for size in [1,51,111,100,200,64,128,256,1024]:
|
232 |
+
x = random([size]).astype(self.cdt)
|
233 |
+
x = random([size]).astype(self.cdt) + 1j*x
|
234 |
+
y1 = ifft(fft(x))
|
235 |
+
y2 = fft(ifft(x))
|
236 |
+
assert_equal(y1.dtype, self.cdt)
|
237 |
+
assert_equal(y2.dtype, self.cdt)
|
238 |
+
assert_array_almost_equal(y1, x)
|
239 |
+
assert_array_almost_equal(y2, x)
|
240 |
+
|
241 |
+
def test_random_real(self):
|
242 |
+
for size in [1,51,111,100,200,64,128,256,1024]:
|
243 |
+
x = random([size]).astype(self.rdt)
|
244 |
+
y1 = ifft(fft(x))
|
245 |
+
y2 = fft(ifft(x))
|
246 |
+
assert_equal(y1.dtype, self.cdt)
|
247 |
+
assert_equal(y2.dtype, self.cdt)
|
248 |
+
assert_array_almost_equal(y1, x)
|
249 |
+
assert_array_almost_equal(y2, x)
|
250 |
+
|
251 |
+
def test_size_accuracy(self):
|
252 |
+
# Sanity check for the accuracy for prime and non-prime sized inputs
|
253 |
+
for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
|
254 |
+
np.random.seed(1234)
|
255 |
+
x = np.random.rand(size).astype(self.rdt)
|
256 |
+
y = ifft(fft(x))
|
257 |
+
_assert_close_in_norm(x, y, self.rtol, size, self.rdt)
|
258 |
+
y = fft(ifft(x))
|
259 |
+
_assert_close_in_norm(x, y, self.rtol, size, self.rdt)
|
260 |
+
|
261 |
+
x = (x + 1j*np.random.rand(size)).astype(self.cdt)
|
262 |
+
y = ifft(fft(x))
|
263 |
+
_assert_close_in_norm(x, y, self.rtol, size, self.rdt)
|
264 |
+
y = fft(ifft(x))
|
265 |
+
_assert_close_in_norm(x, y, self.rtol, size, self.rdt)
|
266 |
+
|
267 |
+
def test_invalid_sizes(self):
|
268 |
+
assert_raises(ValueError, ifft, [])
|
269 |
+
assert_raises(ValueError, ifft, [[1,1],[2,2]], -5)
|
270 |
+
|
271 |
+
|
272 |
+
@pytest.mark.skipif(np.longdouble is np.float64,
|
273 |
+
reason="Long double is aliased to double")
|
274 |
+
class TestLongDoubleIFFT(_TestIFFTBase):
|
275 |
+
def setup_method(self):
|
276 |
+
self.cdt = np.clongdouble
|
277 |
+
self.rdt = np.longdouble
|
278 |
+
self.rtol = 1e-10
|
279 |
+
self.atol = 1e-10
|
280 |
+
|
281 |
+
|
282 |
+
class TestDoubleIFFT(_TestIFFTBase):
|
283 |
+
def setup_method(self):
|
284 |
+
self.cdt = np.complex128
|
285 |
+
self.rdt = np.float64
|
286 |
+
self.rtol = 1e-10
|
287 |
+
self.atol = 1e-10
|
288 |
+
|
289 |
+
|
290 |
+
class TestSingleIFFT(_TestIFFTBase):
|
291 |
+
def setup_method(self):
|
292 |
+
self.cdt = np.complex64
|
293 |
+
self.rdt = np.float32
|
294 |
+
self.rtol = 1e-5
|
295 |
+
self.atol = 1e-4
|
296 |
+
|
297 |
+
|
298 |
+
class _TestRFFTBase:
|
299 |
+
def setup_method(self):
|
300 |
+
np.random.seed(1234)
|
301 |
+
|
302 |
+
def test_definition(self):
|
303 |
+
for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]:
|
304 |
+
x = np.array(t, dtype=self.rdt)
|
305 |
+
y = rfft(x)
|
306 |
+
y1 = direct_rdft(x)
|
307 |
+
assert_array_almost_equal(y,y1)
|
308 |
+
assert_equal(y.dtype, self.cdt)
|
309 |
+
|
310 |
+
def test_djbfft(self):
|
311 |
+
for i in range(2,14):
|
312 |
+
n = 2**i
|
313 |
+
x = np.arange(n)
|
314 |
+
y1 = np.fft.rfft(x)
|
315 |
+
y = rfft(x)
|
316 |
+
assert_array_almost_equal(y,y1)
|
317 |
+
|
318 |
+
def test_invalid_sizes(self):
|
319 |
+
assert_raises(ValueError, rfft, [])
|
320 |
+
assert_raises(ValueError, rfft, [[1,1],[2,2]], -5)
|
321 |
+
|
322 |
+
def test_complex_input(self):
|
323 |
+
x = np.zeros(10, dtype=self.cdt)
|
324 |
+
with assert_raises(TypeError, match="x must be a real sequence"):
|
325 |
+
rfft(x)
|
326 |
+
|
327 |
+
# See gh-5790
|
328 |
+
class MockSeries:
|
329 |
+
def __init__(self, data):
|
330 |
+
self.data = np.asarray(data)
|
331 |
+
|
332 |
+
def __getattr__(self, item):
|
333 |
+
try:
|
334 |
+
return getattr(self.data, item)
|
335 |
+
except AttributeError as e:
|
336 |
+
raise AttributeError("'MockSeries' object "
|
337 |
+
f"has no attribute '{item}'") from e
|
338 |
+
|
339 |
+
def test_non_ndarray_with_dtype(self):
|
340 |
+
x = np.array([1., 2., 3., 4., 5.])
|
341 |
+
xs = _TestRFFTBase.MockSeries(x)
|
342 |
+
|
343 |
+
expected = [1, 2, 3, 4, 5]
|
344 |
+
rfft(xs)
|
345 |
+
|
346 |
+
# Data should not have been overwritten
|
347 |
+
assert_equal(x, expected)
|
348 |
+
assert_equal(xs.data, expected)
|
349 |
+
|
350 |
+
@pytest.mark.skipif(np.longdouble is np.float64,
|
351 |
+
reason="Long double is aliased to double")
|
352 |
+
class TestRFFTLongDouble(_TestRFFTBase):
|
353 |
+
def setup_method(self):
|
354 |
+
self.cdt = np.clongdouble
|
355 |
+
self.rdt = np.longdouble
|
356 |
+
|
357 |
+
|
358 |
+
class TestRFFTDouble(_TestRFFTBase):
|
359 |
+
def setup_method(self):
|
360 |
+
self.cdt = np.complex128
|
361 |
+
self.rdt = np.float64
|
362 |
+
|
363 |
+
|
364 |
+
class TestRFFTSingle(_TestRFFTBase):
|
365 |
+
def setup_method(self):
|
366 |
+
self.cdt = np.complex64
|
367 |
+
self.rdt = np.float32
|
368 |
+
|
369 |
+
|
370 |
+
class _TestIRFFTBase:
|
371 |
+
def setup_method(self):
|
372 |
+
np.random.seed(1234)
|
373 |
+
|
374 |
+
def test_definition(self):
|
375 |
+
x1 = [1,2+3j,4+1j,1+2j,3+4j]
|
376 |
+
x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j]
|
377 |
+
x1 = x1_1[:5]
|
378 |
+
x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j]
|
379 |
+
x2 = x2_1[:5]
|
380 |
+
|
381 |
+
def _test(x, xr):
|
382 |
+
y = irfft(np.array(x, dtype=self.cdt), n=len(xr))
|
383 |
+
y1 = direct_irdft(x, len(xr))
|
384 |
+
assert_equal(y.dtype, self.rdt)
|
385 |
+
assert_array_almost_equal(y,y1, decimal=self.ndec)
|
386 |
+
assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
|
387 |
+
|
388 |
+
_test(x1, x1_1)
|
389 |
+
_test(x2, x2_1)
|
390 |
+
|
391 |
+
def test_djbfft(self):
|
392 |
+
for i in range(2,14):
|
393 |
+
n = 2**i
|
394 |
+
x = np.arange(-1, n, 2) + 1j * np.arange(0, n+1, 2)
|
395 |
+
x[0] = 0
|
396 |
+
if n % 2 == 0:
|
397 |
+
x[-1] = np.real(x[-1])
|
398 |
+
y1 = np.fft.irfft(x)
|
399 |
+
y = irfft(x)
|
400 |
+
assert_array_almost_equal(y,y1)
|
401 |
+
|
402 |
+
def test_random_real(self):
|
403 |
+
for size in [1,51,111,100,200,64,128,256,1024]:
|
404 |
+
x = random([size]).astype(self.rdt)
|
405 |
+
y1 = irfft(rfft(x), n=size)
|
406 |
+
y2 = rfft(irfft(x, n=(size*2-1)))
|
407 |
+
assert_equal(y1.dtype, self.rdt)
|
408 |
+
assert_equal(y2.dtype, self.cdt)
|
409 |
+
assert_array_almost_equal(y1, x, decimal=self.ndec,
|
410 |
+
err_msg="size=%d" % size)
|
411 |
+
assert_array_almost_equal(y2, x, decimal=self.ndec,
|
412 |
+
err_msg="size=%d" % size)
|
413 |
+
|
414 |
+
def test_size_accuracy(self):
|
415 |
+
# Sanity check for the accuracy for prime and non-prime sized inputs
|
416 |
+
if self.rdt == np.float32:
|
417 |
+
rtol = 1e-5
|
418 |
+
elif self.rdt == np.float64:
|
419 |
+
rtol = 1e-10
|
420 |
+
|
421 |
+
for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
|
422 |
+
np.random.seed(1234)
|
423 |
+
x = np.random.rand(size).astype(self.rdt)
|
424 |
+
y = irfft(rfft(x), len(x))
|
425 |
+
_assert_close_in_norm(x, y, rtol, size, self.rdt)
|
426 |
+
y = rfft(irfft(x, 2 * len(x) - 1))
|
427 |
+
_assert_close_in_norm(x, y, rtol, size, self.rdt)
|
428 |
+
|
429 |
+
def test_invalid_sizes(self):
|
430 |
+
assert_raises(ValueError, irfft, [])
|
431 |
+
assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
|
432 |
+
|
433 |
+
|
434 |
+
# self.ndec is bogus; we should have a assert_array_approx_equal for number of
|
435 |
+
# significant digits
|
436 |
+
|
437 |
+
@pytest.mark.skipif(np.longdouble is np.float64,
|
438 |
+
reason="Long double is aliased to double")
|
439 |
+
class TestIRFFTLongDouble(_TestIRFFTBase):
|
440 |
+
def setup_method(self):
|
441 |
+
self.cdt = np.complex128
|
442 |
+
self.rdt = np.float64
|
443 |
+
self.ndec = 14
|
444 |
+
|
445 |
+
|
446 |
+
class TestIRFFTDouble(_TestIRFFTBase):
|
447 |
+
def setup_method(self):
|
448 |
+
self.cdt = np.complex128
|
449 |
+
self.rdt = np.float64
|
450 |
+
self.ndec = 14
|
451 |
+
|
452 |
+
|
453 |
+
class TestIRFFTSingle(_TestIRFFTBase):
|
454 |
+
def setup_method(self):
|
455 |
+
self.cdt = np.complex64
|
456 |
+
self.rdt = np.float32
|
457 |
+
self.ndec = 5
|
458 |
+
|
459 |
+
|
460 |
+
class TestFftnSingle:
|
461 |
+
def setup_method(self):
|
462 |
+
np.random.seed(1234)
|
463 |
+
|
464 |
+
def test_definition(self):
|
465 |
+
x = [[1, 2, 3],
|
466 |
+
[4, 5, 6],
|
467 |
+
[7, 8, 9]]
|
468 |
+
y = fftn(np.array(x, np.float32))
|
469 |
+
assert_(y.dtype == np.complex64,
|
470 |
+
msg="double precision output with single precision")
|
471 |
+
|
472 |
+
y_r = np.array(fftn(x), np.complex64)
|
473 |
+
assert_array_almost_equal_nulp(y, y_r)
|
474 |
+
|
475 |
+
@pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
|
476 |
+
def test_size_accuracy_small(self, size):
|
477 |
+
x = np.random.rand(size, size) + 1j*np.random.rand(size, size)
|
478 |
+
y1 = fftn(x.real.astype(np.float32))
|
479 |
+
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
|
480 |
+
|
481 |
+
assert_equal(y1.dtype, np.complex64)
|
482 |
+
assert_array_almost_equal_nulp(y1, y2, 2000)
|
483 |
+
|
484 |
+
@pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
|
485 |
+
def test_size_accuracy_large(self, size):
|
486 |
+
x = np.random.rand(size, 3) + 1j*np.random.rand(size, 3)
|
487 |
+
y1 = fftn(x.real.astype(np.float32))
|
488 |
+
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
|
489 |
+
|
490 |
+
assert_equal(y1.dtype, np.complex64)
|
491 |
+
assert_array_almost_equal_nulp(y1, y2, 2000)
|
492 |
+
|
493 |
+
def test_definition_float16(self):
|
494 |
+
x = [[1, 2, 3],
|
495 |
+
[4, 5, 6],
|
496 |
+
[7, 8, 9]]
|
497 |
+
y = fftn(np.array(x, np.float16))
|
498 |
+
assert_equal(y.dtype, np.complex64)
|
499 |
+
y_r = np.array(fftn(x), np.complex64)
|
500 |
+
assert_array_almost_equal_nulp(y, y_r)
|
501 |
+
|
502 |
+
@pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
|
503 |
+
def test_float16_input_small(self, size):
|
504 |
+
x = np.random.rand(size, size) + 1j*np.random.rand(size, size)
|
505 |
+
y1 = fftn(x.real.astype(np.float16))
|
506 |
+
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
|
507 |
+
|
508 |
+
assert_equal(y1.dtype, np.complex64)
|
509 |
+
assert_array_almost_equal_nulp(y1, y2, 5e5)
|
510 |
+
|
511 |
+
@pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
|
512 |
+
def test_float16_input_large(self, size):
|
513 |
+
x = np.random.rand(size, 3) + 1j*np.random.rand(size, 3)
|
514 |
+
y1 = fftn(x.real.astype(np.float16))
|
515 |
+
y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
|
516 |
+
|
517 |
+
assert_equal(y1.dtype, np.complex64)
|
518 |
+
assert_array_almost_equal_nulp(y1, y2, 2e6)
|
519 |
+
|
520 |
+
|
521 |
+
class TestFftn:
|
522 |
+
def setup_method(self):
|
523 |
+
np.random.seed(1234)
|
524 |
+
|
525 |
+
def test_definition(self):
|
526 |
+
x = [[1, 2, 3],
|
527 |
+
[4, 5, 6],
|
528 |
+
[7, 8, 9]]
|
529 |
+
y = fftn(x)
|
530 |
+
assert_array_almost_equal(y, direct_dftn(x))
|
531 |
+
|
532 |
+
x = random((20, 26))
|
533 |
+
assert_array_almost_equal(fftn(x), direct_dftn(x))
|
534 |
+
|
535 |
+
x = random((5, 4, 3, 20))
|
536 |
+
assert_array_almost_equal(fftn(x), direct_dftn(x))
|
537 |
+
|
538 |
+
def test_axes_argument(self):
|
539 |
+
# plane == ji_plane, x== kji_space
|
540 |
+
plane1 = [[1, 2, 3],
|
541 |
+
[4, 5, 6],
|
542 |
+
[7, 8, 9]]
|
543 |
+
plane2 = [[10, 11, 12],
|
544 |
+
[13, 14, 15],
|
545 |
+
[16, 17, 18]]
|
546 |
+
plane3 = [[19, 20, 21],
|
547 |
+
[22, 23, 24],
|
548 |
+
[25, 26, 27]]
|
549 |
+
ki_plane1 = [[1, 2, 3],
|
550 |
+
[10, 11, 12],
|
551 |
+
[19, 20, 21]]
|
552 |
+
ki_plane2 = [[4, 5, 6],
|
553 |
+
[13, 14, 15],
|
554 |
+
[22, 23, 24]]
|
555 |
+
ki_plane3 = [[7, 8, 9],
|
556 |
+
[16, 17, 18],
|
557 |
+
[25, 26, 27]]
|
558 |
+
jk_plane1 = [[1, 10, 19],
|
559 |
+
[4, 13, 22],
|
560 |
+
[7, 16, 25]]
|
561 |
+
jk_plane2 = [[2, 11, 20],
|
562 |
+
[5, 14, 23],
|
563 |
+
[8, 17, 26]]
|
564 |
+
jk_plane3 = [[3, 12, 21],
|
565 |
+
[6, 15, 24],
|
566 |
+
[9, 18, 27]]
|
567 |
+
kj_plane1 = [[1, 4, 7],
|
568 |
+
[10, 13, 16], [19, 22, 25]]
|
569 |
+
kj_plane2 = [[2, 5, 8],
|
570 |
+
[11, 14, 17], [20, 23, 26]]
|
571 |
+
kj_plane3 = [[3, 6, 9],
|
572 |
+
[12, 15, 18], [21, 24, 27]]
|
573 |
+
ij_plane1 = [[1, 4, 7],
|
574 |
+
[2, 5, 8],
|
575 |
+
[3, 6, 9]]
|
576 |
+
ij_plane2 = [[10, 13, 16],
|
577 |
+
[11, 14, 17],
|
578 |
+
[12, 15, 18]]
|
579 |
+
ij_plane3 = [[19, 22, 25],
|
580 |
+
[20, 23, 26],
|
581 |
+
[21, 24, 27]]
|
582 |
+
ik_plane1 = [[1, 10, 19],
|
583 |
+
[2, 11, 20],
|
584 |
+
[3, 12, 21]]
|
585 |
+
ik_plane2 = [[4, 13, 22],
|
586 |
+
[5, 14, 23],
|
587 |
+
[6, 15, 24]]
|
588 |
+
ik_plane3 = [[7, 16, 25],
|
589 |
+
[8, 17, 26],
|
590 |
+
[9, 18, 27]]
|
591 |
+
ijk_space = [jk_plane1, jk_plane2, jk_plane3]
|
592 |
+
ikj_space = [kj_plane1, kj_plane2, kj_plane3]
|
593 |
+
jik_space = [ik_plane1, ik_plane2, ik_plane3]
|
594 |
+
jki_space = [ki_plane1, ki_plane2, ki_plane3]
|
595 |
+
kij_space = [ij_plane1, ij_plane2, ij_plane3]
|
596 |
+
x = array([plane1, plane2, plane3])
|
597 |
+
|
598 |
+
assert_array_almost_equal(fftn(x),
|
599 |
+
fftn(x, axes=(-3, -2, -1))) # kji_space
|
600 |
+
assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
|
601 |
+
assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
|
602 |
+
y = fftn(x, axes=(2, 1, 0)) # ijk_space
|
603 |
+
assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
|
604 |
+
y = fftn(x, axes=(2, 0, 1)) # ikj_space
|
605 |
+
assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
|
606 |
+
fftn(ikj_space))
|
607 |
+
y = fftn(x, axes=(1, 2, 0)) # jik_space
|
608 |
+
assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
|
609 |
+
fftn(jik_space))
|
610 |
+
y = fftn(x, axes=(1, 0, 2)) # jki_space
|
611 |
+
assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
|
612 |
+
y = fftn(x, axes=(0, 2, 1)) # kij_space
|
613 |
+
assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
|
614 |
+
|
615 |
+
y = fftn(x, axes=(-2, -1)) # ji_plane
|
616 |
+
assert_array_almost_equal(fftn(plane1), y[0])
|
617 |
+
assert_array_almost_equal(fftn(plane2), y[1])
|
618 |
+
assert_array_almost_equal(fftn(plane3), y[2])
|
619 |
+
|
620 |
+
y = fftn(x, axes=(1, 2)) # ji_plane
|
621 |
+
assert_array_almost_equal(fftn(plane1), y[0])
|
622 |
+
assert_array_almost_equal(fftn(plane2), y[1])
|
623 |
+
assert_array_almost_equal(fftn(plane3), y[2])
|
624 |
+
|
625 |
+
y = fftn(x, axes=(-3, -2)) # kj_plane
|
626 |
+
assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
|
627 |
+
assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
|
628 |
+
assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
|
629 |
+
|
630 |
+
y = fftn(x, axes=(-3, -1)) # ki_plane
|
631 |
+
assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
|
632 |
+
assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
|
633 |
+
assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
|
634 |
+
|
635 |
+
y = fftn(x, axes=(-1, -2)) # ij_plane
|
636 |
+
assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
|
637 |
+
assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
|
638 |
+
assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
|
639 |
+
|
640 |
+
y = fftn(x, axes=(-1, -3)) # ik_plane
|
641 |
+
assert_array_almost_equal(fftn(ik_plane1),
|
642 |
+
swapaxes(y[:, 0, :], -1, -2))
|
643 |
+
assert_array_almost_equal(fftn(ik_plane2),
|
644 |
+
swapaxes(y[:, 1, :], -1, -2))
|
645 |
+
assert_array_almost_equal(fftn(ik_plane3),
|
646 |
+
swapaxes(y[:, 2, :], -1, -2))
|
647 |
+
|
648 |
+
y = fftn(x, axes=(-2, -3)) # jk_plane
|
649 |
+
assert_array_almost_equal(fftn(jk_plane1),
|
650 |
+
swapaxes(y[:, :, 0], -1, -2))
|
651 |
+
assert_array_almost_equal(fftn(jk_plane2),
|
652 |
+
swapaxes(y[:, :, 1], -1, -2))
|
653 |
+
assert_array_almost_equal(fftn(jk_plane3),
|
654 |
+
swapaxes(y[:, :, 2], -1, -2))
|
655 |
+
|
656 |
+
y = fftn(x, axes=(-1,)) # i_line
|
657 |
+
for i in range(3):
|
658 |
+
for j in range(3):
|
659 |
+
assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
|
660 |
+
y = fftn(x, axes=(-2,)) # j_line
|
661 |
+
for i in range(3):
|
662 |
+
for j in range(3):
|
663 |
+
assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
|
664 |
+
y = fftn(x, axes=(0,)) # k_line
|
665 |
+
for i in range(3):
|
666 |
+
for j in range(3):
|
667 |
+
assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
|
668 |
+
|
669 |
+
y = fftn(x, axes=()) # point
|
670 |
+
assert_array_almost_equal(y, x)
|
671 |
+
|
672 |
+
def test_shape_argument(self):
|
673 |
+
small_x = [[1, 2, 3],
|
674 |
+
[4, 5, 6]]
|
675 |
+
large_x1 = [[1, 2, 3, 0],
|
676 |
+
[4, 5, 6, 0],
|
677 |
+
[0, 0, 0, 0],
|
678 |
+
[0, 0, 0, 0]]
|
679 |
+
|
680 |
+
y = fftn(small_x, s=(4, 4))
|
681 |
+
assert_array_almost_equal(y, fftn(large_x1))
|
682 |
+
|
683 |
+
y = fftn(small_x, s=(3, 4))
|
684 |
+
assert_array_almost_equal(y, fftn(large_x1[:-1]))
|
685 |
+
|
686 |
+
def test_shape_axes_argument(self):
|
687 |
+
small_x = [[1, 2, 3],
|
688 |
+
[4, 5, 6],
|
689 |
+
[7, 8, 9]]
|
690 |
+
large_x1 = array([[1, 2, 3, 0],
|
691 |
+
[4, 5, 6, 0],
|
692 |
+
[7, 8, 9, 0],
|
693 |
+
[0, 0, 0, 0]])
|
694 |
+
y = fftn(small_x, s=(4, 4), axes=(-2, -1))
|
695 |
+
assert_array_almost_equal(y, fftn(large_x1))
|
696 |
+
y = fftn(small_x, s=(4, 4), axes=(-1, -2))
|
697 |
+
|
698 |
+
assert_array_almost_equal(y, swapaxes(
|
699 |
+
fftn(swapaxes(large_x1, -1, -2)), -1, -2))
|
700 |
+
|
701 |
+
def test_shape_axes_argument2(self):
|
702 |
+
# Change shape of the last axis
|
703 |
+
x = numpy.random.random((10, 5, 3, 7))
|
704 |
+
y = fftn(x, axes=(-1,), s=(8,))
|
705 |
+
assert_array_almost_equal(y, fft(x, axis=-1, n=8))
|
706 |
+
|
707 |
+
# Change shape of an arbitrary axis which is not the last one
|
708 |
+
x = numpy.random.random((10, 5, 3, 7))
|
709 |
+
y = fftn(x, axes=(-2,), s=(8,))
|
710 |
+
assert_array_almost_equal(y, fft(x, axis=-2, n=8))
|
711 |
+
|
712 |
+
# Change shape of axes: cf #244, where shape and axes were mixed up
|
713 |
+
x = numpy.random.random((4, 4, 2))
|
714 |
+
y = fftn(x, axes=(-3, -2), s=(8, 8))
|
715 |
+
assert_array_almost_equal(y,
|
716 |
+
numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
|
717 |
+
|
718 |
+
def test_shape_argument_more(self):
|
719 |
+
x = zeros((4, 4, 2))
|
720 |
+
with assert_raises(ValueError,
|
721 |
+
match="shape requires more axes than are present"):
|
722 |
+
fftn(x, s=(8, 8, 2, 1))
|
723 |
+
|
724 |
+
def test_invalid_sizes(self):
|
725 |
+
with assert_raises(ValueError,
|
726 |
+
match="invalid number of data points"
|
727 |
+
r" \(\[1, 0\]\) specified"):
|
728 |
+
fftn([[]])
|
729 |
+
|
730 |
+
with assert_raises(ValueError,
|
731 |
+
match="invalid number of data points"
|
732 |
+
r" \(\[4, -3\]\) specified"):
|
733 |
+
fftn([[1, 1], [2, 2]], (4, -3))
|
734 |
+
|
735 |
+
def test_no_axes(self):
|
736 |
+
x = numpy.random.random((2,2,2))
|
737 |
+
assert_allclose(fftn(x, axes=[]), x, atol=1e-7)
|
738 |
+
|
739 |
+
def test_regression_244(self):
|
740 |
+
"""FFT returns wrong result with axes parameter."""
|
741 |
+
# fftn (and hence fft2) used to break when both axes and shape were used
|
742 |
+
x = numpy.ones((4, 4, 2))
|
743 |
+
y = fftn(x, s=(8, 8), axes=(-3, -2))
|
744 |
+
y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2))
|
745 |
+
assert_allclose(y, y_r)
|
746 |
+
|
747 |
+
|
748 |
+
class TestIfftn:
|
749 |
+
dtype = None
|
750 |
+
cdtype = None
|
751 |
+
|
752 |
+
def setup_method(self):
|
753 |
+
np.random.seed(1234)
|
754 |
+
|
755 |
+
@pytest.mark.parametrize('dtype,cdtype,maxnlp',
|
756 |
+
[(np.float64, np.complex128, 2000),
|
757 |
+
(np.float32, np.complex64, 3500)])
|
758 |
+
def test_definition(self, dtype, cdtype, maxnlp):
|
759 |
+
x = np.array([[1, 2, 3],
|
760 |
+
[4, 5, 6],
|
761 |
+
[7, 8, 9]], dtype=dtype)
|
762 |
+
y = ifftn(x)
|
763 |
+
assert_equal(y.dtype, cdtype)
|
764 |
+
assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp)
|
765 |
+
|
766 |
+
x = random((20, 26))
|
767 |
+
assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
|
768 |
+
|
769 |
+
x = random((5, 4, 3, 20))
|
770 |
+
assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
|
771 |
+
|
772 |
+
@pytest.mark.parametrize('maxnlp', [2000, 3500])
|
773 |
+
@pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
|
774 |
+
def test_random_complex(self, maxnlp, size):
|
775 |
+
x = random([size, size]) + 1j*random([size, size])
|
776 |
+
assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp)
|
777 |
+
assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp)
|
778 |
+
|
779 |
+
def test_invalid_sizes(self):
|
780 |
+
with assert_raises(ValueError,
|
781 |
+
match="invalid number of data points"
|
782 |
+
r" \(\[1, 0\]\) specified"):
|
783 |
+
ifftn([[]])
|
784 |
+
|
785 |
+
with assert_raises(ValueError,
|
786 |
+
match="invalid number of data points"
|
787 |
+
r" \(\[4, -3\]\) specified"):
|
788 |
+
ifftn([[1, 1], [2, 2]], (4, -3))
|
789 |
+
|
790 |
+
def test_no_axes(self):
|
791 |
+
x = numpy.random.random((2,2,2))
|
792 |
+
assert_allclose(ifftn(x, axes=[]), x, atol=1e-7)
|
793 |
+
|
794 |
+
class TestRfftn:
|
795 |
+
dtype = None
|
796 |
+
cdtype = None
|
797 |
+
|
798 |
+
def setup_method(self):
|
799 |
+
np.random.seed(1234)
|
800 |
+
|
801 |
+
@pytest.mark.parametrize('dtype,cdtype,maxnlp',
|
802 |
+
[(np.float64, np.complex128, 2000),
|
803 |
+
(np.float32, np.complex64, 3500)])
|
804 |
+
def test_definition(self, dtype, cdtype, maxnlp):
|
805 |
+
x = np.array([[1, 2, 3],
|
806 |
+
[4, 5, 6],
|
807 |
+
[7, 8, 9]], dtype=dtype)
|
808 |
+
y = rfftn(x)
|
809 |
+
assert_equal(y.dtype, cdtype)
|
810 |
+
assert_array_almost_equal_nulp(y, direct_rdftn(x), maxnlp)
|
811 |
+
|
812 |
+
x = random((20, 26))
|
813 |
+
assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp)
|
814 |
+
|
815 |
+
x = random((5, 4, 3, 20))
|
816 |
+
assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp)
|
817 |
+
|
818 |
+
@pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
|
819 |
+
def test_random(self, size):
|
820 |
+
x = random([size, size])
|
821 |
+
assert_allclose(irfftn(rfftn(x), x.shape), x, atol=1e-10)
|
822 |
+
|
823 |
+
@pytest.mark.parametrize('func', [rfftn, irfftn])
|
824 |
+
def test_invalid_sizes(self, func):
|
825 |
+
with assert_raises(ValueError,
|
826 |
+
match="invalid number of data points"
|
827 |
+
r" \(\[1, 0\]\) specified"):
|
828 |
+
func([[]])
|
829 |
+
|
830 |
+
with assert_raises(ValueError,
|
831 |
+
match="invalid number of data points"
|
832 |
+
r" \(\[4, -3\]\) specified"):
|
833 |
+
func([[1, 1], [2, 2]], (4, -3))
|
834 |
+
|
835 |
+
@pytest.mark.parametrize('func', [rfftn, irfftn])
|
836 |
+
def test_no_axes(self, func):
|
837 |
+
with assert_raises(ValueError,
|
838 |
+
match="at least 1 axis must be transformed"):
|
839 |
+
func([], axes=[])
|
840 |
+
|
841 |
+
def test_complex_input(self):
|
842 |
+
with assert_raises(TypeError, match="x must be a real sequence"):
|
843 |
+
rfftn(np.zeros(10, dtype=np.complex64))
|
844 |
+
|
845 |
+
|
846 |
+
class FakeArray:
|
847 |
+
def __init__(self, data):
|
848 |
+
self._data = data
|
849 |
+
self.__array_interface__ = data.__array_interface__
|
850 |
+
|
851 |
+
|
852 |
+
class FakeArray2:
|
853 |
+
def __init__(self, data):
|
854 |
+
self._data = data
|
855 |
+
|
856 |
+
def __array__(self, dtype=None, copy=None):
|
857 |
+
return self._data
|
858 |
+
|
859 |
+
# TODO: Is this test actually valuable? The behavior it's testing shouldn't be
|
860 |
+
# relied upon by users except for overwrite_x = False
|
861 |
+
class TestOverwrite:
|
862 |
+
"""Check input overwrite behavior of the FFT functions."""
|
863 |
+
|
864 |
+
real_dtypes = [np.float32, np.float64, np.longdouble]
|
865 |
+
dtypes = real_dtypes + [np.complex64, np.complex128, np.clongdouble]
|
866 |
+
fftsizes = [8, 16, 32]
|
867 |
+
|
868 |
+
def _check(self, x, routine, fftsize, axis, overwrite_x, should_overwrite):
|
869 |
+
x2 = x.copy()
|
870 |
+
for fake in [lambda x: x, FakeArray, FakeArray2]:
|
871 |
+
routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x)
|
872 |
+
|
873 |
+
sig = "{}({}{!r}, {!r}, axis={!r}, overwrite_x={!r})".format(
|
874 |
+
routine.__name__, x.dtype, x.shape, fftsize, axis, overwrite_x)
|
875 |
+
if not should_overwrite:
|
876 |
+
assert_equal(x2, x, err_msg="spurious overwrite in %s" % sig)
|
877 |
+
|
878 |
+
def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes,
|
879 |
+
fftsize, overwrite_x):
|
880 |
+
np.random.seed(1234)
|
881 |
+
if np.issubdtype(dtype, np.complexfloating):
|
882 |
+
data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
|
883 |
+
else:
|
884 |
+
data = np.random.randn(*shape)
|
885 |
+
data = data.astype(dtype)
|
886 |
+
|
887 |
+
should_overwrite = (overwrite_x
|
888 |
+
and dtype in overwritable_dtypes
|
889 |
+
and fftsize <= shape[axis])
|
890 |
+
self._check(data, routine, fftsize, axis,
|
891 |
+
overwrite_x=overwrite_x,
|
892 |
+
should_overwrite=should_overwrite)
|
893 |
+
|
894 |
+
@pytest.mark.parametrize('dtype', dtypes)
|
895 |
+
@pytest.mark.parametrize('fftsize', fftsizes)
|
896 |
+
@pytest.mark.parametrize('overwrite_x', [True, False])
|
897 |
+
@pytest.mark.parametrize('shape,axes', [((16,), -1),
|
898 |
+
((16, 2), 0),
|
899 |
+
((2, 16), 1)])
|
900 |
+
def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes):
|
901 |
+
overwritable = (np.clongdouble, np.complex128, np.complex64)
|
902 |
+
self._check_1d(fft, dtype, shape, axes, overwritable,
|
903 |
+
fftsize, overwrite_x)
|
904 |
+
self._check_1d(ifft, dtype, shape, axes, overwritable,
|
905 |
+
fftsize, overwrite_x)
|
906 |
+
|
907 |
+
@pytest.mark.parametrize('dtype', real_dtypes)
|
908 |
+
@pytest.mark.parametrize('fftsize', fftsizes)
|
909 |
+
@pytest.mark.parametrize('overwrite_x', [True, False])
|
910 |
+
@pytest.mark.parametrize('shape,axes', [((16,), -1),
|
911 |
+
((16, 2), 0),
|
912 |
+
((2, 16), 1)])
|
913 |
+
def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes):
|
914 |
+
overwritable = self.real_dtypes
|
915 |
+
self._check_1d(irfft, dtype, shape, axes, overwritable,
|
916 |
+
fftsize, overwrite_x)
|
917 |
+
self._check_1d(rfft, dtype, shape, axes, overwritable,
|
918 |
+
fftsize, overwrite_x)
|
919 |
+
|
920 |
+
def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes,
|
921 |
+
overwrite_x):
|
922 |
+
np.random.seed(1234)
|
923 |
+
if np.issubdtype(dtype, np.complexfloating):
|
924 |
+
data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
|
925 |
+
else:
|
926 |
+
data = np.random.randn(*shape)
|
927 |
+
data = data.astype(dtype)
|
928 |
+
|
929 |
+
def fftshape_iter(shp):
|
930 |
+
if len(shp) <= 0:
|
931 |
+
yield ()
|
932 |
+
else:
|
933 |
+
for j in (shp[0]//2, shp[0], shp[0]*2):
|
934 |
+
for rest in fftshape_iter(shp[1:]):
|
935 |
+
yield (j,) + rest
|
936 |
+
|
937 |
+
def part_shape(shape, axes):
|
938 |
+
if axes is None:
|
939 |
+
return shape
|
940 |
+
else:
|
941 |
+
return tuple(np.take(shape, axes))
|
942 |
+
|
943 |
+
def should_overwrite(data, shape, axes):
|
944 |
+
s = part_shape(data.shape, axes)
|
945 |
+
return (overwrite_x and
|
946 |
+
np.prod(shape) <= np.prod(s)
|
947 |
+
and dtype in overwritable_dtypes)
|
948 |
+
|
949 |
+
for fftshape in fftshape_iter(part_shape(shape, axes)):
|
950 |
+
self._check(data, routine, fftshape, axes,
|
951 |
+
overwrite_x=overwrite_x,
|
952 |
+
should_overwrite=should_overwrite(data, fftshape, axes))
|
953 |
+
if data.ndim > 1:
|
954 |
+
# check fortran order
|
955 |
+
self._check(data.T, routine, fftshape, axes,
|
956 |
+
overwrite_x=overwrite_x,
|
957 |
+
should_overwrite=should_overwrite(
|
958 |
+
data.T, fftshape, axes))
|
959 |
+
|
960 |
+
@pytest.mark.parametrize('dtype', dtypes)
|
961 |
+
@pytest.mark.parametrize('overwrite_x', [True, False])
|
962 |
+
@pytest.mark.parametrize('shape,axes', [((16,), None),
|
963 |
+
((16,), (0,)),
|
964 |
+
((16, 2), (0,)),
|
965 |
+
((2, 16), (1,)),
|
966 |
+
((8, 16), None),
|
967 |
+
((8, 16), (0, 1)),
|
968 |
+
((8, 16, 2), (0, 1)),
|
969 |
+
((8, 16, 2), (1, 2)),
|
970 |
+
((8, 16, 2), (0,)),
|
971 |
+
((8, 16, 2), (1,)),
|
972 |
+
((8, 16, 2), (2,)),
|
973 |
+
((8, 16, 2), None),
|
974 |
+
((8, 16, 2), (0, 1, 2))])
|
975 |
+
def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes):
|
976 |
+
overwritable = (np.clongdouble, np.complex128, np.complex64)
|
977 |
+
self._check_nd_one(fftn, dtype, shape, axes, overwritable,
|
978 |
+
overwrite_x)
|
979 |
+
self._check_nd_one(ifftn, dtype, shape, axes, overwritable,
|
980 |
+
overwrite_x)
|
981 |
+
|
982 |
+
|
983 |
+
@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn,
|
984 |
+
rfft, irfft, rfftn, irfftn])
|
985 |
+
def test_invalid_norm(func):
|
986 |
+
x = np.arange(10, dtype=float)
|
987 |
+
with assert_raises(ValueError,
|
988 |
+
match='Invalid norm value \'o\', should be'
|
989 |
+
' "backward", "ortho" or "forward"'):
|
990 |
+
func(x, norm='o')
|
991 |
+
|
992 |
+
|
993 |
+
@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn,
|
994 |
+
irfft, irfftn, hfft, hfftn])
|
995 |
+
def test_swapped_byte_order_complex(func):
|
996 |
+
rng = np.random.RandomState(1234)
|
997 |
+
x = rng.rand(10) + 1j * rng.rand(10)
|
998 |
+
assert_allclose(func(swap_byteorder(x)), func(x))
|
999 |
+
|
1000 |
+
|
1001 |
+
@pytest.mark.parametrize('func', [ihfft, ihfftn, rfft, rfftn])
|
1002 |
+
def test_swapped_byte_order_real(func):
|
1003 |
+
rng = np.random.RandomState(1234)
|
1004 |
+
x = rng.rand(10)
|
1005 |
+
assert_allclose(func(swap_byteorder(x)), func(x))
|
venv/lib/python3.10/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py
ADDED
@@ -0,0 +1,494 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from os.path import join, dirname
|
2 |
+
from typing import Callable, Union
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
from numpy.testing import (
|
6 |
+
assert_array_almost_equal, assert_equal, assert_allclose)
|
7 |
+
import pytest
|
8 |
+
from pytest import raises as assert_raises
|
9 |
+
|
10 |
+
from scipy.fft._pocketfft.realtransforms import (
|
11 |
+
dct, idct, dst, idst, dctn, idctn, dstn, idstn)
|
12 |
+
|
13 |
+
fftpack_test_dir = join(dirname(__file__), '..', '..', '..', 'fftpack', 'tests')
|
14 |
+
|
15 |
+
MDATA_COUNT = 8
|
16 |
+
FFTWDATA_COUNT = 14
|
17 |
+
|
18 |
+
def is_longdouble_binary_compatible():
|
19 |
+
try:
|
20 |
+
one = np.frombuffer(
|
21 |
+
b'\x00\x00\x00\x00\x00\x00\x00\x80\xff\x3f\x00\x00\x00\x00\x00\x00',
|
22 |
+
dtype='<f16')
|
23 |
+
return one == np.longdouble(1.)
|
24 |
+
except TypeError:
|
25 |
+
return False
|
26 |
+
|
27 |
+
|
28 |
+
@pytest.fixture(scope="module")
|
29 |
+
def reference_data():
|
30 |
+
# Matlab reference data
|
31 |
+
MDATA = np.load(join(fftpack_test_dir, 'test.npz'))
|
32 |
+
X = [MDATA['x%d' % i] for i in range(MDATA_COUNT)]
|
33 |
+
Y = [MDATA['y%d' % i] for i in range(MDATA_COUNT)]
|
34 |
+
|
35 |
+
# FFTW reference data: the data are organized as follows:
|
36 |
+
# * SIZES is an array containing all available sizes
|
37 |
+
# * for every type (1, 2, 3, 4) and every size, the array dct_type_size
|
38 |
+
# contains the output of the DCT applied to the input np.linspace(0, size-1,
|
39 |
+
# size)
|
40 |
+
FFTWDATA_DOUBLE = np.load(join(fftpack_test_dir, 'fftw_double_ref.npz'))
|
41 |
+
FFTWDATA_SINGLE = np.load(join(fftpack_test_dir, 'fftw_single_ref.npz'))
|
42 |
+
FFTWDATA_SIZES = FFTWDATA_DOUBLE['sizes']
|
43 |
+
assert len(FFTWDATA_SIZES) == FFTWDATA_COUNT
|
44 |
+
|
45 |
+
if is_longdouble_binary_compatible():
|
46 |
+
FFTWDATA_LONGDOUBLE = np.load(
|
47 |
+
join(fftpack_test_dir, 'fftw_longdouble_ref.npz'))
|
48 |
+
else:
|
49 |
+
FFTWDATA_LONGDOUBLE = {k: v.astype(np.longdouble)
|
50 |
+
for k,v in FFTWDATA_DOUBLE.items()}
|
51 |
+
|
52 |
+
ref = {
|
53 |
+
'FFTWDATA_LONGDOUBLE': FFTWDATA_LONGDOUBLE,
|
54 |
+
'FFTWDATA_DOUBLE': FFTWDATA_DOUBLE,
|
55 |
+
'FFTWDATA_SINGLE': FFTWDATA_SINGLE,
|
56 |
+
'FFTWDATA_SIZES': FFTWDATA_SIZES,
|
57 |
+
'X': X,
|
58 |
+
'Y': Y
|
59 |
+
}
|
60 |
+
|
61 |
+
yield ref
|
62 |
+
|
63 |
+
if is_longdouble_binary_compatible():
|
64 |
+
FFTWDATA_LONGDOUBLE.close()
|
65 |
+
FFTWDATA_SINGLE.close()
|
66 |
+
FFTWDATA_DOUBLE.close()
|
67 |
+
MDATA.close()
|
68 |
+
|
69 |
+
|
70 |
+
@pytest.fixture(params=range(FFTWDATA_COUNT))
|
71 |
+
def fftwdata_size(request, reference_data):
|
72 |
+
return reference_data['FFTWDATA_SIZES'][request.param]
|
73 |
+
|
74 |
+
@pytest.fixture(params=range(MDATA_COUNT))
|
75 |
+
def mdata_x(request, reference_data):
|
76 |
+
return reference_data['X'][request.param]
|
77 |
+
|
78 |
+
|
79 |
+
@pytest.fixture(params=range(MDATA_COUNT))
|
80 |
+
def mdata_xy(request, reference_data):
|
81 |
+
y = reference_data['Y'][request.param]
|
82 |
+
x = reference_data['X'][request.param]
|
83 |
+
return x, y
|
84 |
+
|
85 |
+
|
86 |
+
def fftw_dct_ref(type, size, dt, reference_data):
|
87 |
+
x = np.linspace(0, size-1, size).astype(dt)
|
88 |
+
dt = np.result_type(np.float32, dt)
|
89 |
+
if dt == np.float64:
|
90 |
+
data = reference_data['FFTWDATA_DOUBLE']
|
91 |
+
elif dt == np.float32:
|
92 |
+
data = reference_data['FFTWDATA_SINGLE']
|
93 |
+
elif dt == np.longdouble:
|
94 |
+
data = reference_data['FFTWDATA_LONGDOUBLE']
|
95 |
+
else:
|
96 |
+
raise ValueError()
|
97 |
+
y = (data['dct_%d_%d' % (type, size)]).astype(dt)
|
98 |
+
return x, y, dt
|
99 |
+
|
100 |
+
|
101 |
+
def fftw_dst_ref(type, size, dt, reference_data):
|
102 |
+
x = np.linspace(0, size-1, size).astype(dt)
|
103 |
+
dt = np.result_type(np.float32, dt)
|
104 |
+
if dt == np.float64:
|
105 |
+
data = reference_data['FFTWDATA_DOUBLE']
|
106 |
+
elif dt == np.float32:
|
107 |
+
data = reference_data['FFTWDATA_SINGLE']
|
108 |
+
elif dt == np.longdouble:
|
109 |
+
data = reference_data['FFTWDATA_LONGDOUBLE']
|
110 |
+
else:
|
111 |
+
raise ValueError()
|
112 |
+
y = (data['dst_%d_%d' % (type, size)]).astype(dt)
|
113 |
+
return x, y, dt
|
114 |
+
|
115 |
+
|
116 |
+
def ref_2d(func, x, **kwargs):
|
117 |
+
"""Calculate 2-D reference data from a 1d transform"""
|
118 |
+
x = np.array(x, copy=True)
|
119 |
+
for row in range(x.shape[0]):
|
120 |
+
x[row, :] = func(x[row, :], **kwargs)
|
121 |
+
for col in range(x.shape[1]):
|
122 |
+
x[:, col] = func(x[:, col], **kwargs)
|
123 |
+
return x
|
124 |
+
|
125 |
+
|
126 |
+
def naive_dct1(x, norm=None):
|
127 |
+
"""Calculate textbook definition version of DCT-I."""
|
128 |
+
x = np.array(x, copy=True)
|
129 |
+
N = len(x)
|
130 |
+
M = N-1
|
131 |
+
y = np.zeros(N)
|
132 |
+
m0, m = 1, 2
|
133 |
+
if norm == 'ortho':
|
134 |
+
m0 = np.sqrt(1.0/M)
|
135 |
+
m = np.sqrt(2.0/M)
|
136 |
+
for k in range(N):
|
137 |
+
for n in range(1, N-1):
|
138 |
+
y[k] += m*x[n]*np.cos(np.pi*n*k/M)
|
139 |
+
y[k] += m0 * x[0]
|
140 |
+
y[k] += m0 * x[N-1] * (1 if k % 2 == 0 else -1)
|
141 |
+
if norm == 'ortho':
|
142 |
+
y[0] *= 1/np.sqrt(2)
|
143 |
+
y[N-1] *= 1/np.sqrt(2)
|
144 |
+
return y
|
145 |
+
|
146 |
+
|
147 |
+
def naive_dst1(x, norm=None):
|
148 |
+
"""Calculate textbook definition version of DST-I."""
|
149 |
+
x = np.array(x, copy=True)
|
150 |
+
N = len(x)
|
151 |
+
M = N+1
|
152 |
+
y = np.zeros(N)
|
153 |
+
for k in range(N):
|
154 |
+
for n in range(N):
|
155 |
+
y[k] += 2*x[n]*np.sin(np.pi*(n+1.0)*(k+1.0)/M)
|
156 |
+
if norm == 'ortho':
|
157 |
+
y *= np.sqrt(0.5/M)
|
158 |
+
return y
|
159 |
+
|
160 |
+
|
161 |
+
def naive_dct4(x, norm=None):
|
162 |
+
"""Calculate textbook definition version of DCT-IV."""
|
163 |
+
x = np.array(x, copy=True)
|
164 |
+
N = len(x)
|
165 |
+
y = np.zeros(N)
|
166 |
+
for k in range(N):
|
167 |
+
for n in range(N):
|
168 |
+
y[k] += x[n]*np.cos(np.pi*(n+0.5)*(k+0.5)/(N))
|
169 |
+
if norm == 'ortho':
|
170 |
+
y *= np.sqrt(2.0/N)
|
171 |
+
else:
|
172 |
+
y *= 2
|
173 |
+
return y
|
174 |
+
|
175 |
+
|
176 |
+
def naive_dst4(x, norm=None):
|
177 |
+
"""Calculate textbook definition version of DST-IV."""
|
178 |
+
x = np.array(x, copy=True)
|
179 |
+
N = len(x)
|
180 |
+
y = np.zeros(N)
|
181 |
+
for k in range(N):
|
182 |
+
for n in range(N):
|
183 |
+
y[k] += x[n]*np.sin(np.pi*(n+0.5)*(k+0.5)/(N))
|
184 |
+
if norm == 'ortho':
|
185 |
+
y *= np.sqrt(2.0/N)
|
186 |
+
else:
|
187 |
+
y *= 2
|
188 |
+
return y
|
189 |
+
|
190 |
+
|
191 |
+
@pytest.mark.parametrize('dtype', [np.complex64, np.complex128, np.clongdouble])
|
192 |
+
@pytest.mark.parametrize('transform', [dct, dst, idct, idst])
|
193 |
+
def test_complex(transform, dtype):
|
194 |
+
y = transform(1j*np.arange(5, dtype=dtype))
|
195 |
+
x = 1j*transform(np.arange(5))
|
196 |
+
assert_array_almost_equal(x, y)
|
197 |
+
|
198 |
+
|
199 |
+
DecMapType = dict[
|
200 |
+
tuple[Callable[..., np.ndarray], Union[type[np.floating], type[int]], int],
|
201 |
+
int,
|
202 |
+
]
|
203 |
+
|
204 |
+
# map (transform, dtype, type) -> decimal
|
205 |
+
dec_map: DecMapType = {
|
206 |
+
# DCT
|
207 |
+
(dct, np.float64, 1): 13,
|
208 |
+
(dct, np.float32, 1): 6,
|
209 |
+
|
210 |
+
(dct, np.float64, 2): 14,
|
211 |
+
(dct, np.float32, 2): 5,
|
212 |
+
|
213 |
+
(dct, np.float64, 3): 14,
|
214 |
+
(dct, np.float32, 3): 5,
|
215 |
+
|
216 |
+
(dct, np.float64, 4): 13,
|
217 |
+
(dct, np.float32, 4): 6,
|
218 |
+
|
219 |
+
# IDCT
|
220 |
+
(idct, np.float64, 1): 14,
|
221 |
+
(idct, np.float32, 1): 6,
|
222 |
+
|
223 |
+
(idct, np.float64, 2): 14,
|
224 |
+
(idct, np.float32, 2): 5,
|
225 |
+
|
226 |
+
(idct, np.float64, 3): 14,
|
227 |
+
(idct, np.float32, 3): 5,
|
228 |
+
|
229 |
+
(idct, np.float64, 4): 14,
|
230 |
+
(idct, np.float32, 4): 6,
|
231 |
+
|
232 |
+
# DST
|
233 |
+
(dst, np.float64, 1): 13,
|
234 |
+
(dst, np.float32, 1): 6,
|
235 |
+
|
236 |
+
(dst, np.float64, 2): 14,
|
237 |
+
(dst, np.float32, 2): 6,
|
238 |
+
|
239 |
+
(dst, np.float64, 3): 14,
|
240 |
+
(dst, np.float32, 3): 7,
|
241 |
+
|
242 |
+
(dst, np.float64, 4): 13,
|
243 |
+
(dst, np.float32, 4): 5,
|
244 |
+
|
245 |
+
# IDST
|
246 |
+
(idst, np.float64, 1): 14,
|
247 |
+
(idst, np.float32, 1): 6,
|
248 |
+
|
249 |
+
(idst, np.float64, 2): 14,
|
250 |
+
(idst, np.float32, 2): 6,
|
251 |
+
|
252 |
+
(idst, np.float64, 3): 14,
|
253 |
+
(idst, np.float32, 3): 6,
|
254 |
+
|
255 |
+
(idst, np.float64, 4): 14,
|
256 |
+
(idst, np.float32, 4): 6,
|
257 |
+
}
|
258 |
+
|
259 |
+
for k,v in dec_map.copy().items():
|
260 |
+
if k[1] == np.float64:
|
261 |
+
dec_map[(k[0], np.longdouble, k[2])] = v
|
262 |
+
elif k[1] == np.float32:
|
263 |
+
dec_map[(k[0], int, k[2])] = v
|
264 |
+
|
265 |
+
|
266 |
+
@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
|
267 |
+
@pytest.mark.parametrize('type', [1, 2, 3, 4])
|
268 |
+
class TestDCT:
|
269 |
+
def test_definition(self, rdt, type, fftwdata_size, reference_data):
|
270 |
+
x, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data)
|
271 |
+
y = dct(x, type=type)
|
272 |
+
assert_equal(y.dtype, dt)
|
273 |
+
dec = dec_map[(dct, rdt, type)]
|
274 |
+
assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec))
|
275 |
+
|
276 |
+
@pytest.mark.parametrize('size', [7, 8, 9, 16, 32, 64])
|
277 |
+
def test_axis(self, rdt, type, size):
|
278 |
+
nt = 2
|
279 |
+
dec = dec_map[(dct, rdt, type)]
|
280 |
+
x = np.random.randn(nt, size)
|
281 |
+
y = dct(x, type=type)
|
282 |
+
for j in range(nt):
|
283 |
+
assert_array_almost_equal(y[j], dct(x[j], type=type),
|
284 |
+
decimal=dec)
|
285 |
+
|
286 |
+
x = x.T
|
287 |
+
y = dct(x, axis=0, type=type)
|
288 |
+
for j in range(nt):
|
289 |
+
assert_array_almost_equal(y[:,j], dct(x[:,j], type=type),
|
290 |
+
decimal=dec)
|
291 |
+
|
292 |
+
|
293 |
+
@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
|
294 |
+
def test_dct1_definition_ortho(rdt, mdata_x):
|
295 |
+
# Test orthornomal mode.
|
296 |
+
dec = dec_map[(dct, rdt, 1)]
|
297 |
+
x = np.array(mdata_x, dtype=rdt)
|
298 |
+
dt = np.result_type(np.float32, rdt)
|
299 |
+
y = dct(x, norm='ortho', type=1)
|
300 |
+
y2 = naive_dct1(x, norm='ortho')
|
301 |
+
assert_equal(y.dtype, dt)
|
302 |
+
assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
|
303 |
+
|
304 |
+
|
305 |
+
@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
|
306 |
+
def test_dct2_definition_matlab(mdata_xy, rdt):
|
307 |
+
# Test correspondence with matlab (orthornomal mode).
|
308 |
+
dt = np.result_type(np.float32, rdt)
|
309 |
+
x = np.array(mdata_xy[0], dtype=dt)
|
310 |
+
|
311 |
+
yr = mdata_xy[1]
|
312 |
+
y = dct(x, norm="ortho", type=2)
|
313 |
+
dec = dec_map[(dct, rdt, 2)]
|
314 |
+
assert_equal(y.dtype, dt)
|
315 |
+
assert_array_almost_equal(y, yr, decimal=dec)
|
316 |
+
|
317 |
+
|
318 |
+
@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
|
319 |
+
def test_dct3_definition_ortho(mdata_x, rdt):
|
320 |
+
# Test orthornomal mode.
|
321 |
+
x = np.array(mdata_x, dtype=rdt)
|
322 |
+
dt = np.result_type(np.float32, rdt)
|
323 |
+
y = dct(x, norm='ortho', type=2)
|
324 |
+
xi = dct(y, norm="ortho", type=3)
|
325 |
+
dec = dec_map[(dct, rdt, 3)]
|
326 |
+
assert_equal(xi.dtype, dt)
|
327 |
+
assert_array_almost_equal(xi, x, decimal=dec)
|
328 |
+
|
329 |
+
|
330 |
+
@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
|
331 |
+
def test_dct4_definition_ortho(mdata_x, rdt):
|
332 |
+
# Test orthornomal mode.
|
333 |
+
x = np.array(mdata_x, dtype=rdt)
|
334 |
+
dt = np.result_type(np.float32, rdt)
|
335 |
+
y = dct(x, norm='ortho', type=4)
|
336 |
+
y2 = naive_dct4(x, norm='ortho')
|
337 |
+
dec = dec_map[(dct, rdt, 4)]
|
338 |
+
assert_equal(y.dtype, dt)
|
339 |
+
assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
|
340 |
+
|
341 |
+
|
342 |
+
@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
|
343 |
+
@pytest.mark.parametrize('type', [1, 2, 3, 4])
|
344 |
+
def test_idct_definition(fftwdata_size, rdt, type, reference_data):
|
345 |
+
xr, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data)
|
346 |
+
x = idct(yr, type=type)
|
347 |
+
dec = dec_map[(idct, rdt, type)]
|
348 |
+
assert_equal(x.dtype, dt)
|
349 |
+
assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec))
|
350 |
+
|
351 |
+
|
352 |
+
@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
|
353 |
+
@pytest.mark.parametrize('type', [1, 2, 3, 4])
|
354 |
+
def test_definition(fftwdata_size, rdt, type, reference_data):
|
355 |
+
xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data)
|
356 |
+
y = dst(xr, type=type)
|
357 |
+
dec = dec_map[(dst, rdt, type)]
|
358 |
+
assert_equal(y.dtype, dt)
|
359 |
+
assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec))
|
360 |
+
|
361 |
+
|
362 |
+
@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
|
363 |
+
def test_dst1_definition_ortho(rdt, mdata_x):
|
364 |
+
# Test orthornomal mode.
|
365 |
+
dec = dec_map[(dst, rdt, 1)]
|
366 |
+
x = np.array(mdata_x, dtype=rdt)
|
367 |
+
dt = np.result_type(np.float32, rdt)
|
368 |
+
y = dst(x, norm='ortho', type=1)
|
369 |
+
y2 = naive_dst1(x, norm='ortho')
|
370 |
+
assert_equal(y.dtype, dt)
|
371 |
+
assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
|
372 |
+
|
373 |
+
|
374 |
+
@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
|
375 |
+
def test_dst4_definition_ortho(rdt, mdata_x):
|
376 |
+
# Test orthornomal mode.
|
377 |
+
dec = dec_map[(dst, rdt, 4)]
|
378 |
+
x = np.array(mdata_x, dtype=rdt)
|
379 |
+
dt = np.result_type(np.float32, rdt)
|
380 |
+
y = dst(x, norm='ortho', type=4)
|
381 |
+
y2 = naive_dst4(x, norm='ortho')
|
382 |
+
assert_equal(y.dtype, dt)
|
383 |
+
assert_array_almost_equal(y, y2, decimal=dec)
|
384 |
+
|
385 |
+
|
386 |
+
@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
|
387 |
+
@pytest.mark.parametrize('type', [1, 2, 3, 4])
|
388 |
+
def test_idst_definition(fftwdata_size, rdt, type, reference_data):
|
389 |
+
xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data)
|
390 |
+
x = idst(yr, type=type)
|
391 |
+
dec = dec_map[(idst, rdt, type)]
|
392 |
+
assert_equal(x.dtype, dt)
|
393 |
+
assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec))
|
394 |
+
|
395 |
+
|
396 |
+
@pytest.mark.parametrize('routine', [dct, dst, idct, idst])
|
397 |
+
@pytest.mark.parametrize('dtype', [np.float32, np.float64, np.longdouble])
|
398 |
+
@pytest.mark.parametrize('shape, axis', [
|
399 |
+
((16,), -1), ((16, 2), 0), ((2, 16), 1)
|
400 |
+
])
|
401 |
+
@pytest.mark.parametrize('type', [1, 2, 3, 4])
|
402 |
+
@pytest.mark.parametrize('overwrite_x', [True, False])
|
403 |
+
@pytest.mark.parametrize('norm', [None, 'ortho'])
|
404 |
+
def test_overwrite(routine, dtype, shape, axis, type, norm, overwrite_x):
|
405 |
+
# Check input overwrite behavior
|
406 |
+
np.random.seed(1234)
|
407 |
+
if np.issubdtype(dtype, np.complexfloating):
|
408 |
+
x = np.random.randn(*shape) + 1j*np.random.randn(*shape)
|
409 |
+
else:
|
410 |
+
x = np.random.randn(*shape)
|
411 |
+
x = x.astype(dtype)
|
412 |
+
x2 = x.copy()
|
413 |
+
routine(x2, type, None, axis, norm, overwrite_x=overwrite_x)
|
414 |
+
|
415 |
+
sig = "{}({}{!r}, {!r}, axis={!r}, overwrite_x={!r})".format(
|
416 |
+
routine.__name__, x.dtype, x.shape, None, axis, overwrite_x)
|
417 |
+
if not overwrite_x:
|
418 |
+
assert_equal(x2, x, err_msg="spurious overwrite in %s" % sig)
|
419 |
+
|
420 |
+
|
421 |
+
class Test_DCTN_IDCTN:
|
422 |
+
dec = 14
|
423 |
+
dct_type = [1, 2, 3, 4]
|
424 |
+
norms = [None, 'backward', 'ortho', 'forward']
|
425 |
+
rstate = np.random.RandomState(1234)
|
426 |
+
shape = (32, 16)
|
427 |
+
data = rstate.randn(*shape)
|
428 |
+
|
429 |
+
@pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
|
430 |
+
(dstn, idstn)])
|
431 |
+
@pytest.mark.parametrize('axes', [None,
|
432 |
+
1, (1,), [1],
|
433 |
+
0, (0,), [0],
|
434 |
+
(0, 1), [0, 1],
|
435 |
+
(-2, -1), [-2, -1]])
|
436 |
+
@pytest.mark.parametrize('dct_type', dct_type)
|
437 |
+
@pytest.mark.parametrize('norm', ['ortho'])
|
438 |
+
def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
|
439 |
+
tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
|
440 |
+
tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
|
441 |
+
assert_array_almost_equal(self.data, tmp, decimal=12)
|
442 |
+
|
443 |
+
@pytest.mark.parametrize('funcn,func', [(dctn, dct), (dstn, dst)])
|
444 |
+
@pytest.mark.parametrize('dct_type', dct_type)
|
445 |
+
@pytest.mark.parametrize('norm', norms)
|
446 |
+
def test_dctn_vs_2d_reference(self, funcn, func, dct_type, norm):
|
447 |
+
y1 = funcn(self.data, type=dct_type, axes=None, norm=norm)
|
448 |
+
y2 = ref_2d(func, self.data, type=dct_type, norm=norm)
|
449 |
+
assert_array_almost_equal(y1, y2, decimal=11)
|
450 |
+
|
451 |
+
@pytest.mark.parametrize('funcn,func', [(idctn, idct), (idstn, idst)])
|
452 |
+
@pytest.mark.parametrize('dct_type', dct_type)
|
453 |
+
@pytest.mark.parametrize('norm', norms)
|
454 |
+
def test_idctn_vs_2d_reference(self, funcn, func, dct_type, norm):
|
455 |
+
fdata = dctn(self.data, type=dct_type, norm=norm)
|
456 |
+
y1 = funcn(fdata, type=dct_type, norm=norm)
|
457 |
+
y2 = ref_2d(func, fdata, type=dct_type, norm=norm)
|
458 |
+
assert_array_almost_equal(y1, y2, decimal=11)
|
459 |
+
|
460 |
+
@pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
|
461 |
+
(dstn, idstn)])
|
462 |
+
def test_axes_and_shape(self, fforward, finverse):
|
463 |
+
with assert_raises(ValueError,
|
464 |
+
match="when given, axes and shape arguments"
|
465 |
+
" have to be of the same length"):
|
466 |
+
fforward(self.data, s=self.data.shape[0], axes=(0, 1))
|
467 |
+
|
468 |
+
with assert_raises(ValueError,
|
469 |
+
match="when given, axes and shape arguments"
|
470 |
+
" have to be of the same length"):
|
471 |
+
fforward(self.data, s=self.data.shape, axes=0)
|
472 |
+
|
473 |
+
@pytest.mark.parametrize('fforward', [dctn, dstn])
|
474 |
+
def test_shape(self, fforward):
|
475 |
+
tmp = fforward(self.data, s=(128, 128), axes=None)
|
476 |
+
assert_equal(tmp.shape, (128, 128))
|
477 |
+
|
478 |
+
@pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
|
479 |
+
(dstn, idstn)])
|
480 |
+
@pytest.mark.parametrize('axes', [1, (1,), [1],
|
481 |
+
0, (0,), [0]])
|
482 |
+
def test_shape_is_none_with_axes(self, fforward, finverse, axes):
|
483 |
+
tmp = fforward(self.data, s=None, axes=axes, norm='ortho')
|
484 |
+
tmp = finverse(tmp, s=None, axes=axes, norm='ortho')
|
485 |
+
assert_array_almost_equal(self.data, tmp, decimal=self.dec)
|
486 |
+
|
487 |
+
|
488 |
+
@pytest.mark.parametrize('func', [dct, dctn, idct, idctn,
|
489 |
+
dst, dstn, idst, idstn])
|
490 |
+
def test_swapped_byte_order(func):
|
491 |
+
rng = np.random.RandomState(1234)
|
492 |
+
x = rng.rand(10)
|
493 |
+
swapped_dt = x.dtype.newbyteorder('S')
|
494 |
+
assert_allclose(func(x.astype(swapped_dt)), func(x))
|
venv/lib/python3.10/site-packages/scipy/fft/_realtransforms.py
ADDED
@@ -0,0 +1,693 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from ._basic import _dispatch
|
2 |
+
from scipy._lib.uarray import Dispatchable
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
|
6 |
+
|
7 |
+
|
8 |
+
@_dispatch
|
9 |
+
def dctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
|
10 |
+
workers=None, *, orthogonalize=None):
|
11 |
+
"""
|
12 |
+
Return multidimensional Discrete Cosine Transform along the specified axes.
|
13 |
+
|
14 |
+
Parameters
|
15 |
+
----------
|
16 |
+
x : array_like
|
17 |
+
The input array.
|
18 |
+
type : {1, 2, 3, 4}, optional
|
19 |
+
Type of the DCT (see Notes). Default type is 2.
|
20 |
+
s : int or array_like of ints or None, optional
|
21 |
+
The shape of the result. If both `s` and `axes` (see below) are None,
|
22 |
+
`s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
|
23 |
+
``numpy.take(x.shape, axes, axis=0)``.
|
24 |
+
If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
|
25 |
+
If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
|
26 |
+
``s[i]``.
|
27 |
+
If any element of `s` is -1, the size of the corresponding dimension of
|
28 |
+
`x` is used.
|
29 |
+
axes : int or array_like of ints or None, optional
|
30 |
+
Axes over which the DCT is computed. If not given, the last ``len(s)``
|
31 |
+
axes are used, or all axes if `s` is also not specified.
|
32 |
+
norm : {"backward", "ortho", "forward"}, optional
|
33 |
+
Normalization mode (see Notes). Default is "backward".
|
34 |
+
overwrite_x : bool, optional
|
35 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
36 |
+
workers : int, optional
|
37 |
+
Maximum number of workers to use for parallel computation. If negative,
|
38 |
+
the value wraps around from ``os.cpu_count()``.
|
39 |
+
See :func:`~scipy.fft.fft` for more details.
|
40 |
+
orthogonalize : bool, optional
|
41 |
+
Whether to use the orthogonalized DCT variant (see Notes).
|
42 |
+
Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
|
43 |
+
|
44 |
+
.. versionadded:: 1.8.0
|
45 |
+
|
46 |
+
Returns
|
47 |
+
-------
|
48 |
+
y : ndarray of real
|
49 |
+
The transformed input array.
|
50 |
+
|
51 |
+
See Also
|
52 |
+
--------
|
53 |
+
idctn : Inverse multidimensional DCT
|
54 |
+
|
55 |
+
Notes
|
56 |
+
-----
|
57 |
+
For full details of the DCT types and normalization modes, as well as
|
58 |
+
references, see `dct`.
|
59 |
+
|
60 |
+
Examples
|
61 |
+
--------
|
62 |
+
>>> import numpy as np
|
63 |
+
>>> from scipy.fft import dctn, idctn
|
64 |
+
>>> rng = np.random.default_rng()
|
65 |
+
>>> y = rng.standard_normal((16, 16))
|
66 |
+
>>> np.allclose(y, idctn(dctn(y)))
|
67 |
+
True
|
68 |
+
|
69 |
+
"""
|
70 |
+
return (Dispatchable(x, np.ndarray),)
|
71 |
+
|
72 |
+
|
73 |
+
@_dispatch
|
74 |
+
def idctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
|
75 |
+
workers=None, orthogonalize=None):
|
76 |
+
"""
|
77 |
+
Return multidimensional Inverse Discrete Cosine Transform along the specified axes.
|
78 |
+
|
79 |
+
Parameters
|
80 |
+
----------
|
81 |
+
x : array_like
|
82 |
+
The input array.
|
83 |
+
type : {1, 2, 3, 4}, optional
|
84 |
+
Type of the DCT (see Notes). Default type is 2.
|
85 |
+
s : int or array_like of ints or None, optional
|
86 |
+
The shape of the result. If both `s` and `axes` (see below) are
|
87 |
+
None, `s` is ``x.shape``; if `s` is None but `axes` is
|
88 |
+
not None, then `s` is ``numpy.take(x.shape, axes, axis=0)``.
|
89 |
+
If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
|
90 |
+
If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
|
91 |
+
``s[i]``.
|
92 |
+
If any element of `s` is -1, the size of the corresponding dimension of
|
93 |
+
`x` is used.
|
94 |
+
axes : int or array_like of ints or None, optional
|
95 |
+
Axes over which the IDCT is computed. If not given, the last ``len(s)``
|
96 |
+
axes are used, or all axes if `s` is also not specified.
|
97 |
+
norm : {"backward", "ortho", "forward"}, optional
|
98 |
+
Normalization mode (see Notes). Default is "backward".
|
99 |
+
overwrite_x : bool, optional
|
100 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
101 |
+
workers : int, optional
|
102 |
+
Maximum number of workers to use for parallel computation. If negative,
|
103 |
+
the value wraps around from ``os.cpu_count()``.
|
104 |
+
See :func:`~scipy.fft.fft` for more details.
|
105 |
+
orthogonalize : bool, optional
|
106 |
+
Whether to use the orthogonalized IDCT variant (see Notes).
|
107 |
+
Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
|
108 |
+
|
109 |
+
.. versionadded:: 1.8.0
|
110 |
+
|
111 |
+
Returns
|
112 |
+
-------
|
113 |
+
y : ndarray of real
|
114 |
+
The transformed input array.
|
115 |
+
|
116 |
+
See Also
|
117 |
+
--------
|
118 |
+
dctn : multidimensional DCT
|
119 |
+
|
120 |
+
Notes
|
121 |
+
-----
|
122 |
+
For full details of the IDCT types and normalization modes, as well as
|
123 |
+
references, see `idct`.
|
124 |
+
|
125 |
+
Examples
|
126 |
+
--------
|
127 |
+
>>> import numpy as np
|
128 |
+
>>> from scipy.fft import dctn, idctn
|
129 |
+
>>> rng = np.random.default_rng()
|
130 |
+
>>> y = rng.standard_normal((16, 16))
|
131 |
+
>>> np.allclose(y, idctn(dctn(y)))
|
132 |
+
True
|
133 |
+
|
134 |
+
"""
|
135 |
+
return (Dispatchable(x, np.ndarray),)
|
136 |
+
|
137 |
+
|
138 |
+
@_dispatch
|
139 |
+
def dstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
|
140 |
+
workers=None, orthogonalize=None):
|
141 |
+
"""
|
142 |
+
Return multidimensional Discrete Sine Transform along the specified axes.
|
143 |
+
|
144 |
+
Parameters
|
145 |
+
----------
|
146 |
+
x : array_like
|
147 |
+
The input array.
|
148 |
+
type : {1, 2, 3, 4}, optional
|
149 |
+
Type of the DST (see Notes). Default type is 2.
|
150 |
+
s : int or array_like of ints or None, optional
|
151 |
+
The shape of the result. If both `s` and `axes` (see below) are None,
|
152 |
+
`s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
|
153 |
+
``numpy.take(x.shape, axes, axis=0)``.
|
154 |
+
If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
|
155 |
+
If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
|
156 |
+
``s[i]``.
|
157 |
+
If any element of `shape` is -1, the size of the corresponding dimension
|
158 |
+
of `x` is used.
|
159 |
+
axes : int or array_like of ints or None, optional
|
160 |
+
Axes over which the DST is computed. If not given, the last ``len(s)``
|
161 |
+
axes are used, or all axes if `s` is also not specified.
|
162 |
+
norm : {"backward", "ortho", "forward"}, optional
|
163 |
+
Normalization mode (see Notes). Default is "backward".
|
164 |
+
overwrite_x : bool, optional
|
165 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
166 |
+
workers : int, optional
|
167 |
+
Maximum number of workers to use for parallel computation. If negative,
|
168 |
+
the value wraps around from ``os.cpu_count()``.
|
169 |
+
See :func:`~scipy.fft.fft` for more details.
|
170 |
+
orthogonalize : bool, optional
|
171 |
+
Whether to use the orthogonalized DST variant (see Notes).
|
172 |
+
Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
|
173 |
+
|
174 |
+
.. versionadded:: 1.8.0
|
175 |
+
|
176 |
+
Returns
|
177 |
+
-------
|
178 |
+
y : ndarray of real
|
179 |
+
The transformed input array.
|
180 |
+
|
181 |
+
See Also
|
182 |
+
--------
|
183 |
+
idstn : Inverse multidimensional DST
|
184 |
+
|
185 |
+
Notes
|
186 |
+
-----
|
187 |
+
For full details of the DST types and normalization modes, as well as
|
188 |
+
references, see `dst`.
|
189 |
+
|
190 |
+
Examples
|
191 |
+
--------
|
192 |
+
>>> import numpy as np
|
193 |
+
>>> from scipy.fft import dstn, idstn
|
194 |
+
>>> rng = np.random.default_rng()
|
195 |
+
>>> y = rng.standard_normal((16, 16))
|
196 |
+
>>> np.allclose(y, idstn(dstn(y)))
|
197 |
+
True
|
198 |
+
|
199 |
+
"""
|
200 |
+
return (Dispatchable(x, np.ndarray),)
|
201 |
+
|
202 |
+
|
203 |
+
@_dispatch
|
204 |
+
def idstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False,
|
205 |
+
workers=None, orthogonalize=None):
|
206 |
+
"""
|
207 |
+
Return multidimensional Inverse Discrete Sine Transform along the specified axes.
|
208 |
+
|
209 |
+
Parameters
|
210 |
+
----------
|
211 |
+
x : array_like
|
212 |
+
The input array.
|
213 |
+
type : {1, 2, 3, 4}, optional
|
214 |
+
Type of the DST (see Notes). Default type is 2.
|
215 |
+
s : int or array_like of ints or None, optional
|
216 |
+
The shape of the result. If both `s` and `axes` (see below) are None,
|
217 |
+
`s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is
|
218 |
+
``numpy.take(x.shape, axes, axis=0)``.
|
219 |
+
If ``s[i] > x.shape[i]``, the ith dimension of the input is padded with zeros.
|
220 |
+
If ``s[i] < x.shape[i]``, the ith dimension of the input is truncated to length
|
221 |
+
``s[i]``.
|
222 |
+
If any element of `s` is -1, the size of the corresponding dimension of
|
223 |
+
`x` is used.
|
224 |
+
axes : int or array_like of ints or None, optional
|
225 |
+
Axes over which the IDST is computed. If not given, the last ``len(s)``
|
226 |
+
axes are used, or all axes if `s` is also not specified.
|
227 |
+
norm : {"backward", "ortho", "forward"}, optional
|
228 |
+
Normalization mode (see Notes). Default is "backward".
|
229 |
+
overwrite_x : bool, optional
|
230 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
231 |
+
workers : int, optional
|
232 |
+
Maximum number of workers to use for parallel computation. If negative,
|
233 |
+
the value wraps around from ``os.cpu_count()``.
|
234 |
+
See :func:`~scipy.fft.fft` for more details.
|
235 |
+
orthogonalize : bool, optional
|
236 |
+
Whether to use the orthogonalized IDST variant (see Notes).
|
237 |
+
Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
|
238 |
+
|
239 |
+
.. versionadded:: 1.8.0
|
240 |
+
|
241 |
+
Returns
|
242 |
+
-------
|
243 |
+
y : ndarray of real
|
244 |
+
The transformed input array.
|
245 |
+
|
246 |
+
See Also
|
247 |
+
--------
|
248 |
+
dstn : multidimensional DST
|
249 |
+
|
250 |
+
Notes
|
251 |
+
-----
|
252 |
+
For full details of the IDST types and normalization modes, as well as
|
253 |
+
references, see `idst`.
|
254 |
+
|
255 |
+
Examples
|
256 |
+
--------
|
257 |
+
>>> import numpy as np
|
258 |
+
>>> from scipy.fft import dstn, idstn
|
259 |
+
>>> rng = np.random.default_rng()
|
260 |
+
>>> y = rng.standard_normal((16, 16))
|
261 |
+
>>> np.allclose(y, idstn(dstn(y)))
|
262 |
+
True
|
263 |
+
|
264 |
+
"""
|
265 |
+
return (Dispatchable(x, np.ndarray),)
|
266 |
+
|
267 |
+
|
268 |
+
@_dispatch
|
269 |
+
def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
|
270 |
+
orthogonalize=None):
|
271 |
+
r"""Return the Discrete Cosine Transform of arbitrary type sequence x.
|
272 |
+
|
273 |
+
Parameters
|
274 |
+
----------
|
275 |
+
x : array_like
|
276 |
+
The input array.
|
277 |
+
type : {1, 2, 3, 4}, optional
|
278 |
+
Type of the DCT (see Notes). Default type is 2.
|
279 |
+
n : int, optional
|
280 |
+
Length of the transform. If ``n < x.shape[axis]``, `x` is
|
281 |
+
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
|
282 |
+
default results in ``n = x.shape[axis]``.
|
283 |
+
axis : int, optional
|
284 |
+
Axis along which the dct is computed; the default is over the
|
285 |
+
last axis (i.e., ``axis=-1``).
|
286 |
+
norm : {"backward", "ortho", "forward"}, optional
|
287 |
+
Normalization mode (see Notes). Default is "backward".
|
288 |
+
overwrite_x : bool, optional
|
289 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
290 |
+
workers : int, optional
|
291 |
+
Maximum number of workers to use for parallel computation. If negative,
|
292 |
+
the value wraps around from ``os.cpu_count()``.
|
293 |
+
See :func:`~scipy.fft.fft` for more details.
|
294 |
+
orthogonalize : bool, optional
|
295 |
+
Whether to use the orthogonalized DCT variant (see Notes).
|
296 |
+
Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
|
297 |
+
|
298 |
+
.. versionadded:: 1.8.0
|
299 |
+
|
300 |
+
Returns
|
301 |
+
-------
|
302 |
+
y : ndarray of real
|
303 |
+
The transformed input array.
|
304 |
+
|
305 |
+
See Also
|
306 |
+
--------
|
307 |
+
idct : Inverse DCT
|
308 |
+
|
309 |
+
Notes
|
310 |
+
-----
|
311 |
+
For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to
|
312 |
+
MATLAB ``dct(x)``.
|
313 |
+
|
314 |
+
.. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
|
315 |
+
correspondence with the direct Fourier transform. To recover
|
316 |
+
it you must specify ``orthogonalize=False``.
|
317 |
+
|
318 |
+
For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
|
319 |
+
overall factor in both directions. By default, the transform is also
|
320 |
+
orthogonalized which for types 1, 2 and 3 means the transform definition is
|
321 |
+
modified to give orthogonality of the DCT matrix (see below).
|
322 |
+
|
323 |
+
For ``norm="backward"``, there is no scaling on `dct` and the `idct` is
|
324 |
+
scaled by ``1/N`` where ``N`` is the "logical" size of the DCT. For
|
325 |
+
``norm="forward"`` the ``1/N`` normalization is applied to the forward
|
326 |
+
`dct` instead and the `idct` is unnormalized.
|
327 |
+
|
328 |
+
There are, theoretically, 8 types of the DCT, only the first 4 types are
|
329 |
+
implemented in SciPy.'The' DCT generally refers to DCT type 2, and 'the'
|
330 |
+
Inverse DCT generally refers to DCT type 3.
|
331 |
+
|
332 |
+
**Type I**
|
333 |
+
|
334 |
+
There are several definitions of the DCT-I; we use the following
|
335 |
+
(for ``norm="backward"``)
|
336 |
+
|
337 |
+
.. math::
|
338 |
+
|
339 |
+
y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left(
|
340 |
+
\frac{\pi k n}{N-1} \right)
|
341 |
+
|
342 |
+
If ``orthogonalize=True``, ``x[0]`` and ``x[N-1]`` are multiplied by a
|
343 |
+
scaling factor of :math:`\sqrt{2}`, and ``y[0]`` and ``y[N-1]`` are divided
|
344 |
+
by :math:`\sqrt{2}`. When combined with ``norm="ortho"``, this makes the
|
345 |
+
corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
|
346 |
+
|
347 |
+
.. note::
|
348 |
+
The DCT-I is only supported for input size > 1.
|
349 |
+
|
350 |
+
**Type II**
|
351 |
+
|
352 |
+
There are several definitions of the DCT-II; we use the following
|
353 |
+
(for ``norm="backward"``)
|
354 |
+
|
355 |
+
.. math::
|
356 |
+
|
357 |
+
y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
|
358 |
+
|
359 |
+
If ``orthogonalize=True``, ``y[0]`` is divided by :math:`\sqrt{2}` which,
|
360 |
+
when combined with ``norm="ortho"``, makes the corresponding matrix of
|
361 |
+
coefficients orthonormal (``O @ O.T = np.eye(N)``).
|
362 |
+
|
363 |
+
**Type III**
|
364 |
+
|
365 |
+
There are several definitions, we use the following (for
|
366 |
+
``norm="backward"``)
|
367 |
+
|
368 |
+
.. math::
|
369 |
+
|
370 |
+
y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
|
371 |
+
|
372 |
+
If ``orthogonalize=True``, ``x[0]`` terms are multiplied by
|
373 |
+
:math:`\sqrt{2}` which, when combined with ``norm="ortho"``, makes the
|
374 |
+
corresponding matrix of coefficients orthonormal (``O @ O.T = np.eye(N)``).
|
375 |
+
|
376 |
+
The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up
|
377 |
+
to a factor `2N`. The orthonormalized DCT-III is exactly the inverse of
|
378 |
+
the orthonormalized DCT-II.
|
379 |
+
|
380 |
+
**Type IV**
|
381 |
+
|
382 |
+
There are several definitions of the DCT-IV; we use the following
|
383 |
+
(for ``norm="backward"``)
|
384 |
+
|
385 |
+
.. math::
|
386 |
+
|
387 |
+
y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
|
388 |
+
|
389 |
+
``orthogonalize`` has no effect here, as the DCT-IV matrix is already
|
390 |
+
orthogonal up to a scale factor of ``2N``.
|
391 |
+
|
392 |
+
References
|
393 |
+
----------
|
394 |
+
.. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J.
|
395 |
+
Makhoul, `IEEE Transactions on acoustics, speech and signal
|
396 |
+
processing` vol. 28(1), pp. 27-34,
|
397 |
+
:doi:`10.1109/TASSP.1980.1163351` (1980).
|
398 |
+
.. [2] Wikipedia, "Discrete cosine transform",
|
399 |
+
https://en.wikipedia.org/wiki/Discrete_cosine_transform
|
400 |
+
|
401 |
+
Examples
|
402 |
+
--------
|
403 |
+
The Type 1 DCT is equivalent to the FFT (though faster) for real,
|
404 |
+
even-symmetrical inputs. The output is also real and even-symmetrical.
|
405 |
+
Half of the FFT input is used to generate half of the FFT output:
|
406 |
+
|
407 |
+
>>> from scipy.fft import fft, dct
|
408 |
+
>>> import numpy as np
|
409 |
+
>>> fft(np.array([4., 3., 5., 10., 5., 3.])).real
|
410 |
+
array([ 30., -8., 6., -2., 6., -8.])
|
411 |
+
>>> dct(np.array([4., 3., 5., 10.]), 1)
|
412 |
+
array([ 30., -8., 6., -2.])
|
413 |
+
|
414 |
+
"""
|
415 |
+
return (Dispatchable(x, np.ndarray),)
|
416 |
+
|
417 |
+
|
418 |
+
@_dispatch
|
419 |
+
def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
|
420 |
+
workers=None, orthogonalize=None):
|
421 |
+
"""
|
422 |
+
Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
|
423 |
+
|
424 |
+
Parameters
|
425 |
+
----------
|
426 |
+
x : array_like
|
427 |
+
The input array.
|
428 |
+
type : {1, 2, 3, 4}, optional
|
429 |
+
Type of the DCT (see Notes). Default type is 2.
|
430 |
+
n : int, optional
|
431 |
+
Length of the transform. If ``n < x.shape[axis]``, `x` is
|
432 |
+
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
|
433 |
+
default results in ``n = x.shape[axis]``.
|
434 |
+
axis : int, optional
|
435 |
+
Axis along which the idct is computed; the default is over the
|
436 |
+
last axis (i.e., ``axis=-1``).
|
437 |
+
norm : {"backward", "ortho", "forward"}, optional
|
438 |
+
Normalization mode (see Notes). Default is "backward".
|
439 |
+
overwrite_x : bool, optional
|
440 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
441 |
+
workers : int, optional
|
442 |
+
Maximum number of workers to use for parallel computation. If negative,
|
443 |
+
the value wraps around from ``os.cpu_count()``.
|
444 |
+
See :func:`~scipy.fft.fft` for more details.
|
445 |
+
orthogonalize : bool, optional
|
446 |
+
Whether to use the orthogonalized IDCT variant (see Notes).
|
447 |
+
Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
|
448 |
+
|
449 |
+
.. versionadded:: 1.8.0
|
450 |
+
|
451 |
+
Returns
|
452 |
+
-------
|
453 |
+
idct : ndarray of real
|
454 |
+
The transformed input array.
|
455 |
+
|
456 |
+
See Also
|
457 |
+
--------
|
458 |
+
dct : Forward DCT
|
459 |
+
|
460 |
+
Notes
|
461 |
+
-----
|
462 |
+
For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
|
463 |
+
MATLAB ``idct(x)``.
|
464 |
+
|
465 |
+
.. warning:: For ``type in {1, 2, 3}``, ``norm="ortho"`` breaks the direct
|
466 |
+
correspondence with the inverse direct Fourier transform. To
|
467 |
+
recover it you must specify ``orthogonalize=False``.
|
468 |
+
|
469 |
+
For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same
|
470 |
+
overall factor in both directions. By default, the transform is also
|
471 |
+
orthogonalized which for types 1, 2 and 3 means the transform definition is
|
472 |
+
modified to give orthogonality of the IDCT matrix (see `dct` for the full
|
473 |
+
definitions).
|
474 |
+
|
475 |
+
'The' IDCT is the IDCT-II, which is the same as the normalized DCT-III.
|
476 |
+
|
477 |
+
The IDCT is equivalent to a normal DCT except for the normalization and
|
478 |
+
type. DCT type 1 and 4 are their own inverse and DCTs 2 and 3 are each
|
479 |
+
other's inverses.
|
480 |
+
|
481 |
+
Examples
|
482 |
+
--------
|
483 |
+
The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
|
484 |
+
inputs. The output is also real and even-symmetrical. Half of the IFFT
|
485 |
+
input is used to generate half of the IFFT output:
|
486 |
+
|
487 |
+
>>> from scipy.fft import ifft, idct
|
488 |
+
>>> import numpy as np
|
489 |
+
>>> ifft(np.array([ 30., -8., 6., -2., 6., -8.])).real
|
490 |
+
array([ 4., 3., 5., 10., 5., 3.])
|
491 |
+
>>> idct(np.array([ 30., -8., 6., -2.]), 1)
|
492 |
+
array([ 4., 3., 5., 10.])
|
493 |
+
|
494 |
+
"""
|
495 |
+
return (Dispatchable(x, np.ndarray),)
|
496 |
+
|
497 |
+
|
498 |
+
@_dispatch
|
499 |
+
def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False, workers=None,
|
500 |
+
orthogonalize=None):
|
501 |
+
r"""
|
502 |
+
Return the Discrete Sine Transform of arbitrary type sequence x.
|
503 |
+
|
504 |
+
Parameters
|
505 |
+
----------
|
506 |
+
x : array_like
|
507 |
+
The input array.
|
508 |
+
type : {1, 2, 3, 4}, optional
|
509 |
+
Type of the DST (see Notes). Default type is 2.
|
510 |
+
n : int, optional
|
511 |
+
Length of the transform. If ``n < x.shape[axis]``, `x` is
|
512 |
+
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
|
513 |
+
default results in ``n = x.shape[axis]``.
|
514 |
+
axis : int, optional
|
515 |
+
Axis along which the dst is computed; the default is over the
|
516 |
+
last axis (i.e., ``axis=-1``).
|
517 |
+
norm : {"backward", "ortho", "forward"}, optional
|
518 |
+
Normalization mode (see Notes). Default is "backward".
|
519 |
+
overwrite_x : bool, optional
|
520 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
521 |
+
workers : int, optional
|
522 |
+
Maximum number of workers to use for parallel computation. If negative,
|
523 |
+
the value wraps around from ``os.cpu_count()``.
|
524 |
+
See :func:`~scipy.fft.fft` for more details.
|
525 |
+
orthogonalize : bool, optional
|
526 |
+
Whether to use the orthogonalized DST variant (see Notes).
|
527 |
+
Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
|
528 |
+
|
529 |
+
.. versionadded:: 1.8.0
|
530 |
+
|
531 |
+
Returns
|
532 |
+
-------
|
533 |
+
dst : ndarray of reals
|
534 |
+
The transformed input array.
|
535 |
+
|
536 |
+
See Also
|
537 |
+
--------
|
538 |
+
idst : Inverse DST
|
539 |
+
|
540 |
+
Notes
|
541 |
+
-----
|
542 |
+
.. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
|
543 |
+
correspondence with the direct Fourier transform. To recover
|
544 |
+
it you must specify ``orthogonalize=False``.
|
545 |
+
|
546 |
+
For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
|
547 |
+
overall factor in both directions. By default, the transform is also
|
548 |
+
orthogonalized which for types 2 and 3 means the transform definition is
|
549 |
+
modified to give orthogonality of the DST matrix (see below).
|
550 |
+
|
551 |
+
For ``norm="backward"``, there is no scaling on the `dst` and the `idst` is
|
552 |
+
scaled by ``1/N`` where ``N`` is the "logical" size of the DST.
|
553 |
+
|
554 |
+
There are, theoretically, 8 types of the DST for different combinations of
|
555 |
+
even/odd boundary conditions and boundary off sets [1]_, only the first
|
556 |
+
4 types are implemented in SciPy.
|
557 |
+
|
558 |
+
**Type I**
|
559 |
+
|
560 |
+
There are several definitions of the DST-I; we use the following for
|
561 |
+
``norm="backward"``. DST-I assumes the input is odd around :math:`n=-1` and
|
562 |
+
:math:`n=N`.
|
563 |
+
|
564 |
+
.. math::
|
565 |
+
|
566 |
+
y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right)
|
567 |
+
|
568 |
+
Note that the DST-I is only supported for input size > 1.
|
569 |
+
The (unnormalized) DST-I is its own inverse, up to a factor :math:`2(N+1)`.
|
570 |
+
The orthonormalized DST-I is exactly its own inverse.
|
571 |
+
|
572 |
+
``orthogonalize`` has no effect here, as the DST-I matrix is already
|
573 |
+
orthogonal up to a scale factor of ``2N``.
|
574 |
+
|
575 |
+
**Type II**
|
576 |
+
|
577 |
+
There are several definitions of the DST-II; we use the following for
|
578 |
+
``norm="backward"``. DST-II assumes the input is odd around :math:`n=-1/2` and
|
579 |
+
:math:`n=N-1/2`; the output is odd around :math:`k=-1` and even around :math:`k=N-1`
|
580 |
+
|
581 |
+
.. math::
|
582 |
+
|
583 |
+
y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right)
|
584 |
+
|
585 |
+
If ``orthogonalize=True``, ``y[-1]`` is divided :math:`\sqrt{2}` which, when
|
586 |
+
combined with ``norm="ortho"``, makes the corresponding matrix of
|
587 |
+
coefficients orthonormal (``O @ O.T = np.eye(N)``).
|
588 |
+
|
589 |
+
**Type III**
|
590 |
+
|
591 |
+
There are several definitions of the DST-III, we use the following (for
|
592 |
+
``norm="backward"``). DST-III assumes the input is odd around :math:`n=-1` and
|
593 |
+
even around :math:`n=N-1`
|
594 |
+
|
595 |
+
.. math::
|
596 |
+
|
597 |
+
y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left(
|
598 |
+
\frac{\pi(2k+1)(n+1)}{2N}\right)
|
599 |
+
|
600 |
+
If ``orthogonalize=True``, ``x[-1]`` is multiplied by :math:`\sqrt{2}`
|
601 |
+
which, when combined with ``norm="ortho"``, makes the corresponding matrix
|
602 |
+
of coefficients orthonormal (``O @ O.T = np.eye(N)``).
|
603 |
+
|
604 |
+
The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
|
605 |
+
to a factor :math:`2N`. The orthonormalized DST-III is exactly the inverse of the
|
606 |
+
orthonormalized DST-II.
|
607 |
+
|
608 |
+
**Type IV**
|
609 |
+
|
610 |
+
There are several definitions of the DST-IV, we use the following (for
|
611 |
+
``norm="backward"``). DST-IV assumes the input is odd around :math:`n=-0.5` and
|
612 |
+
even around :math:`n=N-0.5`
|
613 |
+
|
614 |
+
.. math::
|
615 |
+
|
616 |
+
y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right)
|
617 |
+
|
618 |
+
``orthogonalize`` has no effect here, as the DST-IV matrix is already
|
619 |
+
orthogonal up to a scale factor of ``2N``.
|
620 |
+
|
621 |
+
The (unnormalized) DST-IV is its own inverse, up to a factor :math:`2N`. The
|
622 |
+
orthonormalized DST-IV is exactly its own inverse.
|
623 |
+
|
624 |
+
References
|
625 |
+
----------
|
626 |
+
.. [1] Wikipedia, "Discrete sine transform",
|
627 |
+
https://en.wikipedia.org/wiki/Discrete_sine_transform
|
628 |
+
|
629 |
+
"""
|
630 |
+
return (Dispatchable(x, np.ndarray),)
|
631 |
+
|
632 |
+
|
633 |
+
@_dispatch
|
634 |
+
def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False,
|
635 |
+
workers=None, orthogonalize=None):
|
636 |
+
"""
|
637 |
+
Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
|
638 |
+
|
639 |
+
Parameters
|
640 |
+
----------
|
641 |
+
x : array_like
|
642 |
+
The input array.
|
643 |
+
type : {1, 2, 3, 4}, optional
|
644 |
+
Type of the DST (see Notes). Default type is 2.
|
645 |
+
n : int, optional
|
646 |
+
Length of the transform. If ``n < x.shape[axis]``, `x` is
|
647 |
+
truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
|
648 |
+
default results in ``n = x.shape[axis]``.
|
649 |
+
axis : int, optional
|
650 |
+
Axis along which the idst is computed; the default is over the
|
651 |
+
last axis (i.e., ``axis=-1``).
|
652 |
+
norm : {"backward", "ortho", "forward"}, optional
|
653 |
+
Normalization mode (see Notes). Default is "backward".
|
654 |
+
overwrite_x : bool, optional
|
655 |
+
If True, the contents of `x` can be destroyed; the default is False.
|
656 |
+
workers : int, optional
|
657 |
+
Maximum number of workers to use for parallel computation. If negative,
|
658 |
+
the value wraps around from ``os.cpu_count()``.
|
659 |
+
See :func:`~scipy.fft.fft` for more details.
|
660 |
+
orthogonalize : bool, optional
|
661 |
+
Whether to use the orthogonalized IDST variant (see Notes).
|
662 |
+
Defaults to ``True`` when ``norm="ortho"`` and ``False`` otherwise.
|
663 |
+
|
664 |
+
.. versionadded:: 1.8.0
|
665 |
+
|
666 |
+
Returns
|
667 |
+
-------
|
668 |
+
idst : ndarray of real
|
669 |
+
The transformed input array.
|
670 |
+
|
671 |
+
See Also
|
672 |
+
--------
|
673 |
+
dst : Forward DST
|
674 |
+
|
675 |
+
Notes
|
676 |
+
-----
|
677 |
+
.. warning:: For ``type in {2, 3}``, ``norm="ortho"`` breaks the direct
|
678 |
+
correspondence with the inverse direct Fourier transform.
|
679 |
+
|
680 |
+
For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same
|
681 |
+
overall factor in both directions. By default, the transform is also
|
682 |
+
orthogonalized which for types 2 and 3 means the transform definition is
|
683 |
+
modified to give orthogonality of the DST matrix (see `dst` for the full
|
684 |
+
definitions).
|
685 |
+
|
686 |
+
'The' IDST is the IDST-II, which is the same as the normalized DST-III.
|
687 |
+
|
688 |
+
The IDST is equivalent to a normal DST except for the normalization and
|
689 |
+
type. DST type 1 and 4 are their own inverse and DSTs 2 and 3 are each
|
690 |
+
other's inverses.
|
691 |
+
|
692 |
+
"""
|
693 |
+
return (Dispatchable(x, np.ndarray),)
|
venv/lib/python3.10/site-packages/scipy/fft/_realtransforms_backend.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from scipy._lib._array_api import array_namespace
|
2 |
+
import numpy as np
|
3 |
+
from . import _pocketfft
|
4 |
+
|
5 |
+
__all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
|
6 |
+
|
7 |
+
|
8 |
+
def _execute(pocketfft_func, x, type, s, axes, norm,
|
9 |
+
overwrite_x, workers, orthogonalize):
|
10 |
+
xp = array_namespace(x)
|
11 |
+
x = np.asarray(x)
|
12 |
+
y = pocketfft_func(x, type, s, axes, norm,
|
13 |
+
overwrite_x=overwrite_x, workers=workers,
|
14 |
+
orthogonalize=orthogonalize)
|
15 |
+
return xp.asarray(y)
|
16 |
+
|
17 |
+
|
18 |
+
def dctn(x, type=2, s=None, axes=None, norm=None,
|
19 |
+
overwrite_x=False, workers=None, *, orthogonalize=None):
|
20 |
+
return _execute(_pocketfft.dctn, x, type, s, axes, norm,
|
21 |
+
overwrite_x, workers, orthogonalize)
|
22 |
+
|
23 |
+
|
24 |
+
def idctn(x, type=2, s=None, axes=None, norm=None,
|
25 |
+
overwrite_x=False, workers=None, *, orthogonalize=None):
|
26 |
+
return _execute(_pocketfft.idctn, x, type, s, axes, norm,
|
27 |
+
overwrite_x, workers, orthogonalize)
|
28 |
+
|
29 |
+
|
30 |
+
def dstn(x, type=2, s=None, axes=None, norm=None,
|
31 |
+
overwrite_x=False, workers=None, orthogonalize=None):
|
32 |
+
return _execute(_pocketfft.dstn, x, type, s, axes, norm,
|
33 |
+
overwrite_x, workers, orthogonalize)
|
34 |
+
|
35 |
+
|
36 |
+
def idstn(x, type=2, s=None, axes=None, norm=None,
|
37 |
+
overwrite_x=False, workers=None, *, orthogonalize=None):
|
38 |
+
return _execute(_pocketfft.idstn, x, type, s, axes, norm,
|
39 |
+
overwrite_x, workers, orthogonalize)
|
40 |
+
|
41 |
+
|
42 |
+
def dct(x, type=2, n=None, axis=-1, norm=None,
|
43 |
+
overwrite_x=False, workers=None, orthogonalize=None):
|
44 |
+
return _execute(_pocketfft.dct, x, type, n, axis, norm,
|
45 |
+
overwrite_x, workers, orthogonalize)
|
46 |
+
|
47 |
+
|
48 |
+
def idct(x, type=2, n=None, axis=-1, norm=None,
|
49 |
+
overwrite_x=False, workers=None, orthogonalize=None):
|
50 |
+
return _execute(_pocketfft.idct, x, type, n, axis, norm,
|
51 |
+
overwrite_x, workers, orthogonalize)
|
52 |
+
|
53 |
+
|
54 |
+
def dst(x, type=2, n=None, axis=-1, norm=None,
|
55 |
+
overwrite_x=False, workers=None, orthogonalize=None):
|
56 |
+
return _execute(_pocketfft.dst, x, type, n, axis, norm,
|
57 |
+
overwrite_x, workers, orthogonalize)
|
58 |
+
|
59 |
+
|
60 |
+
def idst(x, type=2, n=None, axis=-1, norm=None,
|
61 |
+
overwrite_x=False, workers=None, orthogonalize=None):
|
62 |
+
return _execute(_pocketfft.idst, x, type, n, axis, norm,
|
63 |
+
overwrite_x, workers, orthogonalize)
|
venv/lib/python3.10/site-packages/scipy/fft/tests/__init__.py
ADDED
File without changes
|
venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/mock_backend.cpython-310.pyc
ADDED
Binary file (2.09 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_backend.cpython-310.pyc
ADDED
Binary file (2.67 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_basic.cpython-310.pyc
ADDED
Binary file (17.3 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_fftlog.cpython-310.pyc
ADDED
Binary file (3.92 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_multithreading.cpython-310.pyc
ADDED
Binary file (2.94 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/tests/__pycache__/test_real_transforms.cpython-310.pyc
ADDED
Binary file (5.92 kB). View file
|
|
venv/lib/python3.10/site-packages/scipy/fft/tests/mock_backend.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import scipy.fft
|
3 |
+
|
4 |
+
class _MockFunction:
|
5 |
+
def __init__(self, return_value = None):
|
6 |
+
self.number_calls = 0
|
7 |
+
self.return_value = return_value
|
8 |
+
self.last_args = ([], {})
|
9 |
+
|
10 |
+
def __call__(self, *args, **kwargs):
|
11 |
+
self.number_calls += 1
|
12 |
+
self.last_args = (args, kwargs)
|
13 |
+
return self.return_value
|
14 |
+
|
15 |
+
|
16 |
+
fft = _MockFunction(np.random.random(10))
|
17 |
+
fft2 = _MockFunction(np.random.random(10))
|
18 |
+
fftn = _MockFunction(np.random.random(10))
|
19 |
+
|
20 |
+
ifft = _MockFunction(np.random.random(10))
|
21 |
+
ifft2 = _MockFunction(np.random.random(10))
|
22 |
+
ifftn = _MockFunction(np.random.random(10))
|
23 |
+
|
24 |
+
rfft = _MockFunction(np.random.random(10))
|
25 |
+
rfft2 = _MockFunction(np.random.random(10))
|
26 |
+
rfftn = _MockFunction(np.random.random(10))
|
27 |
+
|
28 |
+
irfft = _MockFunction(np.random.random(10))
|
29 |
+
irfft2 = _MockFunction(np.random.random(10))
|
30 |
+
irfftn = _MockFunction(np.random.random(10))
|
31 |
+
|
32 |
+
hfft = _MockFunction(np.random.random(10))
|
33 |
+
hfft2 = _MockFunction(np.random.random(10))
|
34 |
+
hfftn = _MockFunction(np.random.random(10))
|
35 |
+
|
36 |
+
ihfft = _MockFunction(np.random.random(10))
|
37 |
+
ihfft2 = _MockFunction(np.random.random(10))
|
38 |
+
ihfftn = _MockFunction(np.random.random(10))
|
39 |
+
|
40 |
+
dct = _MockFunction(np.random.random(10))
|
41 |
+
idct = _MockFunction(np.random.random(10))
|
42 |
+
dctn = _MockFunction(np.random.random(10))
|
43 |
+
idctn = _MockFunction(np.random.random(10))
|
44 |
+
|
45 |
+
dst = _MockFunction(np.random.random(10))
|
46 |
+
idst = _MockFunction(np.random.random(10))
|
47 |
+
dstn = _MockFunction(np.random.random(10))
|
48 |
+
idstn = _MockFunction(np.random.random(10))
|
49 |
+
|
50 |
+
fht = _MockFunction(np.random.random(10))
|
51 |
+
ifht = _MockFunction(np.random.random(10))
|
52 |
+
|
53 |
+
|
54 |
+
__ua_domain__ = "numpy.scipy.fft"
|
55 |
+
|
56 |
+
|
57 |
+
_implements = {
|
58 |
+
scipy.fft.fft: fft,
|
59 |
+
scipy.fft.fft2: fft2,
|
60 |
+
scipy.fft.fftn: fftn,
|
61 |
+
scipy.fft.ifft: ifft,
|
62 |
+
scipy.fft.ifft2: ifft2,
|
63 |
+
scipy.fft.ifftn: ifftn,
|
64 |
+
scipy.fft.rfft: rfft,
|
65 |
+
scipy.fft.rfft2: rfft2,
|
66 |
+
scipy.fft.rfftn: rfftn,
|
67 |
+
scipy.fft.irfft: irfft,
|
68 |
+
scipy.fft.irfft2: irfft2,
|
69 |
+
scipy.fft.irfftn: irfftn,
|
70 |
+
scipy.fft.hfft: hfft,
|
71 |
+
scipy.fft.hfft2: hfft2,
|
72 |
+
scipy.fft.hfftn: hfftn,
|
73 |
+
scipy.fft.ihfft: ihfft,
|
74 |
+
scipy.fft.ihfft2: ihfft2,
|
75 |
+
scipy.fft.ihfftn: ihfftn,
|
76 |
+
scipy.fft.dct: dct,
|
77 |
+
scipy.fft.idct: idct,
|
78 |
+
scipy.fft.dctn: dctn,
|
79 |
+
scipy.fft.idctn: idctn,
|
80 |
+
scipy.fft.dst: dst,
|
81 |
+
scipy.fft.idst: idst,
|
82 |
+
scipy.fft.dstn: dstn,
|
83 |
+
scipy.fft.idstn: idstn,
|
84 |
+
scipy.fft.fht: fht,
|
85 |
+
scipy.fft.ifht: ifht
|
86 |
+
}
|
87 |
+
|
88 |
+
|
89 |
+
def __ua_function__(method, args, kwargs):
|
90 |
+
fn = _implements.get(method)
|
91 |
+
return (fn(*args, **kwargs) if fn is not None
|
92 |
+
else NotImplemented)
|