Debian Codegraph @

pywt/tests/test_wp.py

raw symbols SCIP
1 #!/usr/bin/env python
2
3 import os
4 import pickle
5
6 import numpy as np
7 from numpy.testing import (assert_allclose, assert_, assert_raises,
8 assert_equal)
9
10 import pywt
11
12
13 def test_wavelet_packet_structure():
14 x = [1, 2, 3, 4, 5, 6, 7, 8]
15 wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
16
17 assert_(wp.data == [1, 2, 3, 4, 5, 6, 7, 8])
18 assert_(wp.path == '')
19 assert_(wp.level == 0)
20 assert_(wp['ad'].maxlevel == 3)
21
22
23 def test_traversing_wp_tree():
24 x = [1, 2, 3, 4, 5, 6, 7, 8]
25 wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
26
27 assert_(wp.maxlevel == 3)
28
29 # First level
30 assert_allclose(wp['a'].data, np.array([2.12132034356, 4.949747468306,
31 7.778174593052, 10.606601717798]),
32 rtol=1e-12)
33
34 # Second level
35 assert_allclose(wp['aa'].data, np.array([5., 13.]), rtol=1e-12)
36
37 # Third level
38 assert_allclose(wp['aaa'].data, np.array([12.727922061358]), rtol=1e-12)
39
40
41 def test_acess_path():
42 x = [1, 2, 3, 4, 5, 6, 7, 8]
43 wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
44
45 assert_(wp['a'].path == 'a')
46 assert_(wp['aa'].path == 'aa')
47 assert_(wp['aaa'].path == 'aaa')
48
49 # Maximum level reached:
50 assert_raises(IndexError, lambda: wp['aaaa'].path)
51
52 # Wrong path
53 assert_raises(ValueError, lambda: wp['ac'].path)
54
55
56 def test_access_node_attributes():
57 x = [1, 2, 3, 4, 5, 6, 7, 8]
58 wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
59
60 assert_allclose(wp['ad'].data, np.array([-2., -2.]), rtol=1e-12)
61 assert_(wp['ad'].path == 'ad')
62 assert_(wp['ad'].node_name == 'd')
63 assert_(wp['ad'].parent.path == 'a')
64 assert_(wp['ad'].level == 2)
65 assert_(wp['ad'].maxlevel == 3)
66 assert_(wp['ad'].mode == 'symmetric')
67
68 # tuple-based access is also supported
69 node = wp[('a', 'd')]
70 # can access a node's path as either a single string or in tuple form
71 assert_(node.path == 'ad')
72 assert_(node.path_tuple == ('a', 'd'))
73
74
75 def test_collecting_nodes():
76 x = [1, 2, 3, 4, 5, 6, 7, 8]
77 wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
78
79 # All nodes in natural order
80 assert_([node.path for node in wp.get_level(3, 'natural')] ==
81 ['aaa', 'aad', 'ada', 'add', 'daa', 'dad', 'dda', 'ddd'])
82
83 # and in frequency order.
84 assert_([node.path for node in wp.get_level(3, 'freq')] ==
85 ['aaa', 'aad', 'add', 'ada', 'dda', 'ddd', 'dad', 'daa'])
86
87 assert_raises(ValueError, wp.get_level, 3, 'invalid_order')
88
89
90 def test_reconstructing_data():
91 x = [1, 2, 3, 4, 5, 6, 7, 8]
92 wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
93
94 # Create another Wavelet Packet and feed it with some data.
95 new_wp = pywt.WaveletPacket(data=None, wavelet='db1', mode='symmetric')
96 new_wp['aa'] = wp['aa'].data
97 new_wp['ad'] = [-2., -2.]
98
99 # For convenience, :attr:`Node.data` gets automatically extracted
100 # from the :class:`Node` object:
101 new_wp['d'] = wp['d']
102
103 # Reconstruct data from aa, ad, and d packets.
104 assert_allclose(new_wp.reconstruct(update=False), x, rtol=1e-12)
105
106 # The node's :attr:`~Node.data` will not be updated
107 assert_(new_wp.data is None)
108
109 # When `update` is True:
110 assert_allclose(new_wp.reconstruct(update=True), x, rtol=1e-12)
111 assert_allclose(new_wp.data, np.arange(1, 9), rtol=1e-12)
112
113 assert_([n.path for n in new_wp.get_leaf_nodes(False)] ==
114 ['aa', 'ad', 'd'])
115 assert_([n.path for n in new_wp.get_leaf_nodes(True)] ==
116 ['aaa', 'aad', 'ada', 'add', 'daa', 'dad', 'dda', 'ddd'])
117
118
119 def test_removing_nodes():
120 x = [1, 2, 3, 4, 5, 6, 7, 8]
121 wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
122 wp.get_level(2)
123
124 dataleafs = [n.data for n in wp.get_leaf_nodes(False)]
125 expected = np.array([[5., 13.], [-2, -2], [-1, -1], [0, 0]])
126
127 for i in range(4):
128 assert_allclose(dataleafs[i], expected[i, :], atol=1e-12)
129
130 node = wp['ad']
131 del(wp['ad'])
132 dataleafs = [n.data for n in wp.get_leaf_nodes(False)]
133 expected = np.array([[5., 13.], [-1, -1], [0, 0]])
134
135 for i in range(3):
136 assert_allclose(dataleafs[i], expected[i, :], atol=1e-12)
137
138 wp.reconstruct()
139 # The reconstruction is:
140 assert_allclose(wp.reconstruct(),
141 np.array([2., 3., 2., 3., 6., 7., 6., 7.]), rtol=1e-12)
142
143 # Restore the data
144 wp['ad'].data = node.data
145
146 dataleafs = [n.data for n in wp.get_leaf_nodes(False)]
147 expected = np.array([[5., 13.], [-2, -2], [-1, -1], [0, 0]])
148
149 for i in range(4):
150 assert_allclose(dataleafs[i], expected[i, :], atol=1e-12)
151
152 assert_allclose(wp.reconstruct(), np.arange(1, 9), rtol=1e-12)
153
154
155 def test_wavelet_packet_dtypes():
156 rstate = np.random.RandomState(0)
157 N = 32
158 for dtype in [np.float32, np.float64, np.complex64, np.complex128]:
159 x = rstate.randn(N).astype(dtype)
160 if np.iscomplexobj(x):
161 x = x + 1j*np.random.randn(N).astype(x.real.dtype)
162 wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
163 # no unnecessary copy made
164 assert_(wp.data is x)
165
166 # assigning to a node should not change supported dtypes
167 wp['d'] = wp['d'].data
168 assert_equal(wp['d'].data.dtype, x.dtype)
169
170 # full decomposition
171 wp.get_level(wp.maxlevel)
172
173 # reconstruction from coefficients should preserve dtype
174 r = wp.reconstruct(False)
175 assert_equal(r.dtype, x.dtype)
176 assert_allclose(r, x, atol=1e-5, rtol=1e-5)
177
178 # first element of the tuple is the input dtype
179 # second element of the tuple is the transform dtype
180 dtype_pairs = [(np.uint8, np.float64),
181 (np.intp, np.float64), ]
182 if hasattr(np, "complex256"):
183 dtype_pairs += [(np.complex256, np.complex128), ]
184 if hasattr(np, "half"):
185 dtype_pairs += [(np.half, np.float32), ]
186 for (dtype, transform_dtype) in dtype_pairs:
187 x = np.arange(N, dtype=dtype)
188 wp = pywt.WaveletPacket(x, wavelet='db1', mode='symmetric')
189
190 # no unnecessary copy made of top-level data
191 assert_(wp.data is x)
192
193 # full decomposition
194 wp.get_level(wp.maxlevel)
195
196 # reconstructed data will have modified dtype
197 r = wp.reconstruct(False)
198 assert_equal(r.dtype, transform_dtype)
199 assert_allclose(r, x.astype(transform_dtype), atol=1e-5, rtol=1e-5)
200
201
202 def test_db3_roundtrip():
203 original = np.arange(512)
204 wp = pywt.WaveletPacket(data=original, wavelet='db3', mode='smooth',
205 maxlevel=3)
206 r = wp.reconstruct()
207 assert_allclose(original, r, atol=1e-12, rtol=1e-12)
208
209
210 def test_wavelet_packet_axis():
211 rstate = np.random.RandomState(0)
212 shape = (32, 16)
213 x = rstate.standard_normal(shape)
214 for axis in [0, 1, -1]:
215 wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric',
216 axis=axis)
217
218 # partial decomposition
219 nodes = wp.get_level(2)
220 # size along the transformed axis has changed
221 for ax2 in range(x.ndim):
222 if ax2 == (axis % x.ndim):
223 nodes[0].data.shape[ax2] < x.shape[ax2]
224 else:
225 nodes[0].data.shape[ax2] == x.shape[ax2]
226
227 # recontsruction from coefficients should preserve dtype
228 r = wp.reconstruct(False)
229 assert_equal(r.dtype, x.dtype)
230 assert_allclose(r, x, atol=1e-12, rtol=1e-12)
231
232 # ValueError if axis is out of range
233 assert_raises(ValueError, pywt.WaveletPacket, data=x, wavelet='db1',
234 axis=x.ndim)
235
236
237 def test_wavelet_packet_pickle(tmpdir):
238 packet = pywt.WaveletPacket(np.arange(16), 'sym4')
239 filename = os.path.join(tmpdir, 'wp.pickle')
240 with open(filename, 'wb') as f:
241 pickle.dump(packet, f)
242 with open(filename, 'rb') as f:
243 packet2 = pickle.load(f)
244 assert isinstance(packet2, pywt.WaveletPacket)