-
Notifications
You must be signed in to change notification settings - Fork 5
/
_functions.py
261 lines (195 loc) · 7.59 KB
/
_functions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# Copyright (c) 2006-2012 Filip Wasilewski <http://en.ig.ma/>
# Copyright (c) 2012-2016 The PyWavelets Developers
# <https://github.com/PyWavelets/pywt>
# See COPYING for license details.
"""
Other wavelet related functions.
"""
from __future__ import division, print_function, absolute_import
import warnings
import numpy as np
from numpy.fft import fft
from ._extensions._pywt import DiscreteContinuousWavelet, Wavelet, ContinuousWavelet
__all__ = ["integrate_wavelet", "central_frequency", "scale2frequency", "qmf",
"orthogonal_filter_bank",
"intwave", "centrfrq", "scal2frq", "orthfilt"]
_DEPRECATION_MSG = ("`{old}` has been renamed to `{new}` and will "
"be removed in a future version of pywt.")
def trim_wavelet(x, psi, tol=1e-2):
"""
Adjustment to the original pywt library. It trims the wavelet function to be from -1 to 1.
:param x: x
:param psi: psi(x)
:param tol: allowed maximal absolute value of psi(-1) and psi(1).
:return: trimmed wavelet: x, psi(x)
"""
if len(x) != len(psi):
raise ValueError('Lengths do not match: {}, {}'.format(len(x), len(psi)))
l = np.argmax(np.abs(psi)>tol)
r = len(x) - np.argmax(np.abs(psi[::-1])>tol) - 1
x = x[l:r]
psi = psi[l:r]
x = x / x[-1]
return x, psi
def _integrate(arr, step):
integral = np.cumsum(arr)
integral *= step
return integral
def intwave(*args, **kwargs):
msg = _DEPRECATION_MSG.format(old='intwave', new='integrate_wavelet')
warnings.warn(msg, DeprecationWarning)
return integrate_wavelet(*args, **kwargs)
def centrfrq(*args, **kwargs):
msg = _DEPRECATION_MSG.format(old='centrfrq', new='central_frequency')
warnings.warn(msg, DeprecationWarning)
return central_frequency(*args, **kwargs)
def scal2frq(*args, **kwargs):
msg = _DEPRECATION_MSG.format(old='scal2frq', new='scale2frequency')
warnings.warn(msg, DeprecationWarning)
return scale2frequency(*args, **kwargs)
def orthfilt(*args, **kwargs):
msg = _DEPRECATION_MSG.format(old='orthfilt', new='orthogonal_filter_bank')
warnings.warn(msg, DeprecationWarning)
return orthogonal_filter_bank(*args, **kwargs)
def integrate_wavelet(wavelet, precision=8):
"""
Integrate `psi` wavelet function from -Inf to x using the rectangle
integration method.
Parameters
----------
wavelet : Wavelet instance or str
Wavelet to integrate. If a string, should be the name of a wavelet.
precision : int, optional
Precision that will be used for wavelet function
approximation computed with the wavefun(level=precision)
Wavelet's method (default: 8).
Returns
-------
[int_psi, x] :
for orthogonal wavelets
[int_psi_d, int_psi_r, x] :
for other wavelets
Examples
--------
>>> from pywt import Wavelet, integrate_wavelet
>>> wavelet1 = Wavelet('db2')
>>> [int_psi, x] = integrate_wavelet(wavelet1, precision=5)
>>> wavelet2 = Wavelet('bior1.3')
>>> [int_psi_d, int_psi_r, x] = integrate_wavelet(wavelet2, precision=5)
"""
# FIXME: this function should really use scipy.integrate.quad
if type(wavelet) in (tuple, list):
msg = ("Integration of a general signal is deprecated "
"and will be removed in a future version of pywt.")
warnings.warn(msg, DeprecationWarning)
elif not isinstance(wavelet, (Wavelet, ContinuousWavelet)):
wavelet = DiscreteContinuousWavelet(wavelet)
if type(wavelet) in (tuple, list):
psi, x = np.asarray(wavelet[0]), np.asarray(wavelet[1])
step = x[1] - x[0]
return _integrate(psi, step), x
functions_approximations = wavelet.wavefun(precision)
if len(functions_approximations) == 2: # continuous wavelet
psi, x = functions_approximations
# ############################ I added this Code: ############################
x, psi = trim_wavelet(x, psi)
# ############################ Up to here ####################################
step = x[1] - x[0]
return _integrate(psi, step), x
elif len(functions_approximations) == 3: # orthogonal wavelet
phi, psi, x = functions_approximations
step = x[1] - x[0]
return _integrate(psi, step), x
else: # biorthogonal wavelet
phi_d, psi_d, phi_r, psi_r, x = functions_approximations
step = x[1] - x[0]
return _integrate(psi_d, step), _integrate(psi_r, step), x
def central_frequency(wavelet, precision=8):
"""
Computes the central frequency of the `psi` wavelet function.
Parameters
----------
wavelet : Wavelet instance, str or tuple
Wavelet to integrate. If a string, should be the name of a wavelet.
precision : int, optional
Precision that will be used for wavelet function
approximation computed with the wavefun(level=precision)
Wavelet's method (default: 8).
Returns
-------
scalar
"""
if not isinstance(wavelet, (Wavelet, ContinuousWavelet)):
wavelet = DiscreteContinuousWavelet(wavelet)
functions_approximations = wavelet.wavefun(precision)
if len(functions_approximations) == 2:
psi, x = functions_approximations
else:
# (psi, x) for (phi, psi, x)
# (psi_d, x) for (phi_d, psi_d, phi_r, psi_r, x)
psi, x = functions_approximations[1], functions_approximations[-1]
domain = float(x[-1] - x[0])
assert domain > 0
index = np.argmax(abs(fft(psi)[1:])) + 2
if index > len(psi) / 2:
index = len(psi) - index + 2
return 1.0 / (domain / (index - 1))
def scale2frequency(wavelet, scale, precision=8):
"""
Parameters
----------
wavelet : Wavelet instance or str
Wavelet to integrate. If a string, should be the name of a wavelet.
scale : scalar
precision : int, optional
Precision that will be used for wavelet function approximation computed
with ``wavelet.wavefun(level=precision)``. Default is 8.
Returns
-------
freq : scalar
"""
return central_frequency(wavelet, precision=precision) / scale
def qmf(filt):
"""
Returns the Quadrature Mirror Filter(QMF).
The magnitude response of QMF is mirror image about `pi/2` of that of the
input filter.
Parameters
----------
filt : array_like
Input filter for which QMF needs to be computed.
Returns
-------
qm_filter : ndarray
Quadrature mirror of the input filter.
"""
qm_filter = np.array(filt)[::-1]
qm_filter[1::2] = -qm_filter[1::2]
return qm_filter
def orthogonal_filter_bank(scaling_filter):
"""
Returns the orthogonal filter bank.
The orthogonal filter bank consists of the HPFs and LPFs at
decomposition and reconstruction stage for the input scaling filter.
Parameters
----------
scaling_filter : array_like
Input scaling filter (father wavelet).
Returns
-------
orth_filt_bank : tuple of 4 ndarrays
The orthogonal filter bank of the input scaling filter in the order :
1] Decomposition LPF
2] Decomposition HPF
3] Reconstruction LPF
4] Reconstruction HPF
"""
if not (len(scaling_filter) % 2 == 0):
raise ValueError("`scaling_filter` length has to be even.")
scaling_filter = np.asarray(scaling_filter, dtype=np.float64)
rec_lo = np.sqrt(2) * scaling_filter / np.sum(scaling_filter)
dec_lo = rec_lo[::-1]
rec_hi = qmf(rec_lo)
dec_hi = rec_hi[::-1]
orth_filt_bank = (dec_lo, dec_hi, rec_lo, rec_hi)
return orth_filt_bank