| 1 |
# Copyright 2019, The pyFFTW developers |
| 2 |
# |
| 3 |
# All rights reserved. |
| 4 |
# |
| 5 |
# Redistribution and use in source and binary forms, with or without |
| 6 |
# modification, are permitted provided that the following conditions are met: |
| 7 |
# |
| 8 |
# * Redistributions of source code must retain the above copyright notice, this |
| 9 |
# list of conditions and the following disclaimer. |
| 10 |
# |
| 11 |
# * Redistributions in binary form must reproduce the above copyright notice, |
| 12 |
# this list of conditions and the following disclaimer in the documentation |
| 13 |
# and/or other materials provided with the distribution. |
| 14 |
# |
| 15 |
# * Neither the name of the copyright holder nor the names of its contributors |
| 16 |
# may be used to endorse or promote products derived from this software without |
| 17 |
# specific prior written permission. |
| 18 |
# |
| 19 |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 20 |
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 21 |
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 22 |
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |
| 23 |
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 24 |
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 25 |
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 26 |
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 27 |
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 28 |
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 29 |
# POSSIBILITY OF SUCH DAMAGE. |
| 30 |
# |
| 31 |
|
| 32 |
import pyfftw |
| 33 |
import numpy |
| 34 |
|
| 35 |
try: |
| 36 |
import scipy |
| 37 |
scipy_version = scipy.__version__ |
| 38 |
except ImportError: |
| 39 |
scipy_version = '0.0.0' |
| 40 |
|
| 41 |
from packaging.version import Version |
| 42 |
has_scipy_fft = Version(scipy_version) >= Version('1.4.0') |
| 43 |
|
| 44 |
if has_scipy_fft: |
| 45 |
import scipy.fft |
| 46 |
import scipy.signal |
| 47 |
from pyfftw.interfaces import scipy_fft |
| 48 |
|
| 49 |
import unittest |
| 50 |
from pyfftw import _supported_types |
| 51 |
from .test_pyfftw_base import run_test_suites, miss |
| 52 |
from . import test_pyfftw_numpy_interface |
| 53 |
|
| 54 |
'''pyfftw.interfaces.scipy_fft just wraps pyfftw.interfaces.numpy_fft. |
| 55 |
|
| 56 |
All the tests here just check that the call is made correctly. |
| 57 |
''' |
| 58 |
|
| 59 |
funcs = ('fft', 'ifft', 'fft2', 'ifft2', 'fftn', 'ifftn', |
| 60 |
'rfft', 'irfft', 'rfft2', 'irfft2', 'rfftn', 'irfftn', |
| 61 |
'hfft', 'ihfft') |
| 62 |
|
| 63 |
acquired_names = ('hfft2', 'ihfft2', 'hfftn', 'ihfftn', |
| 64 |
'fftshift', 'ifftshift', 'fftfreq', 'rfftfreq') |
| 65 |
|
| 66 |
def make_complex_data(shape, dtype): |
| 67 |
ar, ai = dtype(numpy.random.randn(2, *shape)) |
| 68 |
return ar + 1j*ai |
| 69 |
|
| 70 |
def make_r2c_real_data(shape, dtype): |
| 71 |
return dtype(numpy.random.randn(*shape)) |
| 72 |
|
| 73 |
def make_c2r_real_data(shape, dtype): |
| 74 |
return dtype(numpy.random.randn(*shape)) |
| 75 |
|
| 76 |
# reuse from numpy tests |
| 77 |
make_complex_data = test_pyfftw_numpy_interface.make_complex_data |
| 78 |
complex_dtypes = test_pyfftw_numpy_interface.complex_dtypes |
| 79 |
real_dtypes = test_pyfftw_numpy_interface.real_dtypes |
| 80 |
|
| 81 |
io_dtypes = { |
| 82 |
'complex': (complex_dtypes, make_complex_data), |
| 83 |
'r2c': (real_dtypes, make_r2c_real_data), |
| 84 |
'c2r': (real_dtypes, make_c2r_real_data)} |
| 85 |
|
| 86 |
@unittest.skipIf(not has_scipy_fft, 'scipy.fft is unavailable') |
| 87 |
class InterfacesScipyFFTTestSimple(unittest.TestCase): |
| 88 |
''' A simple test suite for a simple implementation. |
| 89 |
''' |
| 90 |
|
| 91 |
@unittest.skipIf(*miss('64')) |
| 92 |
def test_scipy_backend(self): |
| 93 |
a = pyfftw.empty_aligned((128, 64), dtype='complex128', n=16) |
| 94 |
b = pyfftw.empty_aligned((128, 64), dtype='complex128', n=16) |
| 95 |
|
| 96 |
a[:] = (numpy.random.randn(*a.shape) + |
| 97 |
1j*numpy.random.randn(*a.shape)) |
| 98 |
b[:] = (numpy.random.randn(*b.shape) + |
| 99 |
1j*numpy.random.randn(*b.shape)) |
| 100 |
|
| 101 |
scipy_c = scipy.signal.fftconvolve(a, b) |
| 102 |
|
| 103 |
with scipy.fft.set_backend(scipy_fft, only=True): |
| 104 |
scipy_replaced_c = scipy.signal.fftconvolve(a, b) |
| 105 |
|
| 106 |
self.assertTrue(numpy.allclose(scipy_c, scipy_replaced_c)) |
| 107 |
|
| 108 |
def test_acquired_names(self): |
| 109 |
for each_name in acquired_names: |
| 110 |
|
| 111 |
fft_attr = getattr(scipy.fft, each_name) |
| 112 |
acquired_attr = getattr(scipy_fft, each_name) |
| 113 |
|
| 114 |
self.assertIs(fft_attr, acquired_attr) |
| 115 |
|
| 116 |
|
| 117 |
# InterfacesScipyR2RFFTTest is mostly the same as the ones defined in |
| 118 |
# test_pyfftw_scipy_interface.py, but call the functions from scipy.fft instead |
| 119 |
# of scipy.fftpack and test additional normalization modes. |
| 120 |
|
| 121 |
if '64' in _supported_types: |
| 122 |
default_floating_type = numpy.float64 |
| 123 |
elif '32' in _supported_types: |
| 124 |
default_floating_type = numpy.float32 |
| 125 |
elif 'ld' in _supported_types: |
| 126 |
default_floating_type = numpy.longdouble |
| 127 |
atol_dict = dict(f=1e-5, d=1e-7, g=1e-7) |
| 128 |
rtol_dict = dict(f=1e-4, d=1e-5, g=1e-5) |
| 129 |
transform_types = [1, 2, 3, 4] |
| 130 |
|
| 131 |
if Version(scipy_version) >= Version('1.6.0'): |
| 132 |
# all norm options aside from None |
| 133 |
scipy_norms = [None, 'ortho', 'forward', 'backward'] |
| 134 |
else: |
| 135 |
scipy_norms = [None, 'ortho'] |
| 136 |
|
| 137 |
|
| 138 |
@unittest.skipIf(not has_scipy_fft, 'scipy.fft is unavailable') |
| 139 |
class InterfacesScipyR2RFFTTest(unittest.TestCase): |
| 140 |
''' Class template for building the scipy real to real tests. |
| 141 |
''' |
| 142 |
|
| 143 |
# unittest is not very smart and will always turn this class into a test, |
| 144 |
# even though it is not on the list. Hence mark test-dependent values as |
| 145 |
# constants (so this particular test ends up being run twice). |
| 146 |
func_name = 'dct' |
| 147 |
float_type = default_floating_type |
| 148 |
atol = atol_dict['f'] |
| 149 |
rtol = rtol_dict['f'] |
| 150 |
|
| 151 |
def setUp(self): |
| 152 |
self.scipy_func = getattr(scipy.fft, self.func_name) |
| 153 |
self.pyfftw_func = getattr(scipy_fft, self.func_name) |
| 154 |
self.ndims = numpy.random.randint(1, high=3) |
| 155 |
self.axis = numpy.random.randint(0, high=self.ndims) |
| 156 |
self.shape = numpy.random.randint(2, high=10, size=self.ndims) |
| 157 |
self.data = numpy.random.rand(*self.shape).astype(self.float_type) |
| 158 |
self.data_copy = self.data.copy() |
| 159 |
|
| 160 |
if self.func_name in ['dctn', 'idctn', 'dstn', 'idstn']: |
| 161 |
self.kwargs = dict(axes=(self.axis, )) |
| 162 |
else: |
| 163 |
self.kwargs = dict(axis=self.axis) |
| 164 |
|
| 165 |
def test_unnormalized(self): |
| 166 |
'''Test unnormalized pyfftw transformations against their scipy |
| 167 |
equivalents. |
| 168 |
''' |
| 169 |
for transform_type in transform_types: |
| 170 |
data_hat_p = self.pyfftw_func(self.data, type=transform_type, |
| 171 |
overwrite_x=False, **self.kwargs) |
| 172 |
self.assertEqual(numpy.linalg.norm(self.data - self.data_copy), 0.0) |
| 173 |
data_hat_s = self.scipy_func(self.data, type=transform_type, |
| 174 |
overwrite_x=False, **self.kwargs) |
| 175 |
self.assertTrue(numpy.allclose(data_hat_p, data_hat_s, |
| 176 |
atol=self.atol, rtol=self.rtol)) |
| 177 |
|
| 178 |
def test_normalized(self): |
| 179 |
'''Test normalized against scipy results. Note that scipy does |
| 180 |
not support normalization for all transformations. |
| 181 |
''' |
| 182 |
for norm in scipy_norms: |
| 183 |
for transform_type in transform_types: |
| 184 |
data_hat_p = self.pyfftw_func(self.data, type=transform_type, |
| 185 |
norm=norm, |
| 186 |
overwrite_x=False, **self.kwargs) |
| 187 |
if norm == 'ortho': |
| 188 |
self.assertEqual( |
| 189 |
numpy.linalg.norm(self.data - self.data_copy), 0.0 |
| 190 |
) |
| 191 |
data_hat_s = self.scipy_func(self.data, type=transform_type, |
| 192 |
norm=norm, |
| 193 |
overwrite_x=False, **self.kwargs) |
| 194 |
|
| 195 |
if not numpy.allclose(data_hat_p, data_hat_s, atol=self.atol, rtol=self.rtol): |
| 196 |
info = f"{self.func_name=}, {norm=}, {transform_type=}" |
| 197 |
print(info) |
| 198 |
print("scipy: ", data_hat_s) |
| 199 |
print("ratio: ", data_hat_p / data_hat_s) |
| 200 |
raise ValueError(info) |
| 201 |
|
| 202 |
def test_normalization_inverses(self): |
| 203 |
'''Test normalization in all of the pyfftw scipy wrappers. |
| 204 |
''' |
| 205 |
for transform_type in transform_types: |
| 206 |
inverse_type = {1: 1, 2: 3, 3: 2, 4: 4}[transform_type] |
| 207 |
forward = self.pyfftw_func(self.data, type=transform_type, |
| 208 |
norm='ortho', |
| 209 |
overwrite_x=False, **self.kwargs) |
| 210 |
result = self.pyfftw_func(forward, type=inverse_type, |
| 211 |
norm='ortho', |
| 212 |
overwrite_x=False, **self.kwargs) |
| 213 |
if not numpy.allclose(self.data, result, atol=self.atol, rtol=self.rtol): |
| 214 |
info = f"{self.func_name=}, norm='ortho', {transform_type=}" |
| 215 |
print(info) |
| 216 |
print("ratio: ", result / self.data) |
| 217 |
raise ValueError(info) |
| 218 |
|
| 219 |
|
| 220 |
@unittest.skipIf(not has_scipy_fft, 'scipy.fft is unavailable') |
| 221 |
class InterfacesScipyR2RFFTNTest(InterfacesScipyR2RFFTTest): |
| 222 |
''' Class template for building the scipy real to real tests. |
| 223 |
''' |
| 224 |
|
| 225 |
# unittest is not very smart and will always turn this class into a test, |
| 226 |
# even though it is not on the list. Hence mark test-dependent values as |
| 227 |
# constants (so this particular test ends up being run twice). |
| 228 |
func_name = 'dctn' |
| 229 |
float_type = default_floating_type |
| 230 |
atol = atol_dict['f'] |
| 231 |
rtol = rtol_dict['f'] |
| 232 |
|
| 233 |
def setUp(self): |
| 234 |
self.scipy_func = getattr(scipy.fft, self.func_name) |
| 235 |
self.pyfftw_func = getattr(scipy_fft, self.func_name) |
| 236 |
self.ndims = numpy.random.randint(1, high=3) |
| 237 |
self.shape = numpy.random.randint(2, high=10, size=self.ndims) |
| 238 |
self.data = numpy.random.rand(*self.shape).astype(self.float_type) |
| 239 |
self.data_copy = self.data.copy() |
| 240 |
# random subset of axes |
| 241 |
self.axes = tuple(range(0, numpy.random.randint(0, high=self.ndims))) |
| 242 |
self.kwargs = dict(axes=self.axes) |
| 243 |
|
| 244 |
def test_axes_none(self): |
| 245 |
'''Test transformation over all axes. |
| 246 |
''' |
| 247 |
for transform_type in transform_types: |
| 248 |
data_hat_p = self.pyfftw_func(self.data, type=transform_type, |
| 249 |
overwrite_x=False, axes=None) |
| 250 |
self.assertEqual(numpy.linalg.norm(self.data - self.data_copy), 0.0) |
| 251 |
data_hat_s = self.scipy_func(self.data, type=transform_type, |
| 252 |
overwrite_x=False, axes=None) |
| 253 |
self.assertTrue(numpy.allclose(data_hat_p, data_hat_s, |
| 254 |
atol=self.atol, rtol=self.rtol)) |
| 255 |
|
| 256 |
def test_axes_scalar(self): |
| 257 |
'''Test transformation over a single, scalar axis. |
| 258 |
''' |
| 259 |
for transform_type in transform_types: |
| 260 |
data_hat_p = self.pyfftw_func(self.data, type=transform_type, |
| 261 |
overwrite_x=False, axes=-1) |
| 262 |
self.assertEqual(numpy.linalg.norm(self.data - self.data_copy), 0.0) |
| 263 |
data_hat_s = self.scipy_func(self.data, type=transform_type, |
| 264 |
overwrite_x=False, axes=-1) |
| 265 |
self.assertTrue(numpy.allclose(data_hat_p, data_hat_s, |
| 266 |
atol=self.atol, rtol=self.rtol)) |
| 267 |
|
| 268 |
|
| 269 |
# Construct all the test classes automatically. |
| 270 |
test_cases = [] |
| 271 |
# Construct the r2r test classes. |
| 272 |
for floating_type, floating_name in [[numpy.float32, 'Float32'], |
| 273 |
[numpy.float64, 'Float64']]: |
| 274 |
if floating_type == numpy.float32 and '32' not in _supported_types: |
| 275 |
# skip single precision tests if library is unavailable |
| 276 |
continue |
| 277 |
elif floating_type == numpy.float64 and '64' not in _supported_types: |
| 278 |
# skip double precision tests if library is unavailable |
| 279 |
continue |
| 280 |
|
| 281 |
real_transforms = ('dct', 'idct', 'dst', 'idst') |
| 282 |
real_transforms_nd = ('dctn', 'idctn', 'dstn', 'idstn') |
| 283 |
real_transforms += real_transforms_nd |
| 284 |
|
| 285 |
dt_char = numpy.dtype(floating_type).char |
| 286 |
atol = atol_dict[dt_char] |
| 287 |
rtol = rtol_dict[dt_char] |
| 288 |
|
| 289 |
# test-cases where only one axis is transformed |
| 290 |
for transform_name in real_transforms: |
| 291 |
class_name = ('InterfacesScipyR2RFFTTest' + transform_name.upper() + |
| 292 |
floating_name) |
| 293 |
|
| 294 |
globals()[class_name] = type( |
| 295 |
class_name, |
| 296 |
(InterfacesScipyR2RFFTTest,), |
| 297 |
{'func_name': transform_name, |
| 298 |
'float_type': floating_type, |
| 299 |
'atol': atol, |
| 300 |
'rtol': rtol}) |
| 301 |
|
| 302 |
test_cases.append(globals()[class_name]) |
| 303 |
|
| 304 |
# n-dimensional test-cases |
| 305 |
for transform_name in real_transforms_nd: |
| 306 |
class_name = ('InterfacesScipyR2RFFTNTest' + transform_name.upper() + |
| 307 |
floating_name) |
| 308 |
|
| 309 |
globals()[class_name] = type( |
| 310 |
class_name, |
| 311 |
(InterfacesScipyR2RFFTNTest,), |
| 312 |
{'func_name': transform_name, |
| 313 |
'float_type': floating_type, |
| 314 |
'atol': atol, |
| 315 |
'rtol': rtol}) |
| 316 |
|
| 317 |
test_cases.append(globals()[class_name]) |
| 318 |
|
| 319 |
for each_func in funcs: |
| 320 |
class_name = 'InterfacesScipyFFTTest' + each_func.upper() |
| 321 |
|
| 322 |
parent_class_name = 'InterfacesNumpyFFTTest' + each_func.upper() |
| 323 |
parent_class = getattr(test_pyfftw_numpy_interface, parent_class_name) |
| 324 |
|
| 325 |
class_dict = {'validator_module': scipy.fft if has_scipy_fft else None, |
| 326 |
'test_interface': scipy_fft if has_scipy_fft else None, |
| 327 |
'io_dtypes': io_dtypes, |
| 328 |
'overwrite_input_flag': 'overwrite_x', |
| 329 |
'default_s_from_shape_slicer': slice(None), |
| 330 |
'threads_arg_name': 'workers'} |
| 331 |
|
| 332 |
cls = type(class_name, (parent_class,), class_dict) |
| 333 |
cls = unittest.skipIf(not has_scipy_fft, "scipy.fft is not available")(cls) |
| 334 |
|
| 335 |
globals()[class_name] = cls |
| 336 |
test_cases.append(cls) |
| 337 |
|
| 338 |
test_cases.append(InterfacesScipyFFTTestSimple) |
| 339 |
test_set = None |
| 340 |
|
| 341 |
|
| 342 |
if __name__ == '__main__': |
| 343 |
run_test_suites(test_cases, test_set) |