Debian Codegraph @

tests/test_r2r.py

raw
1 #!/usr/bin/env python
2 #
3 # Copyright 2014 Knowledge Economy Developments Ltd
4 # Copyright 2014 - 2016 David Wells
5 #
6 # Henry Gomersall
7 # [email protected]
8 #
9 # All rights reserved.
10 #
11 # Redistribution and use in source and binary forms, with or without
12 # modification, are permitted provided that the following conditions are met:
13 #
14 # * Redistributions of source code must retain the above copyright notice, this
15 # list of conditions and the following disclaimer.
16 #
17 # * Redistributions in binary form must reproduce the above copyright notice,
18 # this list of conditions and the following disclaimer in the documentation
19 # and/or other materials provided with the distribution.
20 #
21 # * Neither the name of the copyright holder nor the names of its contributors
22 # may be used to endorse or promote products derived from this software without
23 # specific prior written permission.
24 #
25 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
29 # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 # POSSIBILITY OF SUCH DAMAGE.
36 #
37
38 from __future__ import division
39 import itertools as it
40 import random as rand
41 import unittest
42 import numpy
43
44 import pyfftw
45 from pyfftw import _supported_types
46 from .test_pyfftw_base import run_test_suites
47
48 discrete_sine_directions = ['FFTW_RODFT00', 'FFTW_RODFT01', 'FFTW_RODFT10',
49 'FFTW_RODFT11']
50
51 discrete_cosine_directions = ['FFTW_REDFT00', 'FFTW_REDFT01', 'FFTW_REDFT10',
52 'FFTW_REDFT11']
53
54 real_transforms = discrete_sine_directions + discrete_cosine_directions
55
56 normalisation_lookup = {
57 'FFTW_RODFT00': lambda n: 2*(n + 1),
58 'FFTW_RODFT01': lambda n: 2*n,
59 'FFTW_RODFT10': lambda n: 2*n,
60 'FFTW_RODFT11': lambda n: 2*n,
61 'FFTW_REDFT00': lambda n: 2*(n - 1),
62 'FFTW_REDFT01': lambda n: 2*n,
63 'FFTW_REDFT10': lambda n: 2*n,
64 'FFTW_REDFT11': lambda n: 2*n,
65 }
66
67 inverse_lookup = {
68 'FFTW_RODFT00': 'FFTW_RODFT00',
69 'FFTW_RODFT01': 'FFTW_RODFT10',
70 'FFTW_RODFT10': 'FFTW_RODFT01',
71 'FFTW_RODFT11': 'FFTW_RODFT11',
72 'FFTW_REDFT00': 'FFTW_REDFT00',
73 'FFTW_REDFT01': 'FFTW_REDFT10',
74 'FFTW_REDFT10': 'FFTW_REDFT01',
75 'FFTW_REDFT11': 'FFTW_REDFT11',
76 }
77
78 interpolated_function_lookup = {
79 'FFTW_RODFT00': lambda k, x: numpy.sin(numpy.pi*(k + 1)*x),
80 'FFTW_RODFT01': lambda k, x: numpy.sin(numpy.pi*(k + 0.5)*x),
81 'FFTW_RODFT10': lambda k, x: numpy.sin(numpy.pi*(k + 1)*x),
82 'FFTW_RODFT11': lambda k, x: numpy.sin(numpy.pi*(k + 0.5)*x),
83
84 'FFTW_REDFT00': lambda k, x: numpy.cos(numpy.pi*k*x),
85 'FFTW_REDFT10': lambda k, x: numpy.cos(numpy.pi*k*x),
86 'FFTW_REDFT01': lambda k, x: numpy.cos(numpy.pi*(k + 0.5)*x),
87 'FFTW_REDFT11': lambda k, x: numpy.cos(numpy.pi*(k + 0.5)*x),
88 }
89
90 nodes_lookup = {
91 'FFTW_RODFT00': lambda n: numpy.arange(n + 2)[1:-1]/(n + 1),
92 'FFTW_RODFT01': lambda n: numpy.arange(1, n + 1)/n,
93 'FFTW_RODFT10': lambda n: (numpy.arange(n) + 0.5)/n,
94 'FFTW_RODFT11': lambda n: (numpy.arange(n) + 0.5)/n,
95
96 'FFTW_REDFT00': lambda n: numpy.arange(n)/(n - 1),
97 'FFTW_REDFT10': lambda n: (numpy.arange(n) + 0.5)/n,
98 'FFTW_REDFT01': lambda n: numpy.arange(n)/n,
99 'FFTW_REDFT11': lambda n: (numpy.arange(n) + 0.5)/n,
100 }
101
102 @unittest.skipIf('64' not in _supported_types, 'double precision unavailable')
103 class TestRealToRealLookups(unittest.TestCase):
104 '''Test that the lookup tables correctly pair node choices and
105 function choices for using the DCT/DST as interpolators.
106 '''
107 def test_lookups(self):
108 n = rand.randint(10, 20)
109 j = rand.randint(5, n) - 3
110 for transform in real_transforms:
111 nodes = nodes_lookup[transform](n)
112 data = interpolated_function_lookup[transform](j, nodes)
113 output = numpy.empty_like(data)
114 plan = pyfftw.FFTW(data, output, direction=[transform])
115 data[:] = interpolated_function_lookup[transform](j, nodes)
116 plan.execute()
117 tol = 4*j*n*1e-16
118 if transform == 'FFTW_RODFT00':
119 self.assertTrue(abs(output[j] - n - 1) < tol)
120 elif transform == 'FFTW_REDFT00':
121 self.assertTrue(abs(output[j] - n + 1) < tol)
122 else:
123 self.assertTrue(abs(output[j] - n) < tol)
124
125 class TestRealTransform(object):
126 '''Common set of functionality for performing tests on the real to
127 real transforms. This is not implemented as a distinct test class
128 (inheriting from unittest.TestCase) because its `__init__` method
129 takes multiple arguments as input which set up the size and
130 directions of the transform.
131 '''
132 def __init__(self, directions=['FFTW_REDFT00'], dims=(16, ), axes=None,
133 noncontiguous=True, dtype=None):
134 """
135 Arguments:
136
137 - `directions`: List of abbreviated directions, like 'O11' or 'E01'.
138
139 - `dims`: Shape of the data.
140
141 - `axes`: Axes on which to take the transformation. Defaults to the
142 number of directions.
143 """
144 if axes is None:
145 self.axes = tuple(range(len(directions)))
146 else:
147 self.axes = axes
148 for dim in dims:
149 if dim < 3:
150 raise NotImplementedError("Due to complications with the DCT1, "
151 "arrays must be of length at least "
152 "three.")
153
154 if len(self.axes) != len(directions):
155 raise ValueError("There must be exactly one axis per direction.")
156
157 self.directions = directions
158 self.inverse_directions = [inverse_lookup[direction]
159 for direction in directions]
160 self.dims = dims
161 self._normalisation_factor = 1.0
162 for index, axis in enumerate(self.axes):
163 dim = self.dims[axis]
164 direction = self.directions[index]
165 self._normalisation_factor *= normalisation_lookup[direction](dim)
166
167 if noncontiguous:
168 self._input_array = empty_noncontiguous(dims)
169 self._output_array = empty_noncontiguous(dims)
170 else:
171 self._input_array = numpy.zeros(dims)
172 self._output_array = numpy.zeros(dims)
173 self.plan = pyfftw.FFTW(self._input_array, self._output_array,
174 axes=self.axes, direction=self.directions)
175 self.inverse_plan = pyfftw.FFTW(self._input_array, self._output_array,
176 axes=self.axes, direction=self.inverse_directions)
177
178 self.tol = 1e-10
179 if dtype is None:
180 if '64' in _supported_types:
181 dtype = numpy.float64
182 elif '32' in _supported_types:
183 dtype = numpy.float32
184 self.tol = 1e-5
185 elif 'ld' in _supported_types:
186 dtype = numpy.longdouble
187 self.tol = 1e-14
188 self.dtype = dtype
189
190 def test_normalisation(self):
191 return self._normalisation_factor == float(self.plan._get_N())
192
193 def test_against_random_data(self):
194 data = numpy.random.rand(*self.dims).astype(self.dtype, copy=False)
195 self._input_array[:] = data
196 self.plan.execute()
197 self._input_array[:] = self._output_array[:]
198 self.inverse_plan.execute()
199
200 data *= self._normalisation_factor
201 err = numpy.mean(numpy.abs(data - self._output_array))/self._normalisation_factor
202 return err < self.tol
203
204 def test_against_exact_data(self):
205 points = grid(self.dims, self.axes, self.directions)
206 data = numpy.ones_like(points[0], dtype=self.dtype)
207 wavenumbers = list()
208 factors = list()
209
210 for index, axis in enumerate(self.axes):
211 # Simplification: don't test constant terms. They are weird.
212 if self.directions[index] in discrete_cosine_directions:
213 wavenumber_min = 1
214 wavenumber_max = self.dims[axis] - 2
215 else:
216 wavenumber_min = 0
217 wavenumber_max = self.dims[axis] - 2
218 _wavenumbers = sorted({rand.randint(wavenumber_min, wavenumber_max)
219 for _ in range(self.dims[axis])})
220 _factors = [rand.randint(1, 8) for _ in _wavenumbers]
221 interpolated_function = interpolated_function_lookup[
222 self.directions[index]]
223 data *= sum((factor*interpolated_function(wavenumber, points[axis])
224 for factor, wavenumber in zip(_factors, _wavenumbers)))
225 wavenumbers.append(numpy.array(_wavenumbers))
226 factors.append(numpy.array(_factors))
227
228 self._input_array[:] = data
229 self.plan.execute()
230
231 # zero all of the entries that do not correspond to a wavenumber.
232 exact_coefficients = numpy.ones(data.shape)
233 for index, axis in enumerate(self.axes):
234 dim = self.dims[axis]
235 sp = list(it.repeat(slice(None), len(data.shape)))
236 zero_indicies = (numpy.array(list(set(numpy.arange(0, dim)) -
237 set(wavenumbers[index]))))
238 if len(zero_indicies) == 0:
239 pass
240 else:
241 sp[axis] = zero_indicies
242 mask = numpy.ones(data.shape)
243 mask[tuple(sp)] = 0.0
244 exact_coefficients *= mask
245
246 # create the 'known' array of interpolation coefficients.
247 normalisation = self.plan.N/(2**len(self.axes))
248 for index, axis in enumerate(self.axes):
249 for factor, wavenumber in zip(factors[index], wavenumbers[index]):
250 sp = list(it.repeat(slice(None), len(data.shape)))
251 sp[axis] = wavenumber
252 exact_coefficients[tuple(sp)] *= factor
253
254 error = numpy.mean(numpy.abs(self._output_array/normalisation -
255 exact_coefficients))
256 return error < self.tol
257
258
259 def meshgrid(*x):
260 if len(x) == 1:
261 # necessary for one-dimensional case to work correctly. x is a
262 # tuple due to the * operator.
263 return x
264 else:
265 args = numpy.atleast_1d(*x)
266 s0 = (1,)*len(args)
267 return list(map(numpy.squeeze,
268 numpy.broadcast_arrays(*[x.reshape(s0[:i] + (-1,) + s0[i + 1::])
269 for i, x in enumerate(args)])))
270
271
272 def grid(shape, axes, directions, aspect_ratio=None):
273 grids = [numpy.linspace(1, 2, dim) for dim in shape]
274 for index, (axis, direction) in enumerate(zip(axes, directions)):
275 grids[axis] = nodes_lookup[direction](shape[axes[index]])
276
277 return numpy.array(meshgrid(*grids))
278
279
280 def empty_noncontiguous(shape):
281 '''Create a non-contiguous empty array with shape `shape`.
282 '''
283 offsets = lambda s: [rand.randint(0, 3) for _ in s]
284 strides = lambda s: [rand.randint(1, 3) for _ in s]
285 parent_left_offsets = offsets(shape)
286 parent_right_offsets = offsets(shape)
287 parent_strides = strides(shape)
288
289 parent_shape = list()
290 child_slice = list()
291 for index, length in enumerate(shape):
292 left_offset = parent_left_offsets[index]
293 right_offset = parent_right_offsets[index]
294 stride = parent_strides[index]
295 parent_shape.append(left_offset + stride*length + right_offset)
296 if right_offset == 0:
297 child_slice.append(slice(left_offset, None, stride))
298 else:
299 child_slice.append(slice(left_offset, -1*right_offset, stride))
300
301 child = numpy.empty(parent_shape)[tuple(child_slice)]
302 if list(child.shape) != list(shape):
303 raise ValueError("The shape of the noncontiguous array is incorrect."
304 " This is a bug.")
305 return child
306
307
308 def random_testcase():
309 ndims = rand.randint(1, 5)
310
311 axes = list()
312 directions = list()
313 dims = list()
314 for dim in range(ndims):
315 if ndims > 3:
316 dims.append(rand.randint(3, 10))
317 else:
318 dims.append(rand.randint(3, 100))
319 # throw out some dimensions randomly
320 if rand.choice([True, True, False]):
321 directions.append(rand.choice(real_transforms))
322 axes.append(dim)
323
324 if len(axes) == 0:
325 # reroll.
326 return random_testcase()
327 else:
328 return TestRealTransform(directions, dims, axes=axes)
329
330
331 @unittest.skipIf('64' not in _supported_types, 'double precision unavailable')
332 class RealToRealNormalisation(unittest.TestCase):
333 def test_normalisation(self):
334 for _ in range(50):
335 testcase = random_testcase()
336 self.assertTrue(testcase.test_normalisation())
337
338 @unittest.skipIf('64' not in _supported_types, 'double precision unavailable')
339 class RealToRealExactData(unittest.TestCase):
340 def test_exact_data(self):
341 for _ in range(50):
342 testcase = random_testcase()
343 self.assertTrue(testcase.test_against_exact_data())
344
345 @unittest.skipIf('64' not in _supported_types, 'double precision unavailable')
346 class RealToRealRandomData(unittest.TestCase):
347 def test_random_data(self):
348 for _ in range(50):
349 testcase = random_testcase()
350 self.assertTrue(testcase.test_against_random_data())
351
352 test_cases = (TestRealToRealLookups,
353 RealToRealNormalisation,
354 RealToRealExactData,
355 RealToRealRandomData,)
356
357 if __name__ == '__main__':
358 run_test_suites(test_cases)