def estimate_trend(self, time_series_x: np.ndarray, time_series_y: np.ndarray): # Extract imfs and residue emd = EMD() emd.emd(time_series_y) imfs, res = emd.get_imfs_and_residue() return imfs[-1]
def get_imfs(pid, df, config): c = df.iloc[pid]['class'] f = df.iloc[pid]['fname'] signal, rate = librosa.load('data/' + c + '/' + f) emd = EMD() emd(signal, max_imf=config.max_imf) imfs, residue = emd.get_imfs_and_residue() return pid, imfs, residue, rate
def test_imfs_and_residue_accessor(self): S = np.random.random(200) emd = EMD(**{"MAX_ITERATION": 10, "FIXE": 20}) all_imfs = emd(S, max_imf=3) imfs, residue = emd.get_imfs_and_residue() self.assertEqual(all_imfs.shape[0], imfs.shape[0]+1, "Compare number of components") self.assertTrue(np.array_equal(all_imfs[:-1], imfs), "Shouldn't matter where imfs are from") self.assertTrue(np.array_equal(all_imfs[-1], residue), "Residue, if any, is the last row")
def Inst_freq(peeled_seq, fs=4000): t = np.arange(0, 1, 1 / fs) # print(len(t)) emd = EMD() emd.emd(peeled_seq) imfs, res = emd.get_imfs_and_residue() vis = Visualisation(emd) imfs_inst_freqs = vis._calc_inst_freq(imfs, t, order=False, alpha=None) return imfs_inst_freqs
def test_instantiation2(self): t = np.linspace(0, 1, 50) S = t + np.cos(np.cos(4. * t**2)) emd = EMD() emd.emd(S, t) imfs, res = emd.get_imfs_and_residue() vis = Visualisation(emd) assert (vis.imfs == imfs).all() assert (vis.residue == res).all()
def test_check_imfs5(self): t = np.linspace(0, 1, 50) S = t + np.cos(np.cos(4. * t**2)) emd = EMD() emd.emd(S, t) imfs, res = emd.get_imfs_and_residue() vis = Visualisation(emd) imfs2, res2 = vis._check_imfs(imfs, res, False) assert (imfs == imfs2).all() assert (res == res2).all()
def emd_decompose(a, t): emd = EMD() emd.emd(a) imfs, res = emd.get_imfs_and_residue() plt.plot(t, a) plt.title('origin sequence') vis = Visualisation(emd) vis.plot_imfs(t=t) vis.plot_instant_freq(t) vis.show() plt.show() return imfs, res
def Visualing(peeled_seq, fs=4000): t = np.arange(0, 1, 1 / fs) # print(len(t)) emd = EMD() emd.emd(peeled_seq) imfs, res = emd.get_imfs_and_residue() vis = Visualisation(emd) # Create a plot with all IMFs and residue vis.plot_imfs(imfs=imfs, residue=res, t=t, include_residue=True) # Create a plot with instantaneous frequency of all IMFs vis.plot_instant_freq(t, imfs=imfs) # Show both plots vis.show()
def empirical_mode_decomposition(date_ini, ts_ini): """ :param ts_ini: the raw data to be decomposed :return: the decomposed time series """ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//the wavelet tranform //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # A2, D2, D1 = pywt.wavedec(stress_ini.ravel(), 'db5', level=2) # print(stress_ini.shape) # print(D2.shape, D1.shape) # cow = [A2, D2, D1] # raw_data = pywt.waverec(cow, 'db5') # plt.style.use('seaborn-pastel') # fig = plt.figure(figsize=(8, 6)) # ax = fig.add_subplot(111) # ax.plot(stress_ini) # ax.plot(A2) # ax.plot(D2) # ax.plot(D1) # ax.plot(raw_data+0.1) # plt.show() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//the empirical mode decomposition //~~~~~~~~~~~~~~~~~~~~~ emd = EMD() emd.emd(ts_ini.ravel()) imfs, res = emd.get_imfs_and_residue() # Plot results # N = imfs.shape[0] + 2 # plt.style.use('seaborn-pastel') # plt.figure(figsize=(15, 20)) # plt.subplot(N, 1, 1) # plt.plot(date_ini, ts_ini, 'r') # plt.title("Raw data") # plt.xlabel('shear stress, ' + r'$\tau$(MPa)') # # for n, imf in enumerate(imfs): # plt.subplot(N, 1, n + 2) # plt.plot(date_ini, imf, 'g') # plt.title("IMF " + str(n + 1)) # plt.xlabel("Time [0.1s]") # # plt.subplot(N, 1, N) # plt.plot(date_ini, res, 'b') # plt.title("residue") # plt.xlabel('shear stress, ' + r'$\tau$(MPa)') # plt.tight_layout() # plt.savefig('simple_example', dpi=600, bbox_inches='tight') # plt.show() return imfs, res
def hes2(args): n = 10000 t = np.arange(0, n/args.fs, 1/args.fs) S = args.singled_out[-1, 0:n] args.temp_add = 'emd_raw' show_signal(S, args) emd = EMD() emd.emd(S) imfs, res = emd.get_imfs_and_residue() # In general: # components = EEMD()(S) # imfs, res = components[:-1], components[-1] vis = Visualisation() vis.plot_imfs(imfs=imfs, residue=res, t=t, include_residue=True) vis.plot_instant_freq(t, imfs=imfs) vis.show() return 0
data = scio.loadmat(fn) t = np.arange(0, 10000 / 24000, 1 / 24000) f = np.arange(0, 10000) * 24000 / 10000 s0 = data['s0'][:, 0] s1 = data['s1'][:, 0] s2 = data['s2'][:, 0] s3 = data['s3'][:, 0] s4 = data['s4'][:, 0] s5 = data['s5'][:, 0] d = WaveletDenoising(s1).out emd = EMD() emd.emd(d, T=t) imfs, res = emd.get_imfs_and_residue() fig = plt.figure(figsize=(12, 16)) ax_main = fig.add_subplot(len(imfs) + 1, 1, 1) ax_main.set_title(title) ax_main.plot(t, d) rec_b = [] for i in imfs: rec_b.append(d - i) d -= i for i, y in enumerate(rec_b): ax = fig.add_subplot(len(rec_b) + 1, 2, 3 + i * 2) ax.plot(t, y, 'r')
def test_imfs_and_residue_accessor2(self): emd = EMD() with self.assertRaises(ValueError): imfs, residue = emd.get_imfs_and_residue()
def test_get_imfs_and_residue_without_running(self): emd = EMD() with self.assertRaises(ValueError): imfs, residue = emd.get_imfs_and_residue()
def main(args): subdir = datetime.strftime(datetime.now(), '%Y%m%d-%H%M%S') if ~os.path.isabs(args.output_base_dir): dirpath = os.path.dirname(__file__) args.output_base_dir = os.path.join(dirpath, args.output_base_dir) output_dir = os.path.join(os.path.expanduser(args.output_base_dir), subdir) if not os.path.isdir(output_dir): # Create the model directory if it doesn't exist os.makedirs(output_dir) log_dir = args.logs_base_dir if ~os.path.isabs(args.logs_base_dir): log_dir = os.path.join(output_dir, args.logs_base_dir) if not os.path.isdir(log_dir): # Create the log directory if it doesn't exist os.makedirs(log_dir) # Store some git revision info in a text file in the log directory src_path, _ = os.path.split(os.path.realpath(__file__)) # store_revision_info(src_path, log_dir, ' '.join(sys.argv)) print('Output directory: %s' % output_dir) print('Log directory: %s' % log_dir) args.output_dir = output_dir #data = loadmat('data/20msclean_n.mat') data = loadmat('data/1ERBclean_n.mat') args.channels = data['channels'] args.labels = data['labels'] args.labels = args.labels[0] cz = np.squeeze(args.channels[-1, :, :]) ind = (args.labels == 1000) cz_ind = cz[:, ind] x = np.arange(-100,2000) #plt.plot(x, np.mean(cz_ind, 1)) #, 'LineWidth', 2 #plt.show() #plt.plot([0, 0], [-4, 4]) #, 'LineWidth', 2) #plt.plot([-100, 1999], [0, 0]) #, 'LineWidth', 2) #xlim([-100 1000]) #legend(num2str([1: 69]')) fs = 1000 emd = EMD() n_tr = cz_ind.shape[1] nbin = 200 hist_wind = np.zeros([nbin, cz_ind.shape[0]-1000]) wind_ = np.zeros([cz_ind.shape[0], cz_ind.shape[1]]) allign_vals = np.zeros([cz_ind.shape[1]]) for cnt_trial in range(0, n_tr): S = np.squeeze(cz_ind[:, cnt_trial]) #plt.plot(S) #plt.show() S1 = S[100:250] minpos1 = np.argmin(S1) allign_vals[cnt_trial] = minpos1 + 100 order = 2 lf_cutoff = 4. hf_cutoff = 100. imf3 = butter_bandpass(S, lf_cutoff, hf_cutoff, fs, order) emd.emd(S) imfs, res = emd.get_imfs_and_residue() #imf3 = imfs[-3] #vis = Visualisation() #t = np.arange(0, S.size/fs, 1/fs) #vis.plot_imfs(imfs=imfs, residue=res, t=t, include_residue=True) #vis.plot_instant_freq(t, imfs=imfs) #vis.show() stop = 1 # check the emd components if 1: #for imf in imfs: spectrum = plt.magnitude_spectrum(imf3, fs) #plt.plot(spectrum[1], spectrum[0]) #plt.show() #stop = 1 #plt.plot(imf3) #plt.show() # let's say the algorithm above calculates the spectrum magnitude and gives us the imf which is in delta range # manually we have seen it is imfs[-3] y2 = imf3 #S y = hilbert(y2) angles = np.angle(y) insta_phase = np.unwrap(angles) # should we ingore this and go straight to the normsss insta_phase_norm = (insta_phase + math.pi) / (2 * math.pi) % 1. wind_[:, cnt_trial] = insta_phase_norm print(cnt_trial) stop = 1 #phase_reset_wind = np.zeros([args.len_uc, args.nbin, args.win_l + args.win_r]) v = 1 #phase_reset_wind = np.exp(1j * v * 2 * math.pi * wind_) #phase_reset_mean = np.zeros([1, cz_ind.shape[0]]) #phase_reset_std = np.zeros([1, cz_ind.shape[0]]) #for i, uclass in enumerate(args.uc): #ind = (args.uc_ind == i) #temp = wind_[ind, :] allign_vals = allign_vals.astype(int) wind_alligned = np.zeros([cz_ind.shape[0]-1000, cz_ind.shape[1]]) for cnt_trial in range(0, n_tr): print(allign_vals[cnt_trial] - 100) print(allign_vals[cnt_trial] + 999) wind_alligned[:, cnt_trial] = wind_[allign_vals[cnt_trial]-100:allign_vals[cnt_trial] + 1000, cnt_trial] for cnti in range(wind_alligned.shape[0]): test = np.histogram(wind_alligned[cnti, :], nbin, (0, 1)) # calc hist wind_[ind, :] hist_wind[:, cnti] = test[0] # step = np.abs(np.mean(phase_reset_wind[ind, :])) # mean_step = np.mean() #phase_reset_mean[i, :] = np.abs(np.mean(phase_reset_wind[ind, :], 0)) #phase_reset_std[i, :] = np.abs(np.std(phase_reset_wind[ind, :], 0)) # fig, ax = plt.subplots(nrows=1, ncols=1) sigma_y = 2.0 sigma_x = 2.0 sigma = [sigma_y, sigma_x] y = sp.ndimage.filters.gaussian_filter(hist_wind, sigma, mode='constant') plt.imshow(y) # , aspect='auto' #plt.title(np.max(y)) # ax.set_adjustable('box-forced') #filename = 'histophases' + str(cnt_ch) + 'ch' + str(i) + 'cl' + '.png' #plt.savefig(os.path.join(args.output_dir, filename), bbox_inches='tight', pad_inches=0) #plt.close() plt.show() plt.waitforbuttonpress(0.1) plt.close()