Debian Codegraph @

tests/test_pyfftw_dask_interface.py

raw
1 # Copyright 2015 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 interfaces
36
37 try:
38 interfaces.dask_fft
39 except AttributeError:
40 interfaces.dask_fft = None
41
42 try:
43 # Kludge to skip dask tests when mkl_fft is present
44 import mkl_fft
45 interfaces.dask_fft = None
46 except ImportError:
47 pass
48
49 from .test_pyfftw_base import run_test_suites
50 from .test_pyfftw_numpy_interface import complex_dtypes, real_dtypes
51 from ._get_default_args import get_default_args
52
53 import unittest
54 import numpy
55
56 if interfaces.dask_fft:
57 import dask.array as da
58 from dask.array import fft as da_fft
59 from dask.array.fft import fft_wrap
60 else:
61 da = None
62 da_fft = None
63 fft_wrap = None
64
65 import warnings
66 import copy
67
68 from packaging.version import Version
69
70
71 warnings.filterwarnings('always')
72
73
74 def make_complex_data(shape, dtype):
75 ar, ai = dtype(numpy.random.randn(2, *shape))
76 ac = ar + 1j*ai
77
78 return da.from_array(ac, chunks=shape)
79
80 def make_real_data(shape, dtype):
81 ar = dtype(numpy.random.randn(*shape))
82
83 return da.from_array(ar, chunks=shape)
84
85 def _dask_array_fft_has_norm_kwarg():
86 """returns True if dask.array's fft supports the norm keyword argument
87 """
88
89 return False
90
91 functions = {
92 'fft': 'complex',
93 'fft2': 'complex',
94 'fftn': 'complex',
95 'ifft': 'complex',
96 'ifft2': 'complex',
97 'ifftn': 'complex',
98 'rfft': 'r2c',
99 'rfft2': 'r2c',
100 'rfftn': 'r2c',
101 'irfft': 'c2r',
102 'irfft2': 'c2r',
103 'irfftn': 'c2r',
104 'hfft': 'c2r',
105 'ihfft': 'r2c'}
106
107 acquired_names = ('fft_wrap', 'fftfreq', 'rfftfreq', 'fftshift', 'ifftshift')
108
109 @unittest.skipIf(
110 not interfaces.dask_fft,
111 "dask interface is not available, so skipping tests."
112 )
113 class InterfacesDaskFFTTestModule(unittest.TestCase):
114 ''' A really simple test suite to check the module works as expected.
115 '''
116
117 def test_acquired_names(self):
118 for each_name in acquired_names:
119
120 da_fft_attr = getattr(da_fft, each_name)
121 acquired_attr = getattr(interfaces.dask_fft, each_name)
122
123 self.assertIs(da_fft_attr, acquired_attr)
124
125
126 @unittest.skipIf(
127 not interfaces.dask_fft,
128 "dask interface is not available, so skipping tests."
129 )
130 class InterfacesDaskFFTTestFFT(unittest.TestCase):
131
132 io_dtypes = {
133 'complex': (complex_dtypes, make_complex_data),
134 'r2c': (real_dtypes, make_real_data),
135 'c2r': (complex_dtypes, make_complex_data)}
136
137 validator_module = da_fft
138 test_wrapped_interface = interfaces.numpy_fft
139 test_interface = interfaces.dask_fft
140 func = 'fft'
141 axes_kw = 'axis'
142 default_s_from_shape_slicer = slice(-1, None)
143
144 test_shapes = (
145 ((100,), {}),
146 ((128, 64), {'axis': 0}),
147 ((128, 32), {'axis': -1}),
148 ((59, 100), {}),
149 ((59, 99), {'axis': -1}),
150 ((59, 99), {'axis': 0}),
151 ((32, 32, 4), {'axis': 1}),
152 ((32, 32, 2), {'axis': 1, 'norm': 'ortho'}),
153 ((32, 32, 2), {'axis': 1, 'norm': None}),
154 ((32, 32, 2), {'axis': 1, 'norm': 'backward'}),
155 ((32, 32, 2), {'axis': 1, 'norm': 'forward'}),
156 ((64, 128, 16), {}),
157 )
158
159 realinv = False
160 has_norm_kwarg = _dask_array_fft_has_norm_kwarg()
161
162 @property
163 def test_data(self):
164 for test_shape, kwargs in self.test_shapes:
165 axes = self.axes_from_kwargs(kwargs)
166 s = self.s_from_kwargs(test_shape, kwargs)
167
168 if not self.has_norm_kwarg and 'norm' in kwargs:
169 kwargs.pop('norm')
170
171 if self.realinv:
172 test_shape = list(test_shape)
173 test_shape[axes[-1]] = test_shape[axes[-1]]//2 + 1
174 test_shape = tuple(test_shape)
175
176 yield test_shape, s, kwargs
177
178 def __init__(self, *args, **kwargs):
179
180 super(InterfacesDaskFFTTestFFT, self).__init__(*args, **kwargs)
181
182 # Assume python 3, but keep backwards compatibility
183 if not hasattr(self, 'assertRaisesRegex'):
184 self.assertRaisesRegex = self.assertRaisesRegexp
185
186 def validate(self, array_type, test_shape, dtype,
187 s, kwargs):
188
189 # Do it without the cache
190
191 # without:
192 interfaces.cache.disable()
193 self._validate(array_type, test_shape, dtype, s, kwargs)
194
195 def munge_input_array(self, array, kwargs):
196 return array
197
198 def _validate(self, array_type, test_shape, dtype,
199 s, kwargs):
200
201 input_array = self.munge_input_array(
202 array_type(test_shape, dtype), kwargs)
203
204 orig_input_array = input_array
205
206 np_input_array = numpy.asarray(input_array)
207
208 if np_input_array.dtype == 'clongdouble':
209 np_input_array = numpy.complex128(input_array)
210
211 elif np_input_array.dtype == 'longdouble':
212 np_input_array = numpy.float64(input_array)
213
214 da_input_array = da.from_array(np_input_array,
215 chunks=np_input_array.shape)
216
217
218 with warnings.catch_warnings(record=True) as w:
219 # We catch the warnings so as to pick up on when
220 # a complex array is turned into a real array
221
222 if 'axes' in kwargs:
223 validator_kwargs = {'axes': kwargs['axes']}
224 elif 'axis' in kwargs:
225 validator_kwargs = {'axis': kwargs['axis']}
226 else:
227 validator_kwargs = {}
228
229 if self.has_norm_kwarg and 'norm' in kwargs:
230 validator_kwargs['norm'] = kwargs['norm']
231
232 try:
233 test_out_array = getattr(self.validator_module, self.func)(
234 da_input_array, s, **validator_kwargs)
235
236 except Exception as e:
237 interface_exception = None
238 try:
239 getattr(self.test_interface, self.func)(
240 input_array, s, **kwargs)
241 except Exception as _interface_exception:
242 # It's necessary to assign the exception to the
243 # already defined variable in Python 3.
244 # See http://www.python.org/dev/peps/pep-3110/#semantic-changes
245 interface_exception = _interface_exception
246
247 # If the test interface raised, so must this.
248 self.assertEqual(type(interface_exception), type(e),
249 msg='Interface exception raised. ' +
250 'Testing for: ' + repr(e))
251 return
252
253 output_array = getattr(self.test_interface, self.func)(
254 input_array, s, **kwargs)
255
256 if (functions[self.func] == 'r2c'):
257 if input_array.dtype.kind == 'c':
258 if len(w) > 0:
259 # Make sure a warning is raised
260 self.assertIs(
261 w[-1].category, numpy.ComplexWarning)
262
263 # convert dask arrays to NumPy ones prior to calling allclose
264 output_np = output_array.compute()
265 input_np = input_array.compute()
266 test_out_array = test_out_array.compute()
267
268 self.assertTrue(
269 numpy.allclose(output_np, test_out_array,
270 rtol=1e-2, atol=1e-4))
271
272 if input_np.real.dtype == numpy.float16:
273 # FFTW output will never be single precision for half precision
274 # inputs as there is no half-precision FFTW routine
275 input_precision_dtype = numpy.float32
276 else:
277 input_precision_dtype = input_np.real.dtype
278
279 self.assertEqual(input_precision_dtype,
280 output_array.real.dtype)
281
282 self.assertTrue(numpy.allclose(input_array,
283 orig_input_array))
284
285 return output_array
286
287 def axes_from_kwargs(self, kwargs):
288 default_args = get_default_args(
289 getattr(self.test_wrapped_interface, self.func))
290
291 if 'axis' in kwargs:
292 axes = (kwargs['axis'],)
293
294 elif 'axes' in kwargs:
295 axes = kwargs['axes']
296 if axes is None:
297 axes = default_args['axes']
298
299 else:
300 if 'axis' in default_args:
301 # default 1D
302 axes = (default_args['axis'],)
303 else:
304 # default nD
305 axes = default_args['axes']
306
307 if axes is None:
308 axes = (-1,)
309
310 return axes
311
312 def s_from_kwargs(self, test_shape, kwargs):
313 ''' Return either a scalar s or a tuple depending on
314 whether axis or axes is specified
315 '''
316 default_args = get_default_args(
317 getattr(self.test_wrapped_interface, self.func))
318
319 if 'axis' in kwargs:
320 s = test_shape[kwargs['axis']]
321
322 elif 'axes' in kwargs:
323 axes = kwargs['axes']
324 if axes is not None:
325 s = []
326 for each_axis in axes:
327 s.append(test_shape[each_axis])
328 else:
329 # default nD
330 s = []
331 try:
332 for each_axis in default_args['axes']:
333 s.append(test_shape[each_axis])
334 except TypeError:
335 try:
336 s = list(test_shape[
337 self.default_s_from_shape_slicer])
338 except TypeError:
339 # We had an integer as the default, so force
340 # it to be a list
341 s = [test_shape[self.default_s_from_shape_slicer]]
342
343 else:
344 if 'axis' in default_args:
345 # default 1D
346 s = test_shape[default_args['axis']]
347 else:
348 # default nD
349 s = []
350 try:
351 for each_axis in default_args['axes']:
352 s.append(test_shape[each_axis])
353 except TypeError:
354 s = None
355
356 return s
357
358 def test_valid(self):
359 dtype_tuple = self.io_dtypes[functions[self.func]]
360
361 for dtype in dtype_tuple[0]:
362 for test_shape, s, kwargs in self.test_data:
363 s = None
364
365 self.validate(dtype_tuple[1],
366 test_shape, dtype, s, kwargs)
367
368
369 def test_same_sized_s(self):
370 dtype_tuple = self.io_dtypes[functions[self.func]]
371 for dtype in dtype_tuple[0]:
372 for test_shape, s, kwargs in self.test_data:
373
374 self.validate(dtype_tuple[1],
375 test_shape, dtype, s, kwargs)
376
377 def test_bigger_s(self):
378 dtype_tuple = self.io_dtypes[functions[self.func]]
379 for dtype in dtype_tuple[0]:
380 for test_shape, s, kwargs in self.test_data:
381
382 try:
383 for each_axis, length in enumerate(s):
384 s[each_axis] += 2
385 except TypeError:
386 s += 2
387
388 self.validate(dtype_tuple[1],
389 test_shape, dtype, s, kwargs)
390
391
392 def test_smaller_s(self):
393 dtype_tuple = self.io_dtypes[functions[self.func]]
394 for dtype in dtype_tuple[0]:
395 for test_shape, s, kwargs in self.test_data:
396
397 try:
398 for each_axis, length in enumerate(s):
399 s[each_axis] -= 2
400 except TypeError:
401 s -= 2
402
403 self.validate(dtype_tuple[1],
404 test_shape, dtype, s, kwargs)
405
406 def check_arg(self, arg, arg_test_values, array_type, test_shape,
407 dtype, s, kwargs):
408 '''Check that the correct arg is passed to the builder'''
409 # We trust the builders to work as expected when passed
410 # the correct arg (the builders have their own unittests).
411
412 return_values = []
413 input_array = array_type(test_shape, dtype)
414
415 def fake_fft(*args, **kwargs):
416 return_values.append((args, kwargs))
417 return (args, kwargs)
418
419 try:
420
421 # Replace the function that is to be used
422 real_fft = getattr(self.test_interface, self.func)
423 setattr(self.test_interface, self.func, fake_fft)
424
425 _kwargs = kwargs.copy()
426
427 for each_value in arg_test_values:
428 _kwargs[arg] = each_value
429 builder_args = getattr(self.test_interface, self.func)(
430 input_array.copy(), s, **_kwargs)
431
432 self.assertTrue(builder_args[1][arg] == each_value)
433
434 # make sure it was called
435 self.assertTrue(len(return_values) > 0)
436 except:
437 raise
438
439 finally:
440 # Make sure we set it back
441 setattr(self.test_interface, self.func, real_fft)
442
443 # Validate it aswell
444 for each_value in arg_test_values:
445 _kwargs[arg] = each_value
446 builder_args = getattr(self.test_interface, self.func)(
447 input_array.copy(), s, **_kwargs)
448
449 self.validate(array_type, test_shape, dtype, s, _kwargs)
450
451
452 def test_bigger_and_smaller_s(self):
453 dtype_tuple = self.io_dtypes[functions[self.func]]
454 for dtype in dtype_tuple[0]:
455 i = -1
456 for test_shape, s, kwargs in self.test_data:
457
458 try:
459 for each_axis, length in enumerate(s):
460 s[each_axis] += i * 2
461 i *= i
462 except TypeError:
463 s += i * 2
464 i *= i
465
466 self.validate(dtype_tuple[1],
467 test_shape, dtype, s, kwargs)
468
469 @unittest.skipIf(
470 Version(numpy.version.version) >= Version("2.0"),
471 reason="Unsupported for Numpy >=2.0"
472 )
473 def test_dtype_coercion(self):
474 # Make sure we input a dtype that needs to be coerced
475 if functions[self.func] == 'r2c':
476 dtype_tuple = self.io_dtypes['complex']
477 else:
478 dtype_tuple = self.io_dtypes['r2c']
479
480 for dtype in dtype_tuple[0]:
481 for test_shape, s, kwargs in self.test_data:
482 s = None
483
484 self.validate(dtype_tuple[1],
485 test_shape, dtype, s, kwargs)
486
487
488 def test_input_maintained(self):
489 '''Test to make sure the input is maintained by default.
490 '''
491 dtype_tuple = self.io_dtypes[functions[self.func]]
492 for dtype in dtype_tuple[0]:
493 for test_shape, s, kwargs in self.test_data:
494
495 input_array = dtype_tuple[1](test_shape, dtype)
496
497 orig_input_array = input_array.copy()
498
499 getattr(self.test_interface, self.func)(
500 input_array, s, **kwargs)
501
502 self.assertTrue(
503 numpy.all(input_array == orig_input_array))
504
505
506 class InterfacesDaskFFTTestFFT2(InterfacesDaskFFTTestFFT):
507 axes_kw = 'axes'
508 func = 'ifft2'
509 has_norm_kwarg = False
510 test_shapes = (
511 ((128, 64), {'axes': None}),
512 ((128, 32), {'axes': None}),
513 ((128, 32, 4), {'axes': (0, 2)}),
514 ((59, 100), {'axes': (-2, -1)}),
515 ((32, 32), {'axes': (-2, -1), 'norm': 'ortho'}),
516 ((32, 32), {'axes': (-2, -1), 'norm': None}),
517 ((32, 32), {'axes': (-2, -1), 'norm': 'backward'}),
518 ((32, 32), {'axes': (-2, -1), 'norm': 'forward'}),
519 ((64, 128, 16), {'axes': (0, 2)}),
520 ((4, 6, 8, 4), {'axes': (0, 3)}),
521 )
522
523 invalid_args = ()
524
525 def test_shape_and_s_different_lengths(self):
526 dtype_tuple = self.io_dtypes[functions[self.func]]
527 for dtype in dtype_tuple[0]:
528 for test_shape, s, _kwargs in self.test_data:
529 kwargs = copy.copy(_kwargs)
530 try:
531 s = s[1:]
532 except TypeError:
533 self.skipTest('Not meaningful test on 1d arrays.')
534
535 # Convert empty tuples to None
536 s = s if s else None
537
538 del kwargs['axes']
539 self.validate(dtype_tuple[1],
540 test_shape, dtype, s, kwargs)
541
542
543 class InterfacesDaskFFTTestFFTN(InterfacesDaskFFTTestFFT2):
544 func = 'ifftn'
545 has_norm_kwarg = False
546 test_shapes = (
547 ((128, 32, 4), {'axes': None}),
548 ((64, 128, 16), {'axes': (0, 1, 2)}),
549 ((4, 6, 8, 4), {'axes': (0, 3, 1)}),
550 ((4, 6, 4, 4), {'axes': (0, 3, 1), 'norm': 'ortho'}),
551 ((4, 6, 4, 4), {'axes': (0, 3, 1), 'norm': None}),
552 ((4, 6, 4, 4), {'axes': (0, 3, 1), 'norm': 'backward'}),
553 ((4, 6, 4, 4), {'axes': (0, 3, 1), 'norm': 'forward'}),
554 ((4, 6, 8, 4), {'axes': (0, 3, 1, 2)}),
555 )
556
557
558 class InterfacesDaskFFTTestIFFT(InterfacesDaskFFTTestFFT):
559 func = 'ifft'
560 has_norm_kwarg = False
561
562 class InterfacesDaskFFTTestIFFT2(InterfacesDaskFFTTestFFT2):
563 func = 'ifft2'
564 has_norm_kwarg = False
565
566 class InterfacesDaskFFTTestIFFTN(InterfacesDaskFFTTestFFTN):
567 func = 'ifftn'
568 has_norm_kwarg = False
569
570 class InterfacesDaskFFTTestRFFT(InterfacesDaskFFTTestFFT):
571 func = 'rfft'
572 has_norm_kwarg = False
573
574 class InterfacesDaskFFTTestRFFT2(InterfacesDaskFFTTestFFT2):
575 func = 'rfft2'
576 has_norm_kwarg = False
577
578 class InterfacesDaskFFTTestRFFTN(InterfacesDaskFFTTestFFTN):
579 func = 'rfftn'
580 has_norm_kwarg = False
581
582 class InterfacesDaskFFTTestIRFFT(InterfacesDaskFFTTestFFT):
583 func = 'irfft'
584 realinv = True
585 has_norm_kwarg = False
586
587 class InterfacesDaskFFTTestIRFFT2(InterfacesDaskFFTTestFFT2):
588 func = 'irfft2'
589 has_norm_kwarg = False
590 realinv = True
591
592 class InterfacesDaskFFTTestIRFFTN(InterfacesDaskFFTTestFFTN):
593 func = 'irfftn'
594 has_norm_kwarg = False
595 realinv = True
596
597 class InterfacesDaskFFTTestHFFT(InterfacesDaskFFTTestFFT):
598 func = 'hfft'
599 realinv = True
600 has_norm_kwarg = False
601
602 class InterfacesDaskFFTTestIHFFT(InterfacesDaskFFTTestFFT):
603 func = 'ihfft'
604 has_norm_kwarg = False
605
606 test_cases = (
607 InterfacesDaskFFTTestModule,
608 InterfacesDaskFFTTestFFT,
609 InterfacesDaskFFTTestFFT2,
610 InterfacesDaskFFTTestFFTN,
611 InterfacesDaskFFTTestIFFT,
612 InterfacesDaskFFTTestIFFT2,
613 InterfacesDaskFFTTestIFFTN,
614 InterfacesDaskFFTTestRFFT,
615 InterfacesDaskFFTTestRFFT2,
616 InterfacesDaskFFTTestRFFTN,
617 InterfacesDaskFFTTestIRFFT,
618 InterfacesDaskFFTTestIRFFT2,
619 InterfacesDaskFFTTestIRFFTN,
620 InterfacesDaskFFTTestHFFT,
621 InterfacesDaskFFTTestIHFFT)
622
623 test_set = None
624
625 if __name__ == '__main__':
626 run_test_suites(test_cases, test_set)