Debian Codegraph @

tests/test_pyfftw_real_backward.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
36 from pyfftw import FFTW, forget_wisdom
37 import numpy
38 from timeit import Timer
39 import time
40
41 from .test_pyfftw_base import run_test_suites, miss, require, np_fft
42
43 import unittest
44
45 from .test_pyfftw_complex import Complex64FFTWTest
46
47 class RealBackwardDoubleFFTWTest(Complex64FFTWTest):
48
49 def setUp(self):
50 require(self, '64')
51
52 self.input_dtype = numpy.complex128
53 self.output_dtype = numpy.float64
54 self.np_fft_comparison = np_fft.irfft
55
56 self.direction = 'FFTW_BACKWARD'
57
58 def make_shapes(self):
59
60 self.input_shapes = {
61 'small_1d': (9,),
62 '1d': (1025,),
63 '2d': (256, 1025),
64 '3d': (5, 256, 1025)}
65
66 self.output_shapes = {
67 'small_1d': (16,),
68 '1d': (2048,),
69 '2d': (256, 2048),
70 '3d': (5, 256, 2048)}
71
72 def test_invalid_args_raise(self):
73 in_shape = self.input_shapes['1d']
74 out_shape = self.output_shapes['1d']
75
76 axes=(-1,)
77 a, b = self.create_test_arrays(in_shape, out_shape)
78
79 # Note "thread" is incorrect, it should be "threads"
80 self.assertRaises(TypeError, FFTW, a, b, axes,
81 direction='FFTW_BACKWARD', thread=4)
82
83 def create_test_arrays(self, input_shape, output_shape, axes=None):
84
85 a = self.input_dtype(numpy.random.randn(*input_shape)
86 +1j*numpy.random.randn(*input_shape))
87
88 b = self.output_dtype(numpy.random.randn(*output_shape))
89
90 # We fill a by doing the forward FFT from b.
91 # This means that the relevant bits that should be purely
92 # real will be (for example the zero freq component).
93 # This is easier than writing a complicate system to work it out.
94 try:
95 if axes == None:
96 fft = FFTW(b,a,direction='FFTW_FORWARD')
97 else:
98 fft = FFTW(b,a,direction='FFTW_FORWARD', axes=axes)
99
100 b[:] = self.output_dtype(numpy.random.randn(*output_shape))
101
102 fft.execute()
103
104 scaling = numpy.prod(numpy.array(a.shape))
105 a = self.input_dtype(a/scaling)
106
107 except ValueError:
108 # In this case, we assume that it was meant to error,
109 # so we can return what we want.
110 pass
111
112 b = self.output_dtype(numpy.random.randn(*output_shape))
113
114 return a, b
115
116 def run_validate_fft(self, a, b, axes, fft=None, ifft=None,
117 force_unaligned_data=False, create_array_copies=True,
118 threads=1, flags=('FFTW_ESTIMATE',)):
119 ''' *** EVERYTHING IS FLIPPED AROUND BECAUSE WE ARE
120 VALIDATING AN INVERSE FFT ***
121
122 Run a validation of the FFTW routines for the passed pair
123 of arrays, a and b, and the axes argument.
124
125 a and b are assumed to be the same shape (but not necessarily
126 the same layout in memory).
127
128 fft and ifft, if passed, should be instantiated FFTW objects.
129
130 If force_unaligned_data is True, the flag FFTW_UNALIGNED
131 will be passed to the fftw routines.
132 '''
133 if create_array_copies:
134 # Don't corrupt the original mutable arrays
135 a = a.copy()
136 b = b.copy()
137
138 a_orig = a.copy()
139
140 flags = list(flags)
141
142 if force_unaligned_data:
143 flags.append('FFTW_UNALIGNED')
144
145 if ifft == None:
146 ifft = FFTW(a, b, axes=axes, direction='FFTW_BACKWARD',
147 flags=flags, threads=threads)
148 else:
149 ifft.update_arrays(a,b)
150
151 if fft == None:
152 fft = FFTW(b, a, axes=axes, direction='FFTW_FORWARD',
153 flags=flags, threads=threads)
154 else:
155 fft.update_arrays(b,a)
156
157
158 a[:] = a_orig
159 # Test the inverse FFT by comparing it to the result from numpy.fft
160 ifft.execute()
161
162 a[:] = a_orig
163 ref_b = self.reference_fftn(a, axes=axes)
164
165 # The scaling is the product of the lengths of the fft along
166 # the axes along which the fft is taken.
167 scaling = numpy.prod(numpy.array(b.shape)[list(axes)])
168 self.assertEqual(ifft.N, scaling)
169 self.assertEqual(fft.N, scaling)
170
171 # This is actually quite a poor relative error, but it still
172 # sometimes fails. I assume that numpy.fft has different internals
173 # to fftw.
174 self.assertTrue(numpy.allclose(b/scaling, ref_b, rtol=1e-2, atol=1e-3))
175
176 # Test the FFT by comparing the result to the starting
177 # value (which is scaled as per FFTW being unnormalised).
178 fft.execute()
179
180 self.assertTrue(numpy.allclose(a/scaling, a_orig, rtol=1e-2, atol=1e-3))
181 return fft, ifft
182
183 def test_time_with_array_update(self):
184 in_shape = self.input_shapes['2d']
185 out_shape = self.output_shapes['2d']
186
187 axes=(-1,)
188 a, b = self.create_test_arrays(in_shape, out_shape)
189
190 fft, ifft = self.run_validate_fft(a, b, axes)
191
192 def fftw_callable():
193 fft.update_arrays(b,a)
194 fft.execute()
195
196 self.timer_routine(fftw_callable,
197 lambda: self.np_fft_comparison(a))
198
199 self.assertTrue(True)
200
201 def reference_fftn(self, a, axes):
202 # This needs to be an inverse
203 return np_fft.irfftn(a, axes=axes)
204
205 def test_wrong_direction_fail(self):
206 in_shape = self.input_shapes['2d']
207 out_shape = self.output_shapes['2d']
208
209 axes=(-1,)
210 a, b = self.create_test_arrays(in_shape, out_shape)
211
212 with self.assertRaisesRegex(ValueError, 'Invalid direction'):
213 FFTW(a, b, direction='FFTW_FORWARD')
214
215 def test_planning_time_limit(self):
216 in_shape = self.input_shapes['1d']
217 out_shape = self.output_shapes['1d']
218
219 axes=(0,)
220 a, b = self.create_test_arrays(in_shape, out_shape)
221
222 # run this a few times
223 runs = 10
224 t1 = time.time()
225 for n in range(runs):
226 forget_wisdom()
227 fft = FFTW(b, a, axes=axes)
228
229 unlimited_time = (time.time() - t1)/runs
230
231 time_limit = (unlimited_time)/8
232
233 # Now do it again but with an upper limit on the time
234 t1 = time.time()
235 for n in range(runs):
236 forget_wisdom()
237 fft = FFTW(b, a, axes=axes, planning_timelimit=time_limit)
238
239 limited_time = (time.time() - t1)/runs
240
241 import sys
242 if sys.platform == 'win32':
243 # Give a 4x margin on windows. The timers are low
244 # precision and FFTW seems to take longer anyway
245 self.assertTrue(limited_time < time_limit*4)
246 else:
247 # Otherwise have a 2x margin
248 self.assertTrue(limited_time < time_limit*2)
249
250 def test_invalid_planning_time_limit(self):
251 in_shape = self.input_shapes['1d']
252 out_shape = self.output_shapes['1d']
253
254 axes=(0,)
255 a, b = self.create_test_arrays(in_shape, out_shape)
256
257 self.assertRaisesRegex(TypeError, 'Invalid planning timelimit',
258 FFTW, *(b, a, axes), **{'planning_timelimit': 'foo'})
259
260 def test_default_args(self):
261 in_shape = self.input_shapes['2d']
262 out_shape = self.output_shapes['2d']
263
264 a, b = self.create_test_arrays(in_shape, out_shape)
265
266 # default args should fail for backwards transforms
267 # (as the default is FFTW_FORWARD)
268 with self.assertRaisesRegex(ValueError, 'Invalid direction'):
269 FFTW(a, b)
270
271 def test_non_contiguous_2d(self):
272 in_shape = self.input_shapes['2d']
273 out_shape = self.output_shapes['2d']
274
275 axes=(-2,-1)
276 a, b = self.create_test_arrays(in_shape, out_shape)
277
278 # Some arbitrary and crazy slicing
279 a_sliced = a[20:146:2, 100:786:7]
280 # b needs to be compatible
281 b_sliced = b[12:200:3, 300:2041:9]
282
283 self.run_validate_fft(a_sliced, b_sliced, axes, create_array_copies=False)
284
285 def test_non_contiguous_2d_in_3d(self):
286 in_shape = (256, 4, 1025)
287 out_shape = (256, 4, 2048)
288 axes=(0,2)
289 a, b = self.create_test_arrays(in_shape, out_shape)
290
291 # Some arbitrary and crazy slicing
292 a_sliced = a[20:146:2, :, 100:786:7]
293 # b needs to be compatible
294 b_sliced = b[12:200:3, :, 300:2041:9]
295
296 # The data doesn't work, so we need to generate it for the
297 # correct size
298 a_, b_ = self.create_test_arrays(a_sliced.shape, b_sliced.shape, axes=axes)
299
300 # And then copy it into the non contiguous array
301 a_sliced[:] = a_
302 b_sliced[:] = b_
303
304 self.run_validate_fft(a_sliced, b_sliced, axes, create_array_copies=False)
305
306 def test_non_monotonic_increasing_axes(self):
307 super(RealBackwardDoubleFFTWTest,
308 self).test_non_monotonic_increasing_axes()
309
310 @unittest.skipIf(*miss('32'))
311 class RealBackwardSingleFFTWTest(RealBackwardDoubleFFTWTest):
312
313 def setUp(self):
314
315 self.input_dtype = numpy.complex64
316 self.output_dtype = numpy.float32
317 self.np_fft_comparison = np_fft.irfft
318
319 self.direction = 'FFTW_BACKWARD'
320
321 @unittest.skipIf(*miss('ld'))
322 class RealBackwardLongDoubleFFTWTest(RealBackwardDoubleFFTWTest):
323
324 def setUp(self):
325
326 self.input_dtype = numpy.clongdouble
327 self.output_dtype = numpy.longdouble
328 self.np_fft_comparison = np_fft.irfft
329
330 self.direction = 'FFTW_BACKWARD'
331
332 def reference_fftn(self, a, axes):
333
334 a = numpy.complex128(a)
335 return np_fft.irfftn(a, axes=axes)
336
337 @unittest.skip('numpy.fft has issues with this dtype.')
338 def test_time(self):
339 pass
340
341 @unittest.skip('numpy.fft has issues with this dtype.')
342 def test_time_with_array_update(self):
343 pass
344
345 test_cases = (
346 RealBackwardDoubleFFTWTest,
347 RealBackwardSingleFFTWTest,
348 RealBackwardLongDoubleFFTWTest,)
349
350 test_set = None
351
352 if __name__ == '__main__':
353
354 run_test_suites(test_cases, test_set)
355
356 del Complex64FFTWTest