Debian Codegraph @

pywt/tests/test_matlab_compatibility.py

raw symbols SCIP
1 """
2 Test used to verify PyWavelets Discrete Wavelet Transform computation
3 accuracy against MathWorks Wavelet Toolbox.
4 """
5
6 from __future__ import division, print_function, absolute_import
7
8 import numpy as np
9 import pytest
10 from numpy.testing import assert_
11
12 import pywt
13 from pywt._pytest import (uses_pymatbridge, uses_precomputed, size_set)
14 from pywt._pytest import matlab_result_dict_dwt as matlab_result_dict
15
16 # list of mode names in pywt and matlab
17 modes = [('zero', 'zpd'),
18 ('constant', 'sp0'),
19 ('symmetric', 'sym'),
20 ('reflect', 'symw'),
21 ('periodic', 'ppd'),
22 ('smooth', 'sp1'),
23 ('periodization', 'per'),
24 # TODO: Now have implemented asymmetric modes too.
25 # Would be nice to update the Matlab data to test these as well.
26 ('antisymmetric', 'asym'),
27 ('antireflect', 'asymw'),
28 ]
29
30 families = ('db', 'sym', 'coif', 'bior', 'rbio')
31 wavelets = sum([pywt.wavelist(name) for name in families], [])
32
33
34 def _get_data_sizes(w):
35 """ Return the sizes to test for wavelet w. """
36 if size_set == 'full':
37 data_sizes = list(range(w.dec_len, 40)) + \
38 [100, 200, 500, 1000, 50000]
39 else:
40 data_sizes = (w.dec_len, w.dec_len + 1)
41 return data_sizes
42
43
44 @uses_pymatbridge
45 @pytest.mark.slow
46 def test_accuracy_pymatbridge():
47 Matlab = pytest.importorskip("pymatbridge.Matlab")
48 mlab = Matlab()
49
50 rstate = np.random.RandomState(1234)
51 # max RMSE (was 1.0e-10, is reduced to 5.0e-5 due to different coefficients)
52 epsilon = 5.0e-5
53 epsilon_pywt_coeffs = 1.0e-10
54 mlab.start()
55 try:
56 for wavelet in wavelets:
57 w = pywt.Wavelet(wavelet)
58 mlab.set_variable('wavelet', wavelet)
59 for N in _get_data_sizes(w):
60 data = rstate.randn(N)
61 mlab.set_variable('data', data)
62 for pmode, mmode in modes:
63 ma, md = _compute_matlab_result(data, wavelet, mmode, mlab)
64 _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon)
65 ma, md = _load_matlab_result_pywt_coeffs(data, wavelet, mmode)
66 _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon_pywt_coeffs)
67
68 finally:
69 mlab.stop()
70
71
72 @uses_precomputed
73 @pytest.mark.slow
74 def test_accuracy_precomputed():
75 # Keep this specific random seed to match the precomputed Matlab result.
76 rstate = np.random.RandomState(1234)
77 # max RMSE (was 1.0e-10, is reduced to 5.0e-5 due to different coefficients)
78 epsilon = 5.0e-5
79 epsilon_pywt_coeffs = 1.0e-10
80 for wavelet in wavelets:
81 w = pywt.Wavelet(wavelet)
82 for N in _get_data_sizes(w):
83 data = rstate.randn(N)
84 for pmode, mmode in modes:
85 ma, md = _load_matlab_result(data, wavelet, mmode)
86 _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon)
87 ma, md = _load_matlab_result_pywt_coeffs(data, wavelet, mmode)
88 _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon_pywt_coeffs)
89
90
91 def _compute_matlab_result(data, wavelet, mmode, mlab):
92 """ Compute the result using MATLAB.
93
94 This function assumes that the Matlab variables `wavelet` and `data` have
95 already been set externally.
96 """
97 if np.any((wavelet == np.array(['coif6', 'coif7', 'coif8', 'coif9', 'coif10', 'coif11', 'coif12', 'coif13', 'coif14', 'coif15', 'coif16', 'coif17'])),axis=0):
98 w = pywt.Wavelet(wavelet)
99 mlab.set_variable('Lo_D', w.dec_lo)
100 mlab.set_variable('Hi_D', w.dec_hi)
101 mlab_code = ("[ma, md] = dwt(data, Lo_D, Hi_D, 'mode', '%s');" % mmode)
102 else:
103 mlab_code = "[ma, md] = dwt(data, wavelet, 'mode', '%s');" % mmode
104 res = mlab.run_code(mlab_code)
105 if not res['success']:
106 raise RuntimeError("Matlab failed to execute the provided code. "
107 "Check that the wavelet toolbox is installed.")
108 # need np.asarray because sometimes the output is a single float64
109 ma = np.asarray(mlab.get_variable('ma'))
110 md = np.asarray(mlab.get_variable('md'))
111 return ma, md
112
113
114 def _load_matlab_result(data, wavelet, mmode):
115 """ Load the precomputed result.
116 """
117 N = len(data)
118 ma_key = '_'.join([mmode, wavelet, str(N), 'ma'])
119 md_key = '_'.join([mmode, wavelet, str(N), 'md'])
120 if (ma_key not in matlab_result_dict) or \
121 (md_key not in matlab_result_dict):
122 raise KeyError(
123 "Precompted Matlab result not found for wavelet: "
124 "{0}, mode: {1}, size: {2}".format(wavelet, mmode, N))
125 ma = matlab_result_dict[ma_key]
126 md = matlab_result_dict[md_key]
127 return ma, md
128
129
130 def _load_matlab_result_pywt_coeffs(data, wavelet, mmode):
131 """ Load the precomputed result.
132 """
133 N = len(data)
134 ma_key = '_'.join([mmode, wavelet, str(N), 'ma_pywtCoeffs'])
135 md_key = '_'.join([mmode, wavelet, str(N), 'md_pywtCoeffs'])
136 if (ma_key not in matlab_result_dict) or \
137 (md_key not in matlab_result_dict):
138 raise KeyError(
139 "Precompted Matlab result not found for wavelet: "
140 "{0}, mode: {1}, size: {2}".format(wavelet, mmode, N))
141 ma = matlab_result_dict[ma_key]
142 md = matlab_result_dict[md_key]
143 return ma, md
144
145
146 def _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon):
147 # PyWavelets result
148 pa, pd = pywt.dwt(data, w, pmode)
149
150 # calculate error measures
151 rms_a = np.sqrt(np.mean((pa - ma) ** 2))
152 rms_d = np.sqrt(np.mean((pd - md) ** 2))
153
154 msg = ('[RMS_A > EPSILON] for Mode: %s, Wavelet: %s, '
155 'Length: %d, rms=%.3g' % (pmode, wavelet, len(data), rms_a))
156 assert_(rms_a < epsilon, msg=msg)
157
158 msg = ('[RMS_D > EPSILON] for Mode: %s, Wavelet: %s, '
159 'Length: %d, rms=%.3g' % (pmode, wavelet, len(data), rms_d))
160 assert_(rms_d < epsilon, msg=msg)