Debian Codegraph @

pywt/tests/test_multidim.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 from __future__ import division, print_function, absolute_import
4
5 import numpy as np
6 from itertools import combinations
7 from numpy.testing import assert_allclose, assert_, assert_raises, assert_equal
8
9 import pywt
10 # Check that float32, float64, complex64, complex128 are preserved.
11 # Other real types get converted to float64.
12 # complex256 gets converted to complex128
13 dtypes_in = [np.int8, np.float16, np.float32, np.float64, np.complex64,
14 np.complex128]
15 dtypes_out = [np.float64, np.float32, np.float32, np.float64, np.complex64,
16 np.complex128]
17
18 # test complex256 as well if it is available
19 try:
20 dtypes_in += [np.complex256, ]
21 dtypes_out += [np.complex128, ]
22 except AttributeError:
23 pass
24
25
26 def test_dwtn_input():
27 # Array-like must be accepted
28 pywt.dwtn([1, 2, 3, 4], 'haar')
29 # Others must not
30 data = dict()
31 assert_raises(TypeError, pywt.dwtn, data, 'haar')
32 # Must be at least 1D
33 assert_raises(ValueError, pywt.dwtn, 2, 'haar')
34
35
36 def test_3D_reconstruct():
37 data = np.array([
38 [[0, 4, 1, 5, 1, 4],
39 [0, 5, 26, 3, 2, 1],
40 [5, 8, 2, 33, 4, 9],
41 [2, 5, 19, 4, 19, 1]],
42 [[1, 5, 1, 2, 3, 4],
43 [7, 12, 6, 52, 7, 8],
44 [2, 12, 3, 52, 6, 8],
45 [5, 2, 6, 78, 12, 2]]])
46
47 wavelet = pywt.Wavelet('haar')
48 for mode in pywt.Modes.modes:
49 d = pywt.dwtn(data, wavelet, mode=mode)
50 assert_allclose(data, pywt.idwtn(d, wavelet, mode=mode),
51 rtol=1e-13, atol=1e-13)
52
53
54 def test_dwdtn_idwtn_allwavelets():
55 rstate = np.random.RandomState(1234)
56 r = rstate.randn(16, 16)
57 # test 2D case only for all wavelet types
58 wavelist = pywt.wavelist()
59 if 'dmey' in wavelist:
60 wavelist.remove('dmey')
61 for wavelet in wavelist:
62 if wavelet in ['cmor', 'shan', 'fbsp']:
63 # skip these CWT families to avoid warnings
64 continue
65 if isinstance(pywt.DiscreteContinuousWavelet(wavelet), pywt.Wavelet):
66 for mode in pywt.Modes.modes:
67 coeffs = pywt.dwtn(r, wavelet, mode=mode)
68 assert_allclose(pywt.idwtn(coeffs, wavelet, mode=mode),
69 r, rtol=1e-7, atol=1e-7)
70
71
72 def test_stride():
73 wavelet = pywt.Wavelet('haar')
74
75 for dtype in ('float32', 'float64'):
76 data = np.array([[0, 4, 1, 5, 1, 4],
77 [0, 5, 6, 3, 2, 1],
78 [2, 5, 19, 4, 19, 1]],
79 dtype=dtype)
80
81 for mode in pywt.Modes.modes:
82 expected = pywt.dwtn(data, wavelet)
83 strided = np.ones((3, 12), dtype=data.dtype)
84 strided[::-1, ::2] = data
85 strided_dwtn = pywt.dwtn(strided[::-1, ::2], wavelet)
86 for key in expected.keys():
87 assert_allclose(strided_dwtn[key], expected[key])
88
89
90 def test_byte_offset():
91 wavelet = pywt.Wavelet('haar')
92 for dtype in ('float32', 'float64'):
93 data = np.array([[0, 4, 1, 5, 1, 4],
94 [0, 5, 6, 3, 2, 1],
95 [2, 5, 19, 4, 19, 1]],
96 dtype=dtype)
97
98 for mode in pywt.Modes.modes:
99 expected = pywt.dwtn(data, wavelet)
100 padded = np.ones((3, 6), dtype=np.dtype({'data': (data.dtype, 0),
101 'pad': ('byte', data.dtype.itemsize)},
102 align=True))
103 padded[:] = data
104 padded_dwtn = pywt.dwtn(padded['data'], wavelet)
105 for key in expected.keys():
106 assert_allclose(padded_dwtn[key], expected[key])
107
108
109 def test_3D_reconstruct_complex():
110 # All dimensions even length so `take` does not need to be specified
111 data = np.array([
112 [[0, 4, 1, 5, 1, 4],
113 [0, 5, 26, 3, 2, 1],
114 [5, 8, 2, 33, 4, 9],
115 [2, 5, 19, 4, 19, 1]],
116 [[1, 5, 1, 2, 3, 4],
117 [7, 12, 6, 52, 7, 8],
118 [2, 12, 3, 52, 6, 8],
119 [5, 2, 6, 78, 12, 2]]])
120 data = data + 1j
121
122 wavelet = pywt.Wavelet('haar')
123 d = pywt.dwtn(data, wavelet)
124 # idwtn creates even-length shapes (2x dwtn size)
125 original_shape = tuple([slice(None, s) for s in data.shape])
126 assert_allclose(data, pywt.idwtn(d, wavelet)[original_shape],
127 rtol=1e-13, atol=1e-13)
128
129
130 def test_idwtn_idwt2():
131 data = np.array([
132 [0, 4, 1, 5, 1, 4],
133 [0, 5, 6, 3, 2, 1],
134 [2, 5, 19, 4, 19, 1]])
135
136 wavelet = pywt.Wavelet('haar')
137
138 LL, (HL, LH, HH) = pywt.dwt2(data, wavelet)
139 d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH}
140
141 for mode in pywt.Modes.modes:
142 assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet, mode=mode),
143 pywt.idwtn(d, wavelet, mode=mode),
144 rtol=1e-14, atol=1e-14)
145
146
147 def test_idwtn_idwt2_complex():
148 data = np.array([
149 [0, 4, 1, 5, 1, 4],
150 [0, 5, 6, 3, 2, 1],
151 [2, 5, 19, 4, 19, 1]])
152 data = data + 1j
153 wavelet = pywt.Wavelet('haar')
154
155 LL, (HL, LH, HH) = pywt.dwt2(data, wavelet)
156 d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH}
157
158 for mode in pywt.Modes.modes:
159 assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet, mode=mode),
160 pywt.idwtn(d, wavelet, mode=mode),
161 rtol=1e-14, atol=1e-14)
162
163
164 def test_idwtn_missing():
165 # Test to confirm missing data behave as zeroes
166 data = np.array([
167 [0, 4, 1, 5, 1, 4],
168 [0, 5, 6, 3, 2, 1],
169 [2, 5, 19, 4, 19, 1]])
170
171 wavelet = pywt.Wavelet('haar')
172
173 coefs = pywt.dwtn(data, wavelet)
174
175 # No point removing zero, or all
176 for num_missing in range(1, len(coefs)):
177 for missing in combinations(coefs.keys(), num_missing):
178 missing_coefs = coefs.copy()
179 for key in missing:
180 del missing_coefs[key]
181 LL = missing_coefs.get('aa', None)
182 HL = missing_coefs.get('da', None)
183 LH = missing_coefs.get('ad', None)
184 HH = missing_coefs.get('dd', None)
185
186 assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet),
187 pywt.idwtn(missing_coefs, 'haar'), atol=1e-15)
188
189
190 def test_idwtn_all_coeffs_None():
191 coefs = dict(aa=None, da=None, ad=None, dd=None)
192 assert_raises(ValueError, pywt.idwtn, coefs, 'haar')
193
194
195 def test_error_on_invalid_keys():
196 data = np.array([
197 [0, 4, 1, 5, 1, 4],
198 [0, 5, 6, 3, 2, 1],
199 [2, 5, 19, 4, 19, 1]])
200
201 wavelet = pywt.Wavelet('haar')
202
203 LL, (HL, LH, HH) = pywt.dwt2(data, wavelet)
204
205 # unexpected key
206 d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH, 'ff': LH}
207 assert_raises(ValueError, pywt.idwtn, d, wavelet)
208
209 # mismatched key lengths
210 d = {'a': LL, 'da': HL, 'ad': LH, 'dd': HH}
211 assert_raises(ValueError, pywt.idwtn, d, wavelet)
212
213
214 def test_error_mismatched_size():
215 data = np.array([
216 [0, 4, 1, 5, 1, 4],
217 [0, 5, 6, 3, 2, 1],
218 [2, 5, 19, 4, 19, 1]])
219
220 wavelet = pywt.Wavelet('haar')
221
222 LL, (HL, LH, HH) = pywt.dwt2(data, wavelet)
223
224 # Pass/fail depends on first element being shorter than remaining ones so
225 # set 3/4 to an incorrect size to maximize chances. Order of dict items
226 # is random so may not trigger on every test run. Dict is constructed
227 # inside idwtn function so no use using an OrderedDict here.
228 LL = LL[:, :-1]
229 LH = LH[:, :-1]
230 HH = HH[:, :-1]
231 d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH}
232
233 assert_raises(ValueError, pywt.idwtn, d, wavelet)
234
235
236 def test_dwt2_idwt2_dtypes():
237 wavelet = pywt.Wavelet('haar')
238 for dt_in, dt_out in zip(dtypes_in, dtypes_out):
239 x = np.ones((4, 4), dtype=dt_in)
240 errmsg = "wrong dtype returned for {0} input".format(dt_in)
241
242 cA, (cH, cV, cD) = pywt.dwt2(x, wavelet)
243 assert_(cA.dtype == cH.dtype == cV.dtype == cD.dtype,
244 "dwt2: " + errmsg)
245
246 x_roundtrip = pywt.idwt2((cA, (cH, cV, cD)), wavelet)
247 assert_(x_roundtrip.dtype == dt_out, "idwt2: " + errmsg)
248
249
250 def test_dwtn_axes():
251 data = np.array([[0, 1, 2, 3],
252 [1, 1, 1, 1],
253 [1, 4, 2, 8]])
254 data = data + 1j*data # test with complex data
255 coefs = pywt.dwtn(data, 'haar', axes=(1,))
256 expected_a = list(map(lambda x: pywt.dwt(x, 'haar')[0], data))
257 assert_equal(coefs['a'], expected_a)
258 expected_d = list(map(lambda x: pywt.dwt(x, 'haar')[1], data))
259 assert_equal(coefs['d'], expected_d)
260
261 coefs = pywt.dwtn(data, 'haar', axes=(1, 1))
262 expected_aa = list(map(lambda x: pywt.dwt(x, 'haar')[0], expected_a))
263 assert_equal(coefs['aa'], expected_aa)
264 expected_ad = list(map(lambda x: pywt.dwt(x, 'haar')[1], expected_a))
265 assert_equal(coefs['ad'], expected_ad)
266
267
268 def test_idwtn_axes():
269 data = np.array([[0, 1, 2, 3],
270 [1, 1, 1, 1],
271 [1, 4, 2, 8]])
272 data = data + 1j*data # test with complex data
273 coefs = pywt.dwtn(data, 'haar', axes=(1, 1))
274 assert_allclose(pywt.idwtn(coefs, 'haar', axes=(1, 1)), data, atol=1e-14)
275
276
277 def test_idwt2_none_coeffs():
278 data = np.array([[0, 1, 2, 3],
279 [1, 1, 1, 1],
280 [1, 4, 2, 8]])
281 data = data + 1j*data # test with complex data
282 cA, (cH, cV, cD) = pywt.dwt2(data, 'haar', axes=(1, 1))
283
284 # verify setting coefficients to None is the same as zeroing them
285 cD = np.zeros_like(cD)
286 result_zeros = pywt.idwt2((cA, (cH, cV, cD)), 'haar', axes=(1, 1))
287
288 cD = None
289 result_none = pywt.idwt2((cA, (cH, cV, cD)), 'haar', axes=(1, 1))
290
291 assert_equal(result_zeros, result_none)
292
293
294 def test_idwtn_none_coeffs():
295 data = np.array([[0, 1, 2, 3],
296 [1, 1, 1, 1],
297 [1, 4, 2, 8]])
298 data = data + 1j*data # test with complex data
299 coefs = pywt.dwtn(data, 'haar', axes=(1, 1))
300
301 # verify setting coefficients to None is the same as zeroing them
302 coefs['dd'] = np.zeros_like(coefs['dd'])
303 result_zeros = pywt.idwtn(coefs, 'haar', axes=(1, 1))
304
305 coefs['dd'] = None
306 result_none = pywt.idwtn(coefs, 'haar', axes=(1, 1))
307
308 assert_equal(result_zeros, result_none)
309
310
311 def test_idwt2_axes():
312 data = np.array([[0, 1, 2, 3],
313 [1, 1, 1, 1],
314 [1, 4, 2, 8]])
315 coefs = pywt.dwt2(data, 'haar', axes=(1, 1))
316 assert_allclose(pywt.idwt2(coefs, 'haar', axes=(1, 1)), data, atol=1e-14)
317
318 # too many axes
319 assert_raises(ValueError, pywt.idwt2, coefs, 'haar', axes=(0, 1, 1))
320
321
322 def test_idwt2_axes_subsets():
323 data = np.array(np.random.standard_normal((4, 4, 4)))
324 # test all combinations of 2 out of 3 axes transformed
325 for axes in combinations((0, 1, 2), 2):
326 coefs = pywt.dwt2(data, 'haar', axes=axes)
327 assert_allclose(pywt.idwt2(coefs, 'haar', axes=axes), data, atol=1e-14)
328
329
330 def test_idwtn_axes_subsets():
331 data = np.array(np.random.standard_normal((4, 4, 4, 4)))
332 # test all combinations of 3 out of 4 axes transformed
333 for axes in combinations((0, 1, 2, 3), 3):
334 coefs = pywt.dwtn(data, 'haar', axes=axes)
335 assert_allclose(pywt.idwtn(coefs, 'haar', axes=axes), data, atol=1e-14)
336
337
338 def test_negative_axes():
339 data = np.array([[0, 1, 2, 3],
340 [1, 1, 1, 1],
341 [1, 4, 2, 8]])
342 coefs1 = pywt.dwtn(data, 'haar', axes=(1, 1))
343 coefs2 = pywt.dwtn(data, 'haar', axes=(-1, -1))
344 assert_equal(coefs1, coefs2)
345
346 rec1 = pywt.idwtn(coefs1, 'haar', axes=(1, 1))
347 rec2 = pywt.idwtn(coefs1, 'haar', axes=(-1, -1))
348 assert_equal(rec1, rec2)
349
350
351 def test_dwtn_idwtn_dtypes():
352 wavelet = pywt.Wavelet('haar')
353 for dt_in, dt_out in zip(dtypes_in, dtypes_out):
354 x = np.ones((4, 4), dtype=dt_in)
355 errmsg = "wrong dtype returned for {0} input".format(dt_in)
356
357 coeffs = pywt.dwtn(x, wavelet)
358 for k, v in coeffs.items():
359 assert_(v.dtype == dt_out, "dwtn: " + errmsg)
360
361 x_roundtrip = pywt.idwtn(coeffs, wavelet)
362 assert_(x_roundtrip.dtype == dt_out, "idwtn: " + errmsg)
363
364
365 def test_idwtn_mixed_complex_dtype():
366 rstate = np.random.RandomState(0)
367 x = rstate.randn(8, 8, 8)
368 x = x + 1j*x
369 coeffs = pywt.dwtn(x, 'db2')
370
371 x_roundtrip = pywt.idwtn(coeffs, 'db2')
372 assert_allclose(x_roundtrip, x, rtol=1e-10)
373
374 # mismatched dtypes OK
375 coeffs['a' * x.ndim] = coeffs['a' * x.ndim].astype(np.complex64)
376 x_roundtrip2 = pywt.idwtn(coeffs, 'db2')
377 assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7)
378 assert_(x_roundtrip2.dtype == np.complex128)
379
380
381 def test_idwt2_size_mismatch_error():
382 LL = np.zeros((6, 6))
383 LH = HL = HH = np.zeros((5, 5))
384
385 assert_raises(ValueError, pywt.idwt2, (LL, (LH, HL, HH)), wavelet='haar')
386
387
388 def test_dwt2_dimension_error():
389 data = np.ones(16)
390 wavelet = pywt.Wavelet('haar')
391
392 # wrong number of input dimensions
393 assert_raises(ValueError, pywt.dwt2, data, wavelet)
394
395 # too many axes
396 data2 = np.ones((8, 8))
397 assert_raises(ValueError, pywt.dwt2, data2, wavelet, axes=(0, 1, 1))
398
399
400 def test_per_axis_wavelets_and_modes():
401 # tests separate wavelet and edge mode for each axis.
402 rstate = np.random.RandomState(1234)
403 data = rstate.randn(16, 16, 16)
404
405 # wavelet can be a string or wavelet object
406 wavelets = (pywt.Wavelet('haar'), 'sym2', 'db4')
407
408 # mode can be a string or a Modes enum
409 modes = ('symmetric', 'periodization',
410 pywt._extensions._pywt.Modes.reflect)
411
412 coefs = pywt.dwtn(data, wavelets, modes)
413 assert_allclose(pywt.idwtn(coefs, wavelets, modes), data, atol=1e-14)
414
415 coefs = pywt.dwtn(data, wavelets[:1], modes)
416 assert_allclose(pywt.idwtn(coefs, wavelets[:1], modes), data, atol=1e-14)
417
418 coefs = pywt.dwtn(data, wavelets, modes[:1])
419 assert_allclose(pywt.idwtn(coefs, wavelets, modes[:1]), data, atol=1e-14)
420
421 # length of wavelets or modes doesn't match the length of axes
422 assert_raises(ValueError, pywt.dwtn, data, wavelets[:2])
423 assert_raises(ValueError, pywt.dwtn, data, wavelets, mode=modes[:2])
424 assert_raises(ValueError, pywt.idwtn, coefs, wavelets[:2])
425 assert_raises(ValueError, pywt.idwtn, coefs, wavelets, mode=modes[:2])
426
427 # dwt2/idwt2 also support per-axis wavelets/modes
428 data2 = data[..., 0]
429 coefs2 = pywt.dwt2(data2, wavelets[:2], modes[:2])
430 assert_allclose(pywt.idwt2(coefs2, wavelets[:2], modes[:2]), data2,
431 atol=1e-14)
432
433
434 def test_error_on_continuous_wavelet():
435 # A ValueError is raised if a Continuous wavelet is selected
436 data = np.ones((16, 16))
437 for dec_fun, rec_fun in zip([pywt.dwt2, pywt.dwtn],
438 [pywt.idwt2, pywt.idwtn]):
439 for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]:
440 assert_raises(ValueError, dec_fun, data, wavelet=cwave)
441
442 c = dec_fun(data, 'db1')
443 assert_raises(ValueError, rec_fun, c, wavelet=cwave)