Debian Codegraph @

tests/test_pyfftw_base.py

raw
1 # Copyright 2014 Knowledge Economy Developments Ltd
2 #
3 # Henry Gomersall
4 # [email protected]
5 #
6 # All rights reserved.
7 #
8 # Redistribution and use in source and binary forms, with or without
9 # modification, are permitted provided that the following conditions are met:
10 #
11 # * Redistributions of source code must retain the above copyright notice, this
12 # list of conditions and the following disclaimer.
13 #
14 # * Redistributions in binary form must reproduce the above copyright notice,
15 # this list of conditions and the following disclaimer in the documentation
16 # and/or other materials provided with the distribution.
17 #
18 # * Neither the name of the copyright holder nor the names of its contributors
19 # may be used to endorse or promote products derived from this software without
20 # specific prior written permission.
21 #
22 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
26 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 # POSSIBILITY OF SUCH DAMAGE.
33 #
34
35 from pyfftw import FFTW, _supported_types, _all_types_human_readable
36 import numpy
37 import struct
38 from timeit import Timer
39
40 import unittest
41
42 try:
43 import mkl_fft
44 # mkl_fft monkeypatches numpy.fft
45 # explicitly import from fftpack or pocketfft instead
46 try:
47 # numpy 1.17 replaced fftpack with pocketfft
48 from numpy.fft import pocketfft as np_fft
49 except ImportError:
50 from numpy.fft import fftpack as np_fft
51 except ImportError:
52 from numpy import fft as np_fft
53
54 def miss(*xs):
55 '''Skip test if the precisions in the iterable `xs` are not available.'''
56 msg = 'Requires %s' % _all_types_human_readable[xs[0]]
57 for x in xs[1:]:
58 msg += ' and %s' % _all_types_human_readable[x]
59 msg += ' precision.'
60 skip = not all(x in _supported_types for x in xs)
61 return (skip, msg)
62
63 def require(self, *xs):
64 skip, msg = miss(*xs)
65 if skip:
66 self.skipTest(msg)
67
68 class FFTWBaseTest(unittest.TestCase):
69
70 def reference_fftn(self, a, axes):
71 return np_fft.fftn(a, axes=axes)
72
73 def __init__(self, *args, **kwargs):
74
75 super(FFTWBaseTest, self).__init__(*args, **kwargs)
76 self.make_shapes()
77
78 if not hasattr(self, 'assertRaisesRegex'):
79 self.assertRaisesRegex = self.assertRaisesRegexp
80
81 def setUp(self):
82
83 require(self, '32')
84
85 self.input_dtype = numpy.complex64
86 self.output_dtype = numpy.complex64
87 self.np_fft_comparison = np_fft.fft
88
89 self.direction = 'FFTW_FORWARD'
90 return
91
92 def tearDown(self):
93
94 return
95
96 def get_input_dtype_alignment(self):
97 return self.input_dtype([]).real.dtype.alignment
98
99 def get_output_dtype_alignment(self):
100 return self.input_dtype([]).real.dtype.alignment
101
102 def make_shapes(self):
103 self.input_shapes = {
104 'small_1d': (16,),
105 '1d': (2048,),
106 '2d': (256, 2048),
107 '3d': (5, 256, 2048)}
108
109 self.output_shapes = {
110 'small_1d': (16,),
111 '1d': (2048,),
112 '2d': (256, 2048),
113 '3d': (5, 256, 2048)}
114
115 def create_test_arrays(self, input_shape, output_shape, axes=None):
116 a = self.input_dtype(numpy.random.randn(*input_shape)
117 +1j*numpy.random.randn(*input_shape))
118
119 b = self.output_dtype(numpy.random.randn(*output_shape)
120 +1j*numpy.random.randn(*output_shape))
121
122 return a, b
123
124 def timer_routine(self, pyfftw_callable, numpy_fft_callable,
125 comparison_string='numpy.fft'):
126
127 N = 100
128
129 t = Timer(stmt=pyfftw_callable)
130 t_numpy_fft = Timer(stmt=numpy_fft_callable)
131
132 t_str = ("%.2f" % (1000.0/N*t.timeit(N)))+' ms'
133 t_numpy_str = ("%.2f" % (1000.0/N*t_numpy_fft.timeit(N)))+' ms'
134
135 print('One run: '+ t_str + \
136 ' (versus ' + t_numpy_str + ' for ' + comparison_string + \
137 ')')
138
139
140 def run_validate_fft(self, a, b, axes, fft=None, ifft=None,
141 force_unaligned_data=False, create_array_copies=True,
142 threads=1, flags=('FFTW_ESTIMATE',)):
143 ''' Run a validation of the FFTW routines for the passed pair
144 of arrays, a and b, and the axes argument.
145
146 a and b are assumed to be the same shape (but not necessarily
147 the same layout in memory).
148
149 fft and ifft, if passed, should be instantiated FFTW objects.
150
151 If force_unaligned_data is True, the flag FFTW_UNALIGNED
152 will be passed to the fftw routines.
153
154 The threads argument runs the validation with multiple threads.
155
156 flags is passed to the creation of the FFTW object.
157 '''
158
159 if create_array_copies:
160 # Don't corrupt the original mutable arrays
161 a = a.copy()
162 b = b.copy()
163
164 a_orig = a.copy()
165
166 flags = list(flags)
167
168 if force_unaligned_data:
169 flags.append('FFTW_UNALIGNED')
170
171 if fft == None:
172 fft = FFTW(a,b,axes=axes, direction='FFTW_FORWARD',
173 flags=flags, threads=threads)
174 else:
175 fft.update_arrays(a,b)
176
177 if ifft == None:
178 ifft = FFTW(b, a, axes=axes, direction='FFTW_BACKWARD',
179 flags=flags, threads=threads)
180 else:
181 ifft.update_arrays(b,a)
182
183
184 a[:] = a_orig
185
186 # Test the forward FFT by comparing it to the result from numpy.fft
187 fft.execute()
188 ref_b = self.reference_fftn(a, axes=axes)
189
190 # This is actually quite a poor relative error, but it still
191 # sometimes fails. I assume that numpy.fft has different internals
192 # to fftw.
193 self.assertTrue(numpy.allclose(b, ref_b, rtol=1e-2, atol=1e-3))
194
195 # Test the inverse FFT by comparing the result to the starting
196 # value (which is scaled as per FFTW being unnormalised).
197 ifft.execute()
198 # The scaling is the product of the lengths of the fft along
199 # the axes along which the fft is taken.
200 scaling = numpy.prod(numpy.array(a.shape)[list(axes)])
201
202 self.assertEqual(ifft.N, scaling)
203 self.assertEqual(fft.N, scaling)
204
205 self.assertTrue(numpy.allclose(a/scaling, a_orig, rtol=1e-2, atol=1e-3))
206 return fft, ifft
207
208
209 def run_test_suites(test_suites, run_tests=None):
210 '''From each test case (derived from TestCase) in test_suites,
211 load and run all the test cases within.
212
213 If run_tests is not None, then it should be a dictionary with
214 keys being the test suite class name, and the values being
215 a list of test methods to run. Alternatively, the key can
216 be 'all' in which case all the test suites will be run with
217 the provided list of test suites.
218 '''
219 suite = unittest.TestSuite()
220
221 for test_class in test_suites:
222 tests = unittest.TestLoader().loadTestsFromTestCase(test_class)
223
224 if run_tests is not None:
225 if test_class.__name__ in run_tests:
226 this_suite_run = set(run_tests[test_class.__name__])
227 else:
228 this_suite_run = set()
229
230 if 'all' in run_tests:
231 this_suite_run = this_suite_run.union(run_tests['all'])
232
233 _tests = []
234 for each_test in tests:
235 if (each_test.id().split('.')[-1] in this_suite_run):
236 _tests.append(each_test)
237
238 tests = _tests
239
240 suite.addTests(tests)
241
242
243 unittest.TextTestRunner(verbosity=2).run(suite)