Debian Codegraph @

tests/test_pyfftw_scipy_interface.py

raw
1 # Copyright 2014 Knowledge Economy Developments Ltd
2 # Copyright 2014 David Wells
3 #
4 # Henry Gomersall
5 # [email protected]
6 #
7 # All rights reserved.
8 #
9 # Redistribution and use in source and binary forms, with or without
10 # modification, are permitted provided that the following conditions are met:
11 #
12 # * Redistributions of source code must retain the above copyright notice, this
13 # list of conditions and the following disclaimer.
14 #
15 # * Redistributions in binary form must reproduce the above copyright notice,
16 # this list of conditions and the following disclaimer in the documentation
17 # and/or other materials provided with the distribution.
18 #
19 # * Neither the name of the copyright holder nor the names of its contributors
20 # may be used to endorse or promote products derived from this software without
21 # specific prior written permission.
22 #
23 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
24 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
27 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 # POSSIBILITY OF SUCH DAMAGE.
34 #
35
36 from pyfftw.interfaces import scipy_fftpack
37 from packaging.version import Version
38
39 import pyfftw
40 from pyfftw import _supported_types
41 import numpy
42
43 try:
44 import scipy
45 import scipy.fftpack
46 import scipy.signal
47
48 except ImportError:
49 scipy_missing = True
50
51 else:
52 scipy_missing = False
53
54 import unittest
55 from .test_pyfftw_base import run_test_suites, miss
56 from . import test_pyfftw_numpy_interface
57
58 '''pyfftw.interfaces.scipy_fftpack wraps pyfftw.interfaces.numpy_fft and
59 implements the dct and dst functions.
60
61 All the tests here just check that the call is made correctly.
62 '''
63
64 funcs = ('fft', 'ifft', 'fft2', 'ifft2', 'fftn', 'ifftn',
65 'rfft', 'irfft')
66
67 acquired_names = ('diff', 'tilbert', 'itilbert', 'hilbert',
68 'ihilbert', 'cs_diff', 'sc_diff', 'ss_diff', 'cc_diff', 'shift',
69 'fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'convolve')
70
71 def make_complex_data(shape, dtype):
72 ar, ai = dtype(numpy.random.randn(2, *shape))
73 return ar + 1j*ai
74
75 def make_r2c_real_data(shape, dtype):
76 return dtype(numpy.random.randn(*shape))
77
78 def make_c2r_real_data(shape, dtype):
79 return dtype(numpy.random.randn(*shape))
80
81 make_complex_data = test_pyfftw_numpy_interface.make_complex_data
82
83 if scipy.__version__ < '0.19':
84 # Older scipy will raise an error for inputs of type float16, so we
85 # cannot validate transforms with float16 input vs. scipy.fftpack
86 complex_dtypes = pyfftw._supported_nptypes_complex
87 real_dtypes = pyfftw._supported_nptypes_real
88 else:
89 # reuse all dtypes from numpy tests (including float16)
90 complex_dtypes = test_pyfftw_numpy_interface.complex_dtypes
91 real_dtypes = test_pyfftw_numpy_interface.real_dtypes
92
93 # Remove long double because scipy explicitly doesn't support it
94 complex_dtypes = [x for x in complex_dtypes if x != numpy.clongdouble]
95 real_dtypes = [x for x in real_dtypes if x != numpy.longdouble]
96
97 def numpy_fft_replacement(a, s, axes, overwrite_input, planner_effort,
98 threads, auto_align_input, auto_contiguous):
99
100 return (a, s, axes, overwrite_input, planner_effort,
101 threads, auto_align_input, auto_contiguous)
102
103 io_dtypes = {
104 'complex': (complex_dtypes, make_complex_data),
105 'r2c': (real_dtypes, make_r2c_real_data),
106 'c2r': (real_dtypes, make_c2r_real_data)}
107
108 if '64' in _supported_types:
109 default_floating_type = numpy.float64
110 elif '32' in _supported_types:
111 default_floating_type = numpy.float32
112 elif 'ld' in _supported_types:
113 default_floating_type = numpy.longdouble
114 atol_dict = dict(f=1e-5, d=1e-7, g=1e-7)
115 rtol_dict = dict(f=1e-4, d=1e-5, g=1e-5)
116
117 @unittest.skipIf(scipy_missing, 'scipy is not installed, so this feature is'
118 'unavailable')
119 class InterfacesScipyR2RFFTPackTestSimple(unittest.TestCase):
120 ''' A really simple test suite to check simple implementation.
121 '''
122
123 @unittest.skipIf(*miss('64'))
124 def test_scipy_overwrite(self):
125
126 new_style_scipy_fftn = False
127 try:
128 scipy_fftn = scipy.signal.signaltools.fftn
129 scipy_ifftn = scipy.signal.signaltools.ifftn
130 except AttributeError:
131 scipy_fftn = scipy.fftpack.fftn
132 scipy_ifftn = scipy.fftpack.ifftn
133 new_style_scipy_fftn = True
134
135 a = pyfftw.empty_aligned((128, 64), dtype='complex128', n=16)
136 b = pyfftw.empty_aligned((128, 64), dtype='complex128', n=16)
137
138 a[:] = (numpy.random.randn(*a.shape) +
139 1j*numpy.random.randn(*a.shape))
140 b[:] = (numpy.random.randn(*b.shape) +
141 1j*numpy.random.randn(*b.shape))
142
143
144 scipy_c = scipy.signal.fftconvolve(a, b)
145
146 if new_style_scipy_fftn:
147 scipy.fftpack.fftn = scipy_fftpack.fftn
148 scipy.fftpack.ifftn = scipy_fftpack.ifftn
149
150 else:
151 scipy.signal.signaltools.fftn = scipy_fftpack.fftn
152 scipy.signal.signaltools.ifftn = scipy_fftpack.ifftn
153
154 scipy_replaced_c = scipy.signal.fftconvolve(a, b)
155
156 self.assertTrue(numpy.allclose(scipy_c, scipy_replaced_c))
157
158 if new_style_scipy_fftn:
159 scipy.fftpack.fftn = scipy_fftn
160 scipy.fftpack.ifftn = scipy_ifftn
161
162 else:
163 scipy.signal.signaltools.fftn = scipy_fftn
164 scipy.signal.signaltools.ifftn = scipy_ifftn
165
166 def test_funcs(self):
167
168 for each_func in funcs:
169 func_being_replaced = getattr(scipy_fftpack, each_func)
170
171 #create args (8 of them)
172 args = []
173 for n in range(8):
174 args.append(object())
175
176 args = tuple(args)
177
178 try:
179 setattr(scipy_fftpack, each_func,
180 numpy_fft_replacement)
181
182 return_args = getattr(scipy_fftpack, each_func)(*args)
183 for n, each_arg in enumerate(args):
184 # Check that what comes back is what is sent
185 # (which it should be)
186 self.assertIs(each_arg, return_args[n])
187 except:
188 raise
189
190 finally:
191 setattr(scipy_fftpack, each_func,
192 func_being_replaced)
193
194 def test_acquired_names(self):
195 for each_name in acquired_names:
196
197 fftpack_attr = getattr(scipy.fftpack, each_name)
198 acquired_attr = getattr(scipy_fftpack, each_name)
199
200 self.assertIs(fftpack_attr, acquired_attr)
201
202 transform_types = [1, 2, 3, 4]
203
204 @unittest.skipIf(scipy_missing or
205 (Version(scipy.__version__) <= Version('1.2.0')),
206 'SciPy >= 1.2.0 is not installed')
207 class InterfacesScipyR2RFFTTest(unittest.TestCase):
208 ''' Class template for building the scipy real to real tests.
209 '''
210
211 # unittest is not very smart and will always turn this class into a test,
212 # even though it is not on the list. Hence mark test-dependent values as
213 # constants (so this particular test ends up being run twice).
214 func_name = 'dct'
215 float_type = default_floating_type
216 atol = atol_dict['f']
217 rtol = rtol_dict['f']
218
219 def setUp(self):
220 self.scipy_func = getattr(scipy.fftpack, self.func_name)
221 self.pyfftw_func = getattr(scipy_fftpack, self.func_name)
222 self.ndims = numpy.random.randint(1, high=3)
223 self.axis = numpy.random.randint(0, high=self.ndims)
224 self.shape = numpy.random.randint(2, high=10, size=self.ndims)
225 self.data = numpy.random.rand(*self.shape).astype(self.float_type)
226 self.data_copy = self.data.copy()
227
228 if self.func_name in ['dctn', 'idctn', 'dstn', 'idstn']:
229 self.kwargs = dict(axes=(self.axis, ))
230 else:
231 self.kwargs = dict(axis=self.axis)
232
233 def test_unnormalized(self):
234 '''Test unnormalized pyfftw transformations against their scipy
235 equivalents.
236 '''
237 for transform_type in transform_types:
238 data_hat_p = self.pyfftw_func(self.data, type=transform_type,
239 overwrite_x=False, **self.kwargs)
240 self.assertEqual(numpy.linalg.norm(self.data - self.data_copy), 0.0)
241 data_hat_s = self.scipy_func(self.data, type=transform_type,
242 overwrite_x=False, **self.kwargs)
243 self.assertTrue(numpy.allclose(data_hat_p, data_hat_s,
244 atol=self.atol, rtol=self.rtol))
245
246 def test_normalized(self):
247 '''Test normalized against scipy results. Note that scipy does
248 not support normalization for all transformations.
249 '''
250 for transform_type in transform_types:
251 data_hat_p = self.pyfftw_func(self.data, type=transform_type,
252 norm='ortho',
253 overwrite_x=False, **self.kwargs)
254 self.assertEqual(numpy.linalg.norm(self.data - self.data_copy), 0.0)
255 data_hat_s = self.scipy_func(self.data, type=transform_type,
256 norm='ortho',
257 overwrite_x=False, **self.kwargs)
258 self.assertTrue(numpy.allclose(data_hat_p, data_hat_s,
259 atol=self.atol, rtol=self.rtol))
260
261 def test_normalization_inverses(self):
262 '''Test normalization in all of the pyfftw scipy wrappers.
263 '''
264 for transform_type in transform_types:
265 inverse_type = {1: 1, 2: 3, 3: 2, 4: 4}[transform_type]
266 forward = self.pyfftw_func(self.data, type=transform_type,
267 norm='ortho',
268 overwrite_x=False, **self.kwargs)
269 result = self.pyfftw_func(forward, type=inverse_type,
270 norm='ortho',
271 overwrite_x=False, **self.kwargs)
272 self.assertTrue(numpy.allclose(self.data, result,
273 atol=self.atol, rtol=self.rtol))
274
275 @unittest.skipIf(scipy_missing or
276 (Version(scipy.__version__) <= Version('1.2.0')),
277 'SciPy >= 1.2.0 is not installed')
278 class InterfacesScipyR2RFFTNTest(InterfacesScipyR2RFFTTest):
279 ''' Class template for building the scipy real to real tests.
280 '''
281
282 # unittest is not very smart and will always turn this class into a test,
283 # even though it is not on the list. Hence mark test-dependent values as
284 # constants (so this particular test ends up being run twice).
285 func_name = 'dctn'
286 float_type = default_floating_type
287 atol = atol_dict['f']
288 rtol = rtol_dict['f']
289
290 def setUp(self):
291 self.scipy_func = getattr(scipy.fftpack, self.func_name)
292 self.pyfftw_func = getattr(scipy_fftpack, self.func_name)
293 self.ndims = numpy.random.randint(1, high=3)
294 self.shape = numpy.random.randint(2, high=10, size=self.ndims)
295 self.data = numpy.random.rand(*self.shape).astype(self.float_type)
296 self.data_copy = self.data.copy()
297 # random subset of axes
298 self.axes = tuple(range(0, numpy.random.randint(0, high=self.ndims)))
299 self.kwargs = dict(axes=self.axes)
300
301 def test_axes_none(self):
302 '''Test transformation over all axes.
303 '''
304 for transform_type in transform_types:
305 data_hat_p = self.pyfftw_func(self.data, type=transform_type,
306 overwrite_x=False, axes=None)
307 self.assertEqual(numpy.linalg.norm(self.data - self.data_copy), 0.0)
308 data_hat_s = self.scipy_func(self.data, type=transform_type,
309 overwrite_x=False, axes=None)
310 self.assertTrue(numpy.allclose(data_hat_p, data_hat_s,
311 atol=self.atol, rtol=self.rtol))
312
313 @unittest.skipIf(Version(scipy.__version__) <= Version('1.2.0'),
314 'scipy version not new enough')
315 def test_axes_scalar(self):
316 '''Test transformation over a single, scalar axis.
317 '''
318 for transform_type in transform_types:
319 if scipy.__version__ < '1.2':
320 # scalar axes not supported in older SciPy
321 continue
322 data_hat_p = self.pyfftw_func(self.data, type=transform_type,
323 overwrite_x=False, axes=-1)
324 self.assertEqual(numpy.linalg.norm(self.data - self.data_copy), 0.0)
325 data_hat_s = self.scipy_func(self.data, type=transform_type,
326 overwrite_x=False, axes=-1)
327 self.assertTrue(numpy.allclose(data_hat_p, data_hat_s,
328 atol=self.atol, rtol=self.rtol))
329
330
331 built_classes = []
332 # Construct the r2r test classes.
333 for floating_type, floating_name in [[numpy.float32, 'Float32'],
334 [numpy.float64, 'Float64']]:
335 if floating_type == numpy.float32 and '32' not in _supported_types:
336 # skip single precision tests if library is unavailable
337 continue
338 elif floating_type == numpy.float64 and '64' not in _supported_types:
339 # skip double precision tests if library is unavailable
340 continue
341
342 real_transforms = ('dct', 'idct', 'dst', 'idst')
343 try:
344 # additional n-dimensional real transforms in scipy 1.0+
345 from scipy.fftpack import dctn
346 real_transforms_nd = ('dctn', 'idctn', 'dstn', 'idstn')
347 real_transforms += real_transforms_nd
348 except ImportError:
349 real_transforms_nd = ()
350
351 dt_char = numpy.dtype(floating_type).char
352 atol = atol_dict[dt_char]
353 rtol = rtol_dict[dt_char]
354
355 # test-cases where only one axis is transformed
356 for transform_name in real_transforms:
357 class_name = ('InterfacesScipyR2RFFTTest' + transform_name.upper() +
358 floating_name)
359
360 globals()[class_name] = type(
361 class_name,
362 (InterfacesScipyR2RFFTTest,),
363 {'func_name': transform_name,
364 'float_type': floating_type,
365 'atol': atol,
366 'rtol': rtol})
367
368 built_classes.append(globals()[class_name])
369
370 # n-dimensional test-cases
371 for transform_name in real_transforms_nd:
372 class_name = ('InterfacesScipyR2RFFTNTest' + transform_name.upper() +
373 floating_name)
374
375 globals()[class_name] = type(
376 class_name,
377 (InterfacesScipyR2RFFTNTest,),
378 {'func_name': transform_name,
379 'float_type': floating_type,
380 'atol': atol,
381 'rtol': rtol})
382
383 built_classes.append(globals()[class_name])
384
385
386 # Construct the test classes derived from the numpy tests.
387 for each_func in funcs:
388
389 class_name = 'InterfacesScipyR2RFFTPackTest' + each_func.upper()
390
391 parent_class_name = 'InterfacesNumpyFFTTest' + each_func.upper()
392 parent_class = getattr(test_pyfftw_numpy_interface, parent_class_name)
393
394 class_dict = {'validator_module': scipy.fftpack,
395 'test_interface': scipy_fftpack,
396 'io_dtypes': io_dtypes,
397 'overwrite_input_flag': 'overwrite_x',
398 'default_s_from_shape_slicer': slice(None)}
399
400 globals()[class_name] = type(class_name,
401 (parent_class,), class_dict)
402
403 # unlike numpy, none of the scipy functions support the norm kwarg
404 globals()[class_name].has_norm_kwarg = False
405
406 built_classes.append(globals()[class_name])
407
408 built_classes = tuple(built_classes)
409
410 test_cases = (
411 InterfacesScipyR2RFFTPackTestSimple,) + built_classes
412
413 test_set = None
414 #test_set = {'InterfacesScipyR2RFFTPackTestIFFTN': ['test_auto_align_input']}
415
416
417 if __name__ == '__main__':
418
419 run_test_suites(test_cases, test_set)