Debian Codegraph @

pywt/tests/test_matlab_compatibility_cwt.py

raw symbols SCIP
1 """
2 Test used to verify PyWavelets Continuous Wavelet Transform computation
3 accuracy against MathWorks Wavelet Toolbox.
4 """
5
6 from __future__ import division, print_function, absolute_import
7
8 import warnings
9 import numpy as np
10 import pytest
11 from numpy.testing import assert_
12
13 import pywt
14 from pywt._pytest import (uses_pymatbridge, uses_precomputed, size_set,
15 matlab_result_dict_cwt)
16
17 families = ('gaus', 'mexh', 'morl', 'cgau', 'shan', 'fbsp', 'cmor')
18 wavelets = sum([pywt.wavelist(name) for name in families], [])
19
20
21 def _get_data_sizes(w):
22 """ Return the sizes to test for wavelet w. """
23 if size_set == 'full':
24 data_sizes = list(range(100, 101)) + \
25 [100, 200, 500, 1000, 50000]
26 else:
27 data_sizes = (1000, 1000 + 1)
28 return data_sizes
29
30
31 def _get_scales(w):
32 """ Return the scales to test for wavelet w. """
33 if size_set == 'full':
34 scales = (1, np.arange(1, 3), np.arange(1, 4), np.arange(1, 5))
35 else:
36 scales = (1, np.arange(1, 3))
37 return scales
38
39
40 @uses_pymatbridge # skip this case if precomputed results are used instead
41 @pytest.mark.slow
42 def test_accuracy_pymatbridge_cwt():
43 Matlab = pytest.importorskip("pymatbridge.Matlab")
44 mlab = Matlab()
45 rstate = np.random.RandomState(1234)
46 # max RMSE (was 1.0e-10, is reduced to 5.0e-5 due to different coefficients)
47 epsilon = 1e-15
48 epsilon_psi = 1e-15
49 mlab.start()
50 try:
51 for wavelet in wavelets:
52 with warnings.catch_warnings():
53 warnings.simplefilter('ignore', FutureWarning)
54 w = pywt.ContinuousWavelet(wavelet)
55 if np.any((wavelet == np.array(['shan', 'cmor'])),axis=0):
56 mlab.set_variable('wavelet', wavelet+str(w.bandwidth_frequency)+'-'+str(w.center_frequency))
57 elif wavelet == 'fbsp':
58 mlab.set_variable('wavelet', wavelet+str(w.fbsp_order)+'-'+str(w.bandwidth_frequency)+'-'+str(w.center_frequency))
59 else:
60 mlab.set_variable('wavelet', wavelet)
61 mlab_code = ("psi = wavefun(wavelet,10)")
62 res = mlab.run_code(mlab_code)
63 psi = np.asarray(mlab.get_variable('psi'))
64 _check_accuracy_psi(w, psi, wavelet, epsilon_psi)
65 for N in _get_data_sizes(w):
66 data = rstate.randn(N)
67 mlab.set_variable('data', data)
68 for scales in _get_scales(w):
69 coefs = _compute_matlab_result(data, wavelet, scales, mlab)
70 _check_accuracy(data, w, scales, coefs, wavelet, epsilon)
71
72 finally:
73 mlab.stop()
74
75
76 @uses_precomputed # skip this case if pymatbridge + Matlab are being used
77 @pytest.mark.slow
78 def test_accuracy_precomputed_cwt():
79 # Keep this specific random seed to match the precomputed Matlab result.
80 rstate = np.random.RandomState(1234)
81 # has to be improved
82 epsilon = 2e-15
83 epsilon32 = 1e-5
84 epsilon_psi = 1e-15
85 for wavelet in wavelets:
86 with warnings.catch_warnings():
87 warnings.simplefilter('ignore', FutureWarning)
88 w = pywt.ContinuousWavelet(wavelet)
89 w32 = pywt.ContinuousWavelet(wavelet,dtype=np.float32)
90 psi = _load_matlab_result_psi(wavelet)
91 _check_accuracy_psi(w, psi, wavelet, epsilon_psi)
92
93 for N in _get_data_sizes(w):
94 data = rstate.randn(N)
95 data32 = data.astype(np.float32)
96 scales_count = 0
97 for scales in _get_scales(w):
98 scales_count += 1
99 coefs = _load_matlab_result(data, wavelet, scales_count)
100 _check_accuracy(data, w, scales, coefs, wavelet, epsilon)
101 _check_accuracy(data32, w32, scales, coefs, wavelet, epsilon32)
102
103
104 def _compute_matlab_result(data, wavelet, scales, mlab):
105 """ Compute the result using MATLAB.
106
107 This function assumes that the Matlab variables `wavelet` and `data` have
108 already been set externally.
109 """
110 mlab.set_variable('scales', scales)
111 mlab_code = ("coefs = cwt(data, scales, wavelet)")
112 res = mlab.run_code(mlab_code)
113 if not res['success']:
114 raise RuntimeError("Matlab failed to execute the provided code. "
115 "Check that the wavelet toolbox is installed.")
116 # need np.asarray because sometimes the output is a single float64
117 coefs = np.asarray(mlab.get_variable('coefs'))
118 return coefs
119
120
121 def _load_matlab_result(data, wavelet, scales):
122 """ Load the precomputed result.
123 """
124 N = len(data)
125 coefs_key = '_'.join([str(scales), wavelet, str(N), 'coefs'])
126 if (coefs_key not in matlab_result_dict_cwt):
127 raise KeyError(
128 "Precompted Matlab result not found for wavelet: "
129 "{0}, mode: {1}, size: {2}".format(wavelet, scales, N))
130 coefs = matlab_result_dict_cwt[coefs_key]
131 return coefs
132
133
134 def _load_matlab_result_psi(wavelet):
135 """ Load the precomputed result.
136 """
137 psi_key = '_'.join([wavelet, 'psi'])
138 if (psi_key not in matlab_result_dict_cwt):
139 raise KeyError(
140 "Precompted Matlab psi result not found for wavelet: "
141 "{0}}".format(wavelet))
142 psi = matlab_result_dict_cwt[psi_key]
143 return psi
144
145
146 def _check_accuracy(data, w, scales, coefs, wavelet, epsilon):
147 # PyWavelets result
148 coefs_pywt, freq = pywt.cwt(data, scales, w)
149
150 # coefs from Matlab are from R2012a which is missing the complex conjugate
151 # as shown in Eq. 2 of Torrence and Compo. We take the complex conjugate of
152 # the precomputed Matlab result to account for this.
153 coefs = np.conj(coefs)
154
155 # calculate error measures
156 err = coefs_pywt - coefs
157 rms = np.real(np.sqrt(np.mean(np.conj(err) * err)))
158
159 msg = ('[RMS > EPSILON] for Scale: %s, Wavelet: %s, '
160 'Length: %d, rms=%.3g' % (scales, wavelet, len(data), rms))
161 assert_(rms < epsilon, msg=msg)
162
163
164 def _check_accuracy_psi(w, psi, wavelet, epsilon):
165 # PyWavelets result
166 psi_pywt, x = w.wavefun(length=1024)
167
168 # calculate error measures
169 err = psi_pywt.flatten() - psi.flatten()
170 rms = np.real(np.sqrt(np.mean(np.conj(err) * err)))
171
172 msg = ('[RMS > EPSILON] for Wavelet: %s, '
173 'rms=%.3g' % (wavelet, rms))
174 assert_(rms < epsilon, msg=msg)