def test_upcoef_reconstruct(): data = np.arange(3) a = pywt.downcoef("a", data, "haar") d = pywt.downcoef("d", data, "haar") rec = pywt.upcoef("a", a, "haar", take=3) + pywt.upcoef("d", d, "haar", take=3) assert_allclose(rec, data)
def wavelet_dec(self, wavelet='db1', analyze_level=3): sound = self.org_sound coeffs = pywt.wavedec(sound, wavelet, level=analyze_level) coef_a = coeffs[0] coef_d = coeffs[1:] approx_array = pywt.upcoef('a', coef_a, wavelet, level=analyze_level) approx_array = [approx_array] detail_array = list() for ii in range(analyze_level): detail_array.append( pywt.upcoef('d', coef_d[ii], wavelet, level=(analyze_level - ii))) self.approx_array = approx_array self.detail_array = detail_array self.wave_mode = 'wavelet_dec' self.level = analyze_level approx = ['a' + str(self.level)] detail = ['d' + str(self.level - ii) \ for ii in np.arange(self.level)] col_name = approx + detail self.col_name = col_name return approx_array, detail_array
def wavelet_tree(self, wavelet='db1', analyze_level=6): sound = self.org_sound # 进行小波包分解 wp = pywt.WaveletPacket(data=sound, wavelet=wavelet, mode='sym') # 获取小波包分解树的各个节点名称 node_names = [ node.path for node in wp.get_level(analyze_level, 'natural') ] # 获取 概要部分节点名称 和 细节部分节点名称 node_names_approx = node_names[:(2**analyze_level // 2)] node_names_detail = node_names[(2**analyze_level // 2):] # 分别获取 概要部分的信号 和 细节部分的信号 approx_array = [pywt.upcoef('a', wp[node].data, wavelet, level=analyze_level) \ for node in node_names_approx] detail_array = [pywt.upcoef('d', wp[node].data, wavelet, level=analyze_level) \ for node in node_names_detail] self.approx_array = approx_array self.detail_array = detail_array self.wave_mode = 'wavelet_tree' self.level = analyze_level self.col_name = [node.path for node in \ wp.get_level(analyze_level, 'natural')] return approx_array, detail_array
def py_wt(str, x, y): signal = np.array(df.iloc[:, x:y]).reshape(1, -1) signal_wt = pywt.wavedec(signal, 'db5', level=3) signal_cA3, signal_cD3, signal_cD2, signal_cD1 = signal_wt signal_cA3 = np.array(signal_cA3).flatten() signal_cD3 = np.array(signal_cD3).flatten() signal_cD2 = np.array(signal_cD2).flatten() signal_cD1 = np.array(signal_cD1).flatten() signal_cA3_ = pywt.upcoef('a', signal_cA3, 'db5', level=3, take=311) signal_cD1_ = pywt.upcoef('d', signal_cD1, 'db5', level=1, take=311) signal_cD2_ = pywt.upcoef('d', signal_cD2, 'db5', level=2, take=311) signal_cD3_ = pywt.upcoef('d', signal_cD3, 'db5', level=3, take=311) signal_cA3_ = signal_cA3_.tolist() signal_cD1_ = signal_cD1_.tolist() signal_cD2_ = signal_cD2_.tolist() signal_cD3_ = signal_cD3_.tolist() print("signal_cA3:") print(signal_cA3) df_signal = pd.DataFrame({ str + "_cA3": list(signal_cA3_), str + "_cD3": list(signal_cD3_), str + "_cD2": list(signal_cD2_), str + "_cD1": list(signal_cD1_), }) print("df_signal") print(df_signal) return df_signal
def test_upcoef_reconstruct(): data = np.arange(3) a = pywt.downcoef('a', data, 'haar') d = pywt.downcoef('d', data, 'haar') rec = (pywt.upcoef('a', a, 'haar', take=3) + pywt.upcoef('d', d, 'haar', take=3)) assert_allclose(rec, data)
def test_upcoef_complex(): rstate = np.random.RandomState(1234) r = rstate.randn(4) + 1j * rstate.randn(4) nlevels = 3 a = pywt.upcoef('a', r, 'haar', level=nlevels) a_ref = pywt.upcoef('a', r.real, 'haar', level=nlevels) a_ref = a_ref + 1j * pywt.upcoef('a', r.imag, 'haar', level=nlevels) assert_allclose(a, a_ref)
def test_upcoef_complex(): rstate = np.random.RandomState(1234) r = rstate.randn(4) + 1j*rstate.randn(4) nlevels = 3 a = pywt.upcoef('a', r, 'haar', level=nlevels) a_ref = pywt.upcoef('a', r.real, 'haar', level=nlevels) a_ref = a_ref + 1j*pywt.upcoef('a', r.imag, 'haar', level=nlevels) assert_allclose(a, a_ref)
def test_upcoef_multilevel(): r = np.random.randn(4) nlevels = 3 # calling with level=1 nlevels times a1 = r.copy() for i in range(nlevels): a1 = pywt.upcoef('a', a1, 'haar', level=1) # call with level=nlevels once a3 = pywt.upcoef('a', r, 'haar', level=3) assert_allclose(a1, a3)
def wrcoef(X, coef_type, coeffs, wavename, level): N = np.array(X).size a, ds = coeffs[0], list(reversed(coeffs[1:])) if coef_type =='a': return pywt.upcoef('a', a, wavename, level=level)[:N] elif coef_type == 'd': return pywt.upcoef('d', ds[level-1], wavename, level=level)[:N] else: raise ValueError("Invalid coefficient type: {}".format(coef_type))
def wavelet_decomposition(y, wavelet_mother="db8", level_wt=3): w = pywt.Wavelet(wavelet_mother) coeffs = {} wd = {} coeffs['cA' + str(level_wt)] = pywt.downcoef('a', y, w, mode='sym', level=level_wt) wd['cA' + str(level_wt)] = pywt.upcoef('a', coeffs['cA' + str(level_wt)], w, level=level_wt, take=len(y)) for i in range(level_wt, 0, -1): coeffs['cD' + str(i)] = pywt.downcoef('d', y, w, mode='sym', level=i) wd['cD' + str(i)] = pywt.upcoef('d', coeffs['cD' + str(i)], w, level=i, take=len(y)) return (w ,wd, coeffs)
def test_upcoef_docstring(): data = [1, 2, 3, 4, 5, 6] (cA, cD) = pywt.dwt(data, 'db2', 'smooth') rec = pywt.upcoef('a', cA, 'db2') + pywt.upcoef('d', cD, 'db2') expect = [-0.25, -0.4330127, 1., 2., 3., 4., 5., 6., 1.78589838, -1.03108891] assert_allclose(rec, expect) n = len(data) rec = (pywt.upcoef('a', cA, 'db2', take=n) + pywt.upcoef('d', cD, 'db2', take=n)) assert_allclose(rec, data)
def test_upcoef_multilevel(): rstate = np.random.RandomState(1234) r = rstate.randn(4) nlevels = 3 # calling with level=1 nlevels times a1 = r.copy() for i in range(nlevels): a1 = pywt.upcoef("a", a1, "haar", level=1) # call with level=nlevels once a3 = pywt.upcoef("a", r, "haar", level=nlevels) assert_allclose(a1, a3)
def feature_extraction(self, blocks): print 'Feature extraction' result = {"features": [], "tags": []} i = 0 n = len(blocks) level = 4 wavelet = 'db4' for block in blocks: feature = [] electrodes = [block.f3, block.f4, block.af3, block.af4] for electrode in electrodes: #Se obtienen las caracteristicas en el dominio del tiempo, media y desviacion estandar. feature.append(np.mean(electrode)) feature.append(np.std(electrode)) size = len(electrode) #Se aplica la transformada wavelet, para la separacion de las bandas de frecuencia. wavelet_result = pywt.wavedec(electrode, wavelet='db4', level=level) alpha = pywt.upcoef('d', wavelet_result[2], wavelet='db4', level=3, take=size) beta = pywt.upcoef('d', wavelet_result[3], wavelet='db4', level=2, take=size) gamma = pywt.upcoef('d', wavelet_result[4], wavelet='db4', level=1, take=size) #Se obtienen las caracteristicas en el dominio de la frecuencia, media y desviacion estandar. #ALPHA feature.append(np.mean(self.transf(alpha))) feature.append(np.std(self.transf(alpha))) #BETA feature.append(np.mean(self.transf(beta))) feature.append(np.std(self.transf(beta))) #GAMMA feature.append(np.mean(self.transf(gamma))) feature.append(np.std(self.transf(gamma))) result['features'].append(feature) result['tags'].append(block.tag) return result
def __dwt(X): m, n = X.shape for i, x in enumerate(X): ca, cd = pywt.dwt(x, 'db1') tmp_a = pywt.upcoef('a', ca, 'db1', 1, n) X[i, :] = tmp_a return X
def training(self, file_data="user"): raw = RawData(file_data) blocks = raw.get_blocks_data() block = self.get_block(blocks, 'SAD') block_happy = self.get_block(blocks, 'HAPPY') block_neutral = self.get_block(blocks, 'NEUTRAL') #Definicion de los parametros para la aplicacion de la tranformada wavelet level = 4 wavelet = 'db4' sensors = [raw.f3, raw.f4, raw.af3, raw.af4] for i in range(4): n = len(sensors[i]) #Aplicacion de la transformada wavelet. cA4, cD4, cD3, cD2, cD1 = pywt.wavedec(sensors[i], wavelet=wavelet, level=level) #Extraccion de las 5 bandas de frecuencia. delta = pywt.upcoef('a', cA4, wavelet=wavelet, level=level, take=n) theta = pywt.upcoef('d', cD4, wavelet=wavelet, level=level, take=n) alpha = pywt.upcoef('d', cD3, wavelet=wavelet, level=3, take=n) beta = pywt.upcoef('d', cD2, wavelet=wavelet, level=2, take=n) gamma = pywt.upcoef('d', cD1, wavelet=wavelet, level=1, take=n) #Despligue de la grafica luego de la aplicacion de la transformada plt.figure(i, figsize=(20, 10)) plt.subplot(511) plt.plot(self.transf(delta)) plt.ylabel("delta") plt.subplot(512) plt.plot(self.transf(theta)) plt.ylabel("theta") plt.subplot(513) plt.plot(self.transf(alpha)) plt.ylabel("alpha") plt.subplot(514) plt.plot(self.transf(beta)) plt.ylabel("beta") plt.subplot(515) plt.plot(self.transf(gamma)) plt.ylabel("gamma") plt.savefig('../../imagenes/F' + str(i + 1) + 'ANEXOS_' + user + '.png') plt.show()
def plotWavelet(self, wavelet, level): coeffs = pywt.wavedec(self.y, wavelet, level=level) self.yWavelet = pywt.upcoef('a', coeffs[0], wavelet, level=level, take=len(self.y)) name = '{}, level:{}'.format(wavelet, str(level)) plt.plot(self.x, self.yWavelet, label=name)
def mydwt(y): """離散ウェーブレット分解 """ ca, cd = pywt.dwt(y.values, 'db1') n = len(y) columns = ['dwt_approx', 'dwt_detail'] y_dwt = pd.DataFrame(np.zeros([n,len(columns)]), columns=columns, index=y.index) y_dwt['dwt_approx'] = pywt.upcoef('a', ca, 'db1') y_dwt['dwt_detail'] = pywt.upcoef('d', cd, 'db1') #y_dwt.columns = [columns[0] + '_' + columns[1] for i in range(len(columns))] #feature_labels = [[y.name, columns[i]] for i in range(len(columns))] feature_labels = [[str(y.name), columns[i]] for i in range(len(columns))] y_dwt.columns = [str(y.name) + '_' + columns[i] for i in range(len(columns))] return y_dwt, feature_labels
def reconstruct_without_approx(xs, labels, level, fig=None): # reconstruct rs = [pywt.upcoef('d', x, 'db4', level=level) for x in xs] # generate plot if fig is None: fig = plt.figure() for i, x in enumerate(xs): plt.plot((np.abs(x))**2, label="Power of reconstructed signal ({})".format(labels[i])) plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) return rs, fig
def py_wt(str, x, y): signal = np.array(df.iloc[:, x:y]).reshape(1, -1) signal_wt = pywt.wavedec(signal, 'db5', level=3) signal_cA3, signal_cD3, signal_cD2, signal_cD1 = signal_wt signal_cA3 = np.array(signal_cA3).flatten() signal_cD3 = np.array(signal_cD3).flatten() signal_cD2 = np.array(signal_cD2).flatten() signal_cD1 = np.array(signal_cD1).flatten() signal_cA3_ = pywt.upcoef('a', signal_cA3, 'db5', level=3, take=311) signal_cD1_ = pywt.upcoef('d', signal_cD1, 'db5', level=1, take=311) signal_cD2_ = pywt.upcoef('d', signal_cD2, 'db5', level=2, take=311) signal_cD3_ = pywt.upcoef('d', signal_cD3, 'db5', level=3, take=311) signal_cA3_ = signal_cA3_.tolist() signal_cD1_ = signal_cD1_.tolist() signal_cD2_ = signal_cD2_.tolist() signal_cD3_ = signal_cD3_.tolist() return signal_cA3_,signal_cD3_,signal_cD2_,signal_cD1_
def next_lvl(self) -> None: i = self.start_lvl - self.curr_lvl self.cur_cA = self.cur_cA + self.cD[i] self.cur_cA = pywt.upcoef('a', self.cur_cA, self.filter_type, take=len(self.cD[i + 1])) self.curr_lvl -= 1 self.recunstruct = 2**self.curr_lvl self.k *= 2 return
def wavelet_transform(wave, wavelet, level): # Wavelet Transform wavelet = pywt.Wavelet(wavelet) coeffs = pywt.wavedec(wave, wavelet=wavelet, level=level) details_reconstructed = np.zeros(len(wave)) for i in range(level): details_reconstructed = np.vstack((details_reconstructed, pywt.upcoef(part='d', coeffs=coeffs[i + 1], wavelet=wavelet, level=level - (i), take=len(wave)))) return details_reconstructed[1:]
def wavelet_packet_rec(X, wavelet, max_level=3): """Return the node wise reconstructions of a full wavelet decompositions. :param X: Array of size (n, d), where `d` is the number of different signals; each will be decomposed separately. :param wavelet: Wavelet to use; string will be passed on to PyWavelets. :param max_level: Maximum depth of the resulting packet tree. :returns: Array of size `(n, d * 2**3)`. """ res = [] for i in range(X.shape[1]): x = X[:, i] wp = pywt.WaveletPacket(x, wavelet, maxlevel=max_level) for node in wp.get_leaf_nodes(True): res.append(pywt.upcoef(node.path[-1], node.data, wavelet, node.level)) return np.concatenate([i[:, np.newaxis] for i in res], axis=1)
def get_feature_2(data): # fluc, seasonal_c, local_c logging.info('get feature v2') feature = np.empty((data.shape[0], 3 * config.x_dim), dtype=np.float) for i in range(config.x_dim): col = data[:, i] fluc = col.std() / col.mean() if col.mean() > 0 else col.std() diff = col[1440:] - col[:-1440] seasonal_c = diff.std() cA1, cD1 = pywt.dwt(col, 'db2') D1 = pywt.upcoef('d', cD1, 'db2', 1) local_c = D1.std() feature[:, i * 3] = [fluc] * len(data) feature[:, i * 3 + 1] = [seasonal_c] * len(data) feature[:, i * 3 + 2] = [local_c] * len(data) return feature
def ReconUsingUpcoef(signal, wname='db4', level=3): w = Wavelet(wname) X = signal #coeffs = wavedec(a, w, mode='symmetric', level=level, axis=-1) coeffs = [] for i in range(level): a, d = dwt(X, w, mode='symmetric', axis=-1) coeffs.append(d) coeffs.append(a) coeffs.reverse() ca = coeffs[0] n = len(X) return upcoef('a', ca, w, take=n, level=level)
def DwtRec(signal, wavelet, level): # 返回的是每一层的分量,即将原始信号进行了频带分解,时间长度与原始序列signal等长 # 每一层对应一行 CoeffsRev = [] Coeffs = DWT(signal, wavelet=wavelet, level=level) for row in range(level + 1): if row == 0: # 重构近似系数,即低频分量 leveltype = level part = 'a' else: # 重构细节系数,即高频分量 leveltype = level - row + 1 part = 'd' EachLevelRev = pywt.upcoef(part, Coeffs[row], wavelet=wavelet, level=leveltype, take=len(signal)) CoeffsRev.append(EachLevelRev) return np.array(CoeffsRev)
def wv_signal_decomprs(self, signal_df): """ Make a compression of the input signals with a discrete wavelet transform. """ signal_wv_list = [] # and decompress data effectively. take=self.original_signal_len for signal_name in self.signals_names: temp_wv_list = pywt.upcoef('a', signal_df[signal_name], self.wv_sel, level=self.wv_order).tolist() signal_wv_list.append(temp_wv_list) print("Signal length after decompression: {}".format( len(signal_wv_list[0]))) # Create and return the output dataframe with the compressed signals output_df = pd.DataFrame() for i, signal in enumerate(self.signals_names): output_df[signal] = \ self.correct_deco_len(self.original_signal_df[signal], signal_wv_list[i]) return output_df
# For the scaling function, we need to compute the inverse DWT with a delta # for the approximation coefficients. (All detail coefficients are set # to zero.) # EY : 20150703 note on using PyWavelets # to make a custom Wavelet, you need to specify lowpass and highpass decomposition filters and lowpass and highpass reconstruction filters for a Filter Bank # how do we get the lowpass and highpass decomposition filters from the highpass reconstruction filters? # see my note in my pdf/LaTeX writeup, note on Sec. 6.2. of Strang and Nguyen # the answer is to just reverse the order cf. http://www.pybytes.com/pywavelets/regression/wavelet.html c = f0[::-1] d = f1[::-1] dec_lo, dec_hi, rec_lo, rec_hi = np.hstack(c), np.hstack(d), np.hstack(f0), np.hstack(f1) filter_bank = [dec_lo, dec_hi, rec_lo, rec_hi ] DaubechiesWavelet = pywt.Wavelet(name="DaubechiesWavelet", filter_bank=filter_bank) y = pywt.upcoef('a', [1.,0.], DaubechiesWavelet, numlevels) phi = M*np.append(0, y[0:L]) # For the wavelet, we need to compute the inverse DWT with a delta for the # detail coefficients. (All approximation coefficients and all detail # coefficients at finer scales are set to zero.) y = pywt.upcoef('d', [1.,0.], DaubechiesWavelet, numlevels) # Inverse DWT w = M*np.append(0,y[0:L]) # Determine the time vector. t = np.vstack(np.array(range(L+1)))/M # Plot the results. plt.figure(1) plt.plot(t,phi,'-',label="Scaling function") plt.plot(t,w,'--',label="Wavelet")
import pywt #--信号data--- cA, cD1, cD2, cD3 = pywt.wavedec(data, 'haar', level=3) #分解 data = pywt.waverec([cA, cD1, cD2, cD3], 'haar') #重构 x1 = pywt.upcoef('a', cA, 'haar', level=3, take=N) #计算第3层尺度系数的信号,长度为N x2 = pywt.upcoef('d', cD1, 'haar', level=3, take=N) #计算第3层细节系数的信号,长度为N
def Beat_analysis_preproc(*args): nargin = len(args) if nargin == 0: print('pas d' 'entree correcte pour la location de l' 'onde R') return elif nargin == 1: signal = args[0] level_max_BLD = 8 wavelet_BLD = 'sym4' build_level_BLD = 8 level_max_DEN = 3 wavelet_DEN = 'sym4' elif nargin == 2: signal = args[0] level_max_BLD = args[1] wavelet_BLD = 'sym4' build_level_BLD = args[1] level_max_DEN = 3 wavelet_DEN = 'sym4' elif nargin == 3: signal = args[0] level_max_BLD = args[1] wavelet_BLD = args[2] build_level_BLD = args[1] level_max_DEN = 3 wavelet_DEN = 'sym4' elif nargin == 4: signal = args[0] level_max_BLD = args[1] wavelet_BLD = args[2] build_level_BLD = args[3] level_max_DEN = 3 wavelet_DEN = 'sym4' elif nargin == 5: signal = args[0] level_max_BLD = args[1] wavelet_BLD = args[2] build_level_BLD = args[3] level_max_DEN = args[4] wavelet_DEN = 'sym4' else: signal = args[0] level_max_BLD = args[1] wavelet_BLD = args[2] build_level_BLD = args[3] level_max_DEN = args[4] wavelet_DEN = args[5] varargout = list() if level_max_BLD: coeffs = pywt.wavedec(signal, wavelet_BLD, 'sym', level_max_BLD) baseline = pywt.upcoef('a', coeffs[0], 'sym4', 8, take=len(signal) + 6)[:int(len(signal))] signal_basrem = signal - baseline varargout.append(signal_basrem) varargout.append(baseline) else: signal_basrem = signal varargout.append(signal_basrem) varargout.append(np.zeros((len(signal)))) if level_max_DEN: deb = signal[0] sig_basrem_d1 = WDen.wden(signal_basrem - deb, 'sqtwolog', 'soft', 'sln', level_max_DEN, wavelet_DEN) + deb sig_basrem_d2 = WDen.wden(signal_basrem - deb, 'minimaxi', 'soft', 'sln', level_max_DEN, wavelet_DEN) + deb varargout.append(sig_basrem_d1) varargout.append(sig_basrem_d2) else: varargout.append(signal_basrem) varargout.append(signal_basrem) return varargout[0], varargout[1], varargout[2], varargout[3]
df_day_of_week = df.iloc[:, 7:8] df_holiday = df.iloc[:, 8:9] df_load = df.iloc[:, 9:10] printc("用db5小波进行yes_ave 3层分解") yes_ave = np.array(df.iloc[:, 1:2]).reshape(1, -1) # print(ML.shape) yes_ave_wt = pywt.wavedec(yes_ave, 'db5', level=3) yes_ave_cA3, yes_ave_cD3, yes_ave_cD2, yes_ave_cD1 = yes_ave_wt yes_ave_cA3 = np.array(yes_ave_cA3).flatten() yes_ave_cD3 = np.array(yes_ave_cD3).flatten() yes_ave_cD2 = np.array(yes_ave_cD2).flatten() yes_ave_cD1 = np.array(yes_ave_cD1).flatten() yes_ave_cA3_ = pywt.upcoef('a', yes_ave_cA3, 'db5', level=3, take=311) yes_ave_cD1_ = pywt.upcoef('d', yes_ave_cD1, 'db5', level=1, take=311) yes_ave_cD2_ = pywt.upcoef('d', yes_ave_cD2, 'db5', level=2, take=311) yes_ave_cD3_ = pywt.upcoef('d', yes_ave_cD3, 'db5', level=3, take=311) yes_ave_cA3_ = yes_ave_cA3_.tolist() yes_ave_cD1_ = yes_ave_cD1_.tolist() yes_ave_cD2_ = yes_ave_cD2_.tolist() yes_ave_cD3_ = yes_ave_cD3_.tolist() print(yes_ave_cA3) printc("用db5小波进行yes_load 3层分解") yes_load = np.array(df.iloc[:, 2:3]).reshape(1, -1) # print(ML.shape) yes_load_wt = pywt.wavedec(yes_load, 'db5', level=3)
# to zero.) # EY : 20150703 note on using PyWavelets # to make a custom Wavelet, you need to specify lowpass and highpass decomposition filters and lowpass and highpass reconstruction filters for a Filter Bank # how do we get the lowpass and highpass decomposition filters from the highpass reconstruction filters? # see my note in my pdf/LaTeX writeup, note on Sec. 6.2. of Strang and Nguyen # the answer is to just reverse the order cf. http://www.pybytes.com/pywavelets/regression/wavelet.html c = f0[::-1] d = f1[::-1] dec_lo, dec_hi, rec_lo, rec_hi = np.hstack(c), np.hstack(d), np.hstack( f0), np.hstack(f1) filter_bank = [dec_lo, dec_hi, rec_lo, rec_hi] DaubechiesWavelet = pywt.Wavelet(name="DaubechiesWavelet", filter_bank=filter_bank) y = pywt.upcoef('a', [1., 0.], DaubechiesWavelet, numlevels) phi = M * np.append(0, y[0:L]) # For the wavelet, we need to compute the inverse DWT with a delta for the # detail coefficients. (All approximation coefficients and all detail # coefficients at finer scales are set to zero.) y = pywt.upcoef('d', [1., 0.], DaubechiesWavelet, numlevels) # Inverse DWT w = M * np.append(0, y[0:L]) # Determine the time vector. t = np.vstack(np.array(range(L + 1))) / M # Plot the results. plt.figure(1) plt.plot(t, phi, '-', label="Scaling function") plt.plot(t, w, '--', label="Wavelet")
# df.to_excel("cjp2.xlsx",sheet_name="xcjp",index=False,header=True) ########################################################################## ########################################################################## printc("用db5小波进行日前发电量3层分解") DAG = np.array(df.iloc[:, 5:6]).reshape(1, -1) # print(ML.shape) DAG_wt = pywt.wavedec(DAG, 'db5', level=3) DAG_cA3, DAG_cD3, DAG_cD2, DAG_cD1 = DAG_wt DAG_cA3 = np.array(DAG_cA3).flatten() DAG_cD3 = np.array(DAG_cD3).flatten() DAG_cD2 = np.array(DAG_cD2).flatten() DAG_cD1 = np.array(DAG_cD1).flatten() DAG_cA3_ = pywt.upcoef('a', DAG_cA3, 'db5', level=3, take=311) DAG_cD1_ = pywt.upcoef('d', DAG_cD1, 'db5', level=1, take=311) DAG_cD2_ = pywt.upcoef('d', DAG_cD2, 'db5', level=2, take=311) DAG_cD3_ = pywt.upcoef('d', DAG_cD3, 'db5', level=3, take=311) DAG_cA3_ = DAG_cA3_.tolist() DAG_cD1_ = DAG_cD1_.tolist() DAG_cD2_ = DAG_cD2_.tolist() DAG_cD3_ = DAG_cD3_.tolist() printc("用db5小波进行周前发电量3层分解") WC = np.array(df.iloc[:, 4:5]).reshape(1, -1) WC_wt = pywt.wavedec(WC, 'db5', level=3) WC_cA3, WC_cD3, WC_cD2, WC_cD1 = WC_wt WC_cA3 = np.array(WC_cA3).flatten()
def wavelet_transform(data, wavelet='db2', mode='reflect'): (cA, cD) = pywt.dwt(data, wavelet, mode) return pywt.upcoef('a',cA,wavelet,take = len(data)), \ pywt.upcoef('d',cD,wavelet,take = len(data))
def progressive_lowcut_series(series): """Progressively remove low-frequency components of 1D series. Yields sequence in which the low-frequency (large-scale) components of `series` are progressively removed. The sequence is obtained from reconstrution of a multilevel discrete haar wavelet decompositon of `series`. N.B.: The length of `series` is assumed to be a power of 2 (does not check!) Parameters ---------- series : array_like 1D data series with a length that is a power of 2 Yields ------- lowcut_series : array Sequence of progressively lowcut filtered data `series`. The yielded series have the same length as `series`. Notes ----- After an N level discrete wavelet decomposition, a data series S can be reconstructed in terms of wavelet 'approximations' (A) and 'details' (D):: S = A(N) + D(N) + D(N-1) ... D(2) + D(1) = A(N-1) + D(N-1) + ... D(2) + D(1) [A(N-1) = A(N) + D(N)] ... = A(1) + D(1) [(A(1) = A(2) + D(2)] where A(N) represents the 'lowest' level approximation [e.g., for the haar wavelet and a complete decomposition of dyadic length data, A(N) is equal to mean(S)] The sequence returned by this function is:: S - A(N), S - A(N-1), S - A(N-2), ..., S - A(1) This sequence is computed by the equivalent:: S - A(N), S - A(N) - D(N), S - A(N) - D(N) - D(N-1), ..., S - A(N) - D(N) - D(N-1) - ... - D(2), i.e. the details are removed in sequence:: lowcut = S - A(N) for j = N to 2 lowcut = lowcut - D(j) """ series_data = np.asarray(series) wavelet = pywt.Wavelet('haar') nlevel = pywt.dwt_max_level(series_data.size, wavelet.dec_len) decomp_coef = pywt.wavedec(series_data, wavelet=wavelet, level=nlevel) cAn, cD = decomp_coef[0], decomp_coef[1:] lowcut_series = series_data - pywt.upcoef('a', cAn, wavelet, level=nlevel) yield lowcut_series for j, cDj in enumerate(cD[:-1]): Dj = pywt.upcoef('d', cDj, wavelet, level=nlevel - j) lowcut_series -= Dj yield lowcut_series
def approx(x, wavelet, level): ca = pywt.wavedec(x, wavelet, level=level) ca = ca[0] return pywt.upcoef('a', ca, wavelet, level, take=len(x))
def progressive_lowcut_series(series): """Progressively remove low-frequency components of 1D series. Yields sequence in which the low-frequency (large-scale) components of `series` are progressively removed. The sequence is obtained from reconstruction of a multilevel discrete haar wavelet decomposition of `series`. N.B.: The length of `series` is assumed to be a power of 2 (does not check!) Parameters ---------- series : array_like 1D data series with a length that is a power of 2 Yields ------- lowcut_series : array Sequence of progressively lowcut filtered data `series`. The yielded series have the same length as `series`. Notes ----- After an N level discrete wavelet decomposition, a data series S can be reconstructed in terms of wavelet 'approximations' (A) and 'details' (D):: S = A(N) + D(N) + D(N-1) ... D(2) + D(1) = A(N-1) + D(N-1) + ... D(2) + D(1) [A(N-1) = A(N) + D(N)] ... = A(1) + D(1) [(A(1) = A(2) + D(2)] where A(N) represents the 'lowest' level approximation. For the haar wavelet and data S having a length that is a power of 2, A(N) is equal to mean(S)] The sequence returned by this function is:: S - A(N), S - A(N-1), S - A(N-2), ..., S - A(1) This sequence is computed by the equivalent:: S - A(N), S - A(N) - D(N), S - A(N) - D(N) - D(N-1), ..., S - A(N) - D(N) - D(N-1) - ... - D(2), i.e. the details are removed in sequence:: lowcut = S - A(N) for j = N to 2 lowcut -= D(j) """ series_data = np.asarray(series) wavelet = pywt.Wavelet("haar") nlevel = pywt.dwt_max_level(series_data.size, wavelet.dec_len) decomp_coef = pywt.wavedec(series_data, wavelet=wavelet, level=nlevel) cAn, cD = decomp_coef[0], decomp_coef[1:] lowcut_series = series_data - pywt.upcoef("a", cAn, wavelet, level=nlevel) yield lowcut_series for j, cDj in enumerate(cD[:-1]): Dj = pywt.upcoef("d", cDj, wavelet, level=nlevel - j) lowcut_series -= Dj yield lowcut_series