小波分解重构
function H=SE(WS)
load("650837_20161013152521.mat")
WS=double(WS);
vx=WS(1,:);
vy=WS(2,:);
vz=WS(3,:);
N=length(vx);
%用db3小波进行5层分解
[c1,l1]=wavedec(vx,5,'db3');
[c2,l2]=wavedec(vy,5,'db3');
[c3,l3]=wavedec(vz,5,'db3');
%构造第1-5层高频系数 matlab388
dx5=wrcoef('d',c1,l1,'db3',5);
dx4=wrcoef('d',c1,l1,'db3',4);
dx3=wrcoef('d',c1,l1,'db3',3);
dx2=wrcoef('d',c1,l1,'db3',2);
dx1=wrcoef('d',c1,l1,'db3',1);
dy5=wrcoef('d',c2,l2,'db3',5);
dy4=wrcoef('d',c2,l2,'db3',4);
dy3=wrcoef('d',c2,l2,'db3',3);
dy2=wrcoef('d',c2,l2,'db3',2);
dy1=wrcoef('d',c2,l2,'db3',1);
dz5=wrcoef('d',c3,l3,'db3',5);
dz4=wrcoef('d',c3,l3,'db3',4);
dz3=wrcoef('d',c3,l3,'db3',3);
dz2=wrcoef('d',c3,l3,'db3',2);
dz1=wrcoef('d',c3,l3,'db3',1);
%构造第5层高频细节系数
ax5=wrcoef('a',c1,l1,'db3',5);
ay5=wrcoef('a',c2,l2,'db3',5);
az5=wrcoef('a',c3,l3,'db3',5);
% %合并为一个矩阵
A=[ dx1' dx2' dx3' dx4' dx5' ax5' ];
B=[ dy1' dy2' dy3' dy4' dy5' ay5' ];
C=[ dz1' dz2' dz3' dz4' dz5' az5' ];
for t=1:6
for s=1:N
Tx(s)=A(s,t)^2 ;
Ty(s)=B(s,t)^2 ;
Tz(s)=C(s,t)^2 ;
end
ex(t)= sum(Tx);
ey(t)= sum(Ty);
ez(t)= sum(Tz);
end
%小波熵
Ex=sum(ex);
Ey=sum(ey);
Ez=sum(ez);
px=ex/Ex;
py=ey/Ey;
pz=ez/Ez;
for i=1:6
hx(i)=px(i)*log(px(i));
hy(i)=py(i)*log(py(i));
hz(i)=pz(i)*log(pz(i));
end
Hx=-sum(hx);
Hy=-sum(hy);
Hz=-sum(hz);
H = [Hx,Hy,Hz]
end
from numpy import *
import numpy as np
from wrcoef_1 import wrcoef,wavedec
import pandas as pd
from pandas import DataFrame, Series
import pywt
def get_matrix(x1):
signal = x1
C, L1 = wavedec(signal, wavelet='db3', level=5)
c = pywt.wavedec(signal, 'db3', level=5)
a, details = c[0], c[1:]
L = [d.size for d in details[1:]] + [signal.size, ]
for n in range(5):
a = pywt.upcoef('a', a, 'db3', level=1, take=L[n])
dx5 = wrcoef(C, L1, wavelet='db3', level=5)
dx4 = wrcoef(C, L1, wavelet='db3', level=4)
dx3 = wrcoef(C, L1, wavelet='db3', level=3)
dx2 = wrcoef(C, L1, wavelet='db3', level=2)
dx1 = wrcoef(C, L1, wavelet='db3', level=1)
A = np.vstack((dx1, dx2, dx3, dx4, dx5, a))
A = np.transpose(A)
return A
def SE(a1):
x1 = a1[0]
x2 = a1[1]
x3 = a1[2]
N = len(x1)
A = get_matrix(x1)
B = get_matrix(x2)
C = get_matrix(x3)
Tx, Ty, Tz = np.zeros((1, 2307)), np.zeros((1, 2307)), np.zeros((1, 2307))
ex, ey, ez = np.zeros(6), np.zeros(6), np.zeros(6)
for t in range(6):
for s in range(N):
Tx[0, s] = A[s][t] * A[s][t]
Ty[0, s] = B[s][t] * B[s][t]
Tz[0, s] = C[s][t] * C[s][t]
ex[t] = sum(Tx)
ey[t] = sum(Ty)
ez[t] = sum(Tz)
Ex = sum(ex)
Ey = sum(ey)
Ez = sum(ez)
px = ex / Ex
py = ey / Ey
pz = ez / Ez
hx, hy, hz = np.zeros(6), np.zeros(6), np.zeros(6)
for i in range(6):
hx[i] = px[i] * log(px[i])
hy[i] = py[i] * log(py[i])
hz[i] = pz[i] * log(pz[i])
Hx = -sum(hx)
Hy = -sum(hy)
Hz = -sum(hz)
H = [Hx, Hy, Hz]
return H
def exread(path):
df = pd.read_excel(path)
data1 = df.iloc[:, 0]
data2 = df.iloc[:, 1]
data3 = df.iloc[:, 2]
a1 = np.vstack((data1, data2, data3))
return a1
def write_excel_xls(path, Cx, Cy, Cz):
df = DataFrame(
{'id': Series(['650837_20161013152530']),
'num1': Series([Cx]),
'num2': Series([Cy]),
'num3': Series([Cz])})
df.to_excel(path, index=False)
if __name__ == '__main__':
a1 = exread('650837_20161013152521_11.xls')
H = SE(a1)
write_excel_xls('SE.xls', H[0], H[1], H[2])
import math
import numpy as np
import pywt
import pandas as pd
def wavedec(data, wavelet, mode='symmetric', level=1, axis=-1):
"""
Multiple level 1-D discrete fast wavelet decomposition
Calling Sequence
----------------
[C, L] = wavedec(data, wavelet, mode, level, axis)
[C, L] = wavedec(data, wavelet)
[C, L] = wavedec(data, 'sym3')
Parameters
----------
data: array_like
Input data
wavelet : Wavelet object or name string
Wavelet to use
mode : str, optional
Signal extension mode, see Modes (default: 'symmetric')
level : int, optional
Decomposition level (must be >= 0). Default is 1.
axis: int, optional
Axis over which to compute the DWT. If not given, the
last axis is used.
Returns
-------
C: list
Ordered list of flattened coefficients arrays (N=level):
C = [app. coef.(N)|det. coef.(N)|... |det. coef.(1)]
L: list
Ordered list of individual lengths of coefficients arrays.
L(1) = length of app. coef.(N)
L(i) = length of det. coef.(N-i+2) for i = 2,...,N+1
L(N+2) = length(X).
Description
-----------
wavedec can be used for multiple-level 1-D discrete fast wavelet
decomposition using a specific wavelet name or instance of the
Wavelet class instance.
The coefficient vector C contains the approximation coefficient at level N
and all detail coefficient from level 1 to N
The first entry of L is the length of the approximation coefficient,
then the length of the detail coefficients are stored and the last
value of L is the length of the signal vector.
The approximation coefficient can be extracted with C(1:L(1)).
The detail coefficients can be obtained with C(L(1):sum(L(1:2))),
C(sum(L(1:2)):sum(L(1:3))),.... until C(sum(L(1:length(L)-2)):sum(L(1:length(L)-1)))
The implementation of the function is based on pywt.wavedec
with the following minor changes:
- checking of the axis is dropped out
- checking of the maximum possible level is dropped out
(as for Matlab's implementation)
- returns format is modified to Matlab's internal format:
two separate lists of details coefficients and
corresponding lengths
Examples
--------
>>> C, L = wavedec([3, 7, 1, 1, -2, 5, 4, 6], 'sym3', level=2)
>>> C
array([ 7.38237875 5.36487594 8.83289608 2.21549896 11.10312807
-0.42770133 3.72423411 0.48210099 1.06367045 -5.0083641
-2.11206142 -2.64704675 -3.16825651 -0.67715519 0.56811154
2.70377533])
>>> L
array([5, 5, 6, 8])
"""
data = np.asarray(data)
if not isinstance(wavelet, pywt.Wavelet):
wavelet = pywt.Wavelet(wavelet)
coefs, lengths = [], []
lengths.append(len(data))
for i in range(level):
data, d = pywt.dwt(data, wavelet, mode, axis)
coefs.append(d)
lengths.append(len(d))
coefs.append(data)
lengths.append(len(data))
coefs.reverse()
lengths.reverse()
return np.concatenate(coefs).ravel(), lengths
def detcoef(coefs, lengths, levels=None):
"""
1-D detail coefficients extraction
Calling Sequence
----------------
D = detcoef(C, L)
D = detcoef(C, L, N)
D = detcoef(C, L, [1, 2, 3])
Parameters
----------
coefs: list
Ordered list of flattened coefficients arrays (N=level):
C = [app. coef.(N)|det. coef.(N)|... |det. coef.(1)]
lengths: list
Ordered list of individual lengths of coefficients arrays.
L(1) = length of app. coef.(N)
L(i) = length of det. coef.(N-i+2) for i = 2,...,N+1
L(N+2) = length(X).
levels : int or list
restruction level with N<=length(L)-2
Returns
----------
D : reconstructed detail coefficient
Description
-----------
detcoef is for extraction of detail coefficient at different level
after a multiple level decomposition. If levels is omitted,
the detail coefficients will extract at all levels.
The wavelet coefficients and lengths can be generated using wavedec.
Examples
--------
>>> x = range(100)
>>> w = pywt.Wavelet('sym3')
>>> C, L = wavedec(x, wavelet=w, level=5)
>>> D = detcoef(C, L, levels=len(L)-2)
"""
if not levels:
levels = range(len(lengths) - 2)
if not isinstance(levels, list):
levels = [levels]
first = np.cumsum(lengths) + 1
first = first[-3::-1]
last = first + lengths[-2:0:-1] - 1
x = []
for level in levels:
d = coefs[first[level - 1] - 1:last[level - 1]]
x.append(d)
if len(x) == 1:
x = x[0]
return x
def wrcoef(coefs, lengths, wavelet, level):
"""
Restruction from single branch from multiple level decomposition
Calling Sequence
----------------
X = wrcoef(C, L, wavelet, level)
Parameters
----------
# type='a' is not implemented.
# type : string
# approximation or detail, 'a' or 'd'.
coefs: list
Ordered list of flattened coefficients arrays (N=level):
C = [app. coef.(N)|det. coef.(N)|... |det. coef.(1)]
lengths: list
Ordered list of individual lengths of coefficients arrays.
L(1) = length of app. coef.(N)
L(i) = length of det. coef.(N-i+2) for i = 2,...,N+1
L(N+2) = length(X).
wavelet : Wavelet object or name string
Wavelet to use
level : int
restruction level with level<=length(L)-2
Returns
----------
X :
vector of reconstructed coefficients
Description
-----------
wrcoef is for reconstruction from single branch of multiple level
decomposition from 1-D wavelet coefficients.
The wavelet coefficients and lengths can be generated using wavedec.
Examples
--------
>>> x = range(100)
>>> w = pywt.Wavelet('sym3')
>>> C, L = wavedec(x, wavelet=w, level=5)
>>> X = wrcoef(C, L, wavelet=w, level=len(L)-2)
"""
def upsconv(x, f, s):
y_len = 2 * len(x) + 1
y = np.zeros(y_len)
y[1:y_len:2] = x
y = np.convolve(y, f, 'full')
sy = len(y)
d = (sy - s) / 2.0
y = y[int(math.floor(d)):(sy - int(math.ceil(d)))]
return y
if not isinstance(wavelet, pywt.Wavelet):
wavelet = pywt.Wavelet(wavelet)
data = detcoef(coefs, lengths, level)
idx = len(lengths) - level
data = upsconv(data, wavelet.rec_hi, lengths[idx])
for k in range(level-1):
data = upsconv(data, wavelet.rec_lo, lengths[idx + k + 1])
return data
def exread(path):
df = pd.read_excel(path, header=None)
data1 = df.iloc[:, 0]
data2 = df.iloc[:, 1]
data3 = df.iloc[:, 2]
a1 = np.vstack((data1, data2, data3))
return a1
if __name__ == '__main__':
WS = np.array(exread('.\\wsread.xls'))
X = WS[0]
signal = X
print('x=', signal)
C, L = wavedec(signal, wavelet='db3', level=5)
D = wrcoef(C, L, wavelet='db3', level=5)
print(D)