def __init__(self, trials=100, noise_width=0.05, ext_EMD=None, **config): # Ensemble constants self.trials = trials self.noise_width = noise_width self.random = np.random.RandomState() self.noise_kind = "normal" if ext_EMD is None: from PyEMD import EMD self.EMD = EMD() else: self.EMD = ext_EMD # By default (None) Pool spawns #processes = #CPU processes = None if "processes" not in config else config["processes"] self.pool = Pool(processes=processes) # Update based on options for key in config.keys(): if key in self.__dict__.keys(): self.__dict__[key] = config[key] elif key in self.EMD.__dict__.keys(): self.EMD.__dict__[key] = config[key]
def __init__(self, trials=100, epsilon=0.005, ext_EMD=None, **kwargs): # Ensemble constants self.trials = trials self.epsilon = epsilon self.all_noise_std = np.empty(self.trials) self.beta_progress = True # Scale noise by std self.random = np.random.RandomState() self.noise_kind = "normal" self.all_noise_EMD = [] if ext_EMD is None: from PyEMD import EMD self.EMD = EMD() else: self.EMD = ext_EMD self.range_thr = 0.01 self.total_power_thr = 0.05 # Update based on options for key in kwargs.keys(): if key in self.__dict__.keys(): self.__dict__[key] = kwargs[key] elif key in self.EMD.__dict__.keys(): self.EMD.__dict__[key] = kwargs[key]
def __init__(self, trials=100, noise_width=0.05, ext_EMD=None, parallel=True, **config): # Ensemble constants self.trials = trials self.noise_width = noise_width self.random = np.random.RandomState() self.noise_kind = "normal" self.parallel = parallel if ext_EMD is None: from PyEMD import EMD self.EMD = EMD() else: self.EMD = ext_EMD # Update based on options for key in config.keys(): if key in self.__dict__.keys() or key == "processes": self.__dict__[key] = config[key] elif key in self.EMD.__dict__.keys(): self.EMD.__dict__[key] = config[key]
def test_different_length_input(self): T = np.arange(20) S = np.random.random(len(T) + 7) emd = EMD() with self.assertRaises(ValueError): emd.emd(S, T)
def EMDsplit(dataset): samples = np.shape(dataset)[0] newdata = np.zeros((samples, 10, 4, 300)) short_samples = [] for i in range(samples): x = dataset[i, 0, 0, :] y = dataset[i, 1, 0, :] x_IMFs = EMD(x) y_IMFs = EMD(y) x_len, y_len = np.shape(x_IMFs)[0], np.shape(y_IMFs)[0] # For higher order IMFs and residue, sum it back to IMF5. if x_len > 5: for imf in range(5, x_len): x_IMFs[4, :] += x_IMFs[imf, :] if y_len > 5: for imf in range(5, y_len): y_IMFs[4, :] += y_IMFs[imf, :] # Construct newdata array for j in range(min(x_len, 5)): newdata[i, j, 0, :] = x_IMFs[j] for k in range(min(y_len, 5)): newdata[i, 4 + k, 0, :] = y_IMFs[k] print("Step {}/{} done".format(i, samples)) if x_len < 5 or y_len < 5: print("This step {} had a short EMD".format(i)) short_samples.append(i) return newdata, short_samples
def test_emd_FIXE(self): T = np.linspace(0, 1, 100) c = np.sin(9 * 2 * np.pi * T) offset = 4 S = c + offset emd = EMD() # Default state: converge self.assertTrue(emd.FIXE == 0) self.assertTrue(emd.FIXE_H == 0) # Set 1 iteration per each sift, # same as removing offset FIXE = 1 emd.FIXE = FIXE # Check flags correctness self.assertTrue(emd.FIXE == FIXE) self.assertTrue(emd.FIXE_H == 0) # Extract IMFs IMFs = emd.emd(S) # Check that IMFs are correct self.assertTrue(np.allclose(IMFs[0], c)) self.assertTrue(np.allclose(IMFs[1], offset))
def __init__(self, trials=100, epsilon=0.005, ext_EMD=None, **kwargs): # Ensemble constants self.trials = trials self.epsilon = epsilon self.all_noise_std = np.zeros(self.trials) self.beta_progress = True # Scale noise by std self.random = np.random.RandomState() self.noise_kind = "normal" self.all_noise_EMD = [] if ext_EMD is None: from PyEMD import EMD self.EMD = EMD() else: self.EMD = ext_EMD self.range_thr = 0.01 self.total_power_thr = 0.05 # By default (None) Pool spawns #processes = #CPU processes = None if "processes" not in kwargs else kwargs["processes"] self.pool = Pool(processes=processes) # Update based on options for key in kwargs.keys(): if key in self.__dict__.keys(): self.__dict__[key] = kwargs[key] elif key in self.EMD.__dict__.keys(): self.EMD.__dict__[key] = kwargs[key]
def test_akima(self): dtype = np.float32 emd = EMD() emd.spline_kind = 'akima' emd.DTYPE = dtype arr = lambda x: np.array(x) # Test error: len(X)!=len(Y) with self.assertRaises(ValueError): akima(arr([0]), arr([1, 2]), arr([0, 1, 2])) # Test error: any(dt) <= 0 with self.assertRaises(ValueError): akima(arr([1, 0, 2]), arr([1, 2]), arr([0, 1, 2])) with self.assertRaises(ValueError): akima(arr([0, 0, 2]), arr([1, 2]), arr([0, 1, 1])) # Test for correct responses T = np.array([0, 1, 2, 3, 4], dtype) S = np.array([0, 1, -1, -1, 5], dtype) t = np.array([i / 2. for i in range(9)], dtype) _t, s = emd.spline_points(t, np.array((T, S))) s_true = np.array([ S[0], 0.9125, S[1], 0.066666, S[2], -1.35416667, S[3], 1.0625, S[4] ], dtype) self.assertTrue(np.allclose(s_true, s), "Comparing akima with true") s_np = akima(np.array(T), np.array(S), np.array(t)) self.assertTrue(np.allclose(s, s_np), "Shouldn't matter if with numpy")
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 test_different_length_input(self): T = np.arange(20) S = np.random.random(len(T)+7) emd = EMD() with self.assertRaises(ValueError): emd.emd(S, T)
def test_emd_FIXE(self): T = np.linspace(0, 1, 100) c = np.sin(9*2*np.pi*T) offset = 4 S = c + offset emd = EMD() # Default state: converge self.assertTrue(emd.FIXE==0) self.assertTrue(emd.FIXE_H==0) # Set 1 iteration per each sift, # same as removing offset FIXE = 1 emd.FIXE = FIXE # Check flags correctness self.assertTrue(emd.FIXE==FIXE) self.assertTrue(emd.FIXE_H==0) # Extract IMFs IMFs = emd.emd(S) # Check that IMFs are correct self.assertTrue(np.allclose(IMFs[0], c)) self.assertTrue(np.allclose(IMFs[1], offset))
def test_single_imf(self): """ Input is IMF. Expecint single shifting. """ max_diff = lambda a,b: np.max(np.abs(a-b)) emd = EMD() emd.FIXE_H = 2 t = np.arange(0, 1, 0.001) c1 = np.cos(4*2*np.pi*t) # 2 Hz S = c1.copy() # Input - linear function f(t) = sin(2Hz t) # import pdb; pdb.set_trace() imfs = emd.emd(S, t) self.assertEqual(imfs.shape[0], 1, "Expecting sin + trend") diff = np.allclose(imfs[0], c1) self.assertTrue(diff, "Expecting 1st IMF to be sin\nMaxDiff = " + str(max_diff(imfs[0],c1))) # Input - linear function f(t) = siin(2Hz t) + 2*t c2 = 5*(t+2) S += c2.copy() imfs = emd.emd(S, t) self.assertEqual(imfs.shape[0], 2, "Expecting sin + trend") diff1 = np.allclose(imfs[0], c1, atol=0.2) self.assertTrue(diff1, "Expecting 1st IMF to be sin\nMaxDiff = " + str(max_diff(imfs[0],c1))) diff2 = np.allclose(imfs[1], c2, atol=0.2) self.assertTrue(diff2, "Expecting 2nd IMF to be trend\nMaxDiff = " + str(max_diff(imfs[1],c2)))
def test_akima(self): dtype = np.float32 emd = EMD() emd.spline_kind = 'akima' emd.DTYPE = dtype # Test error: len(X)!=len(Y) with self.assertRaises(ValueError): akima(np.array([0]), np.array([1,2]), np.array([0,1,2])) # Test error: any(dt) <= 0 with self.assertRaises(ValueError): akima(np.array([1,0,2]), np.array([1,2]), np.array([0,1,2])) with self.assertRaises(ValueError): akima(np.array([0,0,2]), np.array([1,2]), np.array([0,1,1])) # Test for correct responses T = np.array([0, 1, 2, 3, 4], dtype) S = np.array([0, 1, -1, -1, 5], dtype) t = np.array([i/2. for i in range(9)], dtype) _t, s = emd.spline_points(t, np.array((T,S))) s_true = np.array([S[0], 0.9125, S[1], 0.066666, S[2],-1.35416667, S[3], 1.0625, S[4]], dtype) self.assertTrue(np.allclose(s_true, s), "Comparing akima with true") s_np = akima(np.array(T), np.array(S), np.array(t)) self.assertTrue(np.allclose(s, s_np), "Shouldn't matter if with numpy")
def test_cubic(self): dtype = np.float64 emd = EMD() emd.spline_kind = 'cubic' emd.DTYPE = dtype T = np.array([0, 1, 2, 3, 4], dtype=dtype) S = np.array([0, 1, -1, -1, 5], dtype=dtype) t = np.arange(9, dtype=dtype)/2. # TODO: Something weird with float32. # Seems to be SciPy problem. _t, s = emd.spline_points(t, np.array((T,S))) s_true = np.array([S[0], 1.203125, S[1], 0.046875, \ S[2], -1.515625, S[3], 1.015625, S[4]], dtype=dtype) self.assertTrue(np.allclose(s, s_true, atol=0.01), "Comparing cubic") T = T[:-2].copy() S = S[:-2].copy() t = np.arange(5, dtype=dtype)/2. _t, s3 = emd.spline_points(t, np.array((T,S))) s3_true = np.array([S[0], 0.78125, S[1], 0.28125, S[2]], dtype=dtype) self.assertTrue(np.allclose(s3, s3_true), "Compare cubic 3pts")
class EmdTransformer(object): """Empirical Mode Decomposition""" def __init__(self, ensemble=False, **kwargs): self.ensemble = ensemble if ensemble: self.emd_obj = EEMD(**kwargs) else: self.emd_obj = EMD(**kwargs) def fit_transform(self, data, **kwargs): if isinstance(data, pd.DataFrame): data = data.values else: assert isinstance(data, np.ndarray) assert len(data.shape) == 2 imfs = [] for col in range(data.shape[1]): if self.ensemble: IMFs = self.emd_obj.eemd(data[:, col], **kwargs) else: IMFs = self.emd_obj.emd(data[:, col], **kwargs) imfs.append(IMFs.T) return np.concatenate(imfs, axis=1) def inverse_transform(self, **kwargs): raise NotImplementedError
def __init__(self, trials: int = 100, noise_width: float = 0.05, ext_EMD=None, parallel: bool = False, **kwargs): # Ensemble constants self.trials = trials self.noise_width = noise_width self.separate_trends = bool(kwargs.get('separate_trends', False)) self.random = np.random.RandomState() self.noise_kind = kwargs.get('noise_kind', 'normal') self.parallel = parallel self.processes = kwargs.get('processes') # Optional[int] if self.processes is not None and not self.parallel: self.logger.warning( "Passed value for process has no effect when `parallel` is False." ) if ext_EMD is None: from PyEMD import EMD self.EMD = EMD(**kwargs) else: self.EMD = ext_EMD self.E_IMF = None # Optional[np.ndarray] self.residue = None # Optional[np.ndarray]
def test_unsupporter_spline(self): emd = EMD() emd.spline_kind = "waterfall" S = np.random.random(20) with self.assertRaises(ValueError): emd.emd(S)
def test_calc_instant_freq(self): t = np.linspace(0, 1, 50) S = t + np.cos(np.cos(4. * t**2)) emd = EMD() imfs = emd.emd(S, t) vis = Visualisation() freqs = vis._calc_inst_freq(imfs, t, False, None) assert imfs.shape == freqs.shape
def test_calc_instant_phase3(self): t = np.linspace(0, 1, 50) S = t + np.cos(np.cos(4. * t**2)) emd = EMD() imfs = emd.emd(S, t) vis = Visualisation() with self.assertRaises(AssertionError): phase = vis._calc_inst_phase(imfs, 0.8)
def test_calc_instant_phase2(self): t = np.linspace(0, 1, 50) S = t + np.cos(np.cos(4. * t**2)) emd = EMD() imfs = emd.emd(S, t) vis = Visualisation() phase = vis._calc_inst_phase(imfs, 0.4) assert len(imfs) == len(phase)
def __init__(self, trails, n_component, whiten=True, max_iter=200): self.ceemdan = CEEMDAN(trials=trails) self.eemd = EEMD(trails=trails) self.emd = EMD() self.n_component = n_component self.ICA_transfomer = FastICA(n_components=n_component, whiten=whiten, max_iter=max_iter)
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_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 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_wrong_extrema_detection_type(self): emd = EMD() emd.extrema_detection = "very_complicated" t = np.arange(10) s = np.array([-1, 0, 1, 0, -1, 0, 3, 0, -9, 0]) with self.assertRaises(ValueError): emd.find_extrema(t, s)
def IMFs(self, win): temp = self.data_freq * int(1 / self.gap) self.price = self.PriceList[-60 / int(self.gap):-1] s = self.price emd = EMD() IMFs = emd.emd(s) r = IMFs[-1] b = np.std(s - r) self.r = math.log(b / a)
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 dme_function(lista_para_ejecutar): nueva_list = lista_para_ejecutar new_data =[] for item in nueva_list: new_data.append(float(item)) #x = np.linspace(0, 10, len(lista_para_ejecutar)) signal = np.array(new_data) emd = EMD() IMFS = emd.emd(signal) return IMFS
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 imff(self): temp = self.data_freq * int(1 / self.gap) self.price = self.PriceList[-int(self.data_freq / self.gap):-1] s = np.array(self.price) emd = EMD() IMFs = emd.emd(s) r = IMFs[-1] a = np.std(r) b = np.std(s - r) self.r = math.log(b / a)
def emd_csi(csi, imfn=10): # Execute EMD on signal emd = EMD() emd.FIXE = 10 IMF = emd(csi) csi_emd = np.zeros((csi.shape[0], imfn)) for n, imf in enumerate(IMF): if n < imfn: csi_emd[:, n - 1] = imf return csi_emd
def get_same_shaped_imfs(signal): emd = EMD() try: imfs_signal = emd.emd(signal.numpy(), max_imf=12) except AttributeError: imfs_signal = emd.emd(signal, max_imf=12) if imfs_signal.shape[0] > 12: imfs_signal = imfs_signal[:12, :] new_imfs = np.zeros((12, signal.shape[0])) new_imfs[:imfs_signal.shape[0], :] = imfs_signal return new_imfs
def test_emd_passArgsViaDict(self): FIXE = 10 params = {"FIXE": FIXE} # First test without initiation emd = EMD() self.assertFalse(emd.FIXE == FIXE, "{} == {}".format(emd.FIXE, FIXE)) # Second: test with passing emd = EMD(**params) self.assertTrue(emd.FIXE == FIXE, "{} == {}".format(emd.FIXE, FIXE))
def test_max_iteration_flag(self): S = np.random.random(200) emd = EMD() emd.MAX_ITERATION = 10 emd.FIXE = 20 imfs = emd.emd(S) # There's not much to test, except that it doesn't fail. # With low MAX_ITERATION value for random signal it's # guaranteed to have at least 2 imfs. self.assertTrue(imfs.shape[0]>1)
def test_trend(self): """ Input is trend. Expeting no shifting process. """ emd = EMD() t = np.arange(0, 1, 0.01) S = 2*t # Input - linear function f(t) = 2*t imfs = emd.emd(S, t) self.assertEqual(imfs.shape[0], 1, "Expecting single IMF") self.assertTrue(np.allclose(S, imfs[0]))
def test_slinear(self): dtype = np.float64 emd = EMD() emd.spline_kind = 'slinear' emd.DTYPE = dtype T = np.array([0, 1, 2, 3, 4], dtype=dtype) S = np.array([0, 1, -1, -1, 5], dtype=dtype) t = np.arange(9, dtype=dtype)/2. _t, s = emd.spline_points(t, np.array((T,S))) s_true = np.array([S[0], 0.5, S[1], 0, \ S[2], -1, S[3], 2, S[4]], dtype=dtype) self.assertTrue(np.allclose(s, s_true), "Comparing SLinear")
def test_incorrectExtremaDetectionSetup(self): extrema_detection = "bubble_gum" # Sanity check emd = EMD() self.assertFalse(emd.extrema_detection==extrema_detection) # Assign incorrect extrema_detection emd.extrema_detection = extrema_detection self.assertTrue(emd.extrema_detection==extrema_detection) T = np.arange(10) S = np.sin(T) max_pos, max_val = np.random.random((2,3)) min_pos, min_val = np.random.random((2,3)) # Check for Exception with self.assertRaises(ValueError): emd.prepare_points(T, S, max_pos, max_val, min_pos, min_val)
def test_find_extrema_parabol(self): """ Simple test for extrema. """ emd = EMD() emd.extrema_detection = "parabol" t = np.arange(10) s = np.array([-1, 0, 1, 0, -1, 0, 3, 0, -9, 0]) expMaxPos = [2, 6] expMaxVal = [1, 3] expMinPos = [4, 8] expMinVal = [-1, -9] maxPos, maxVal, minPos, minVal, nz = emd.find_extrema(t, s) self.assertEqual(maxPos.tolist(), expMaxPos) self.assertEqual(maxVal.tolist(), expMaxVal) self.assertEqual(minPos.tolist(), expMinPos) self.assertEqual(minVal.tolist(), expMinVal)
def test_emd_default(self): T = np.linspace(0, 2, 200) c1 = 1*np.sin(11*2*np.pi*T+0.1) c2 = 11*np.sin(1*2*np.pi*T+0.1) offset = 9 S = c1 + c2 + offset emd = EMD(spline_kind='akima') imfs = emd.emd(S, T) self.assertTrue(imfs.shape[0]==3) close_imfs1 = np.allclose(c1[2:-2], imfs[0,2:-2], atol=0.21) self.assertTrue(close_imfs1) close_imfs2 = np.allclose(c2[2:-2], imfs[1,2:-2], atol=0.24) diff = np.abs(c2[2:-2] - imfs[1,2:-2]) self.assertTrue(close_imfs2) close_offset = np.allclose(offset, imfs[2,1:-1], atol=0.5) self.assertTrue(close_offset)
def test_find_extrema_simple_repeat(self): """ Test what happens in /^^\ situation, i.e. when extremum is somewhere between two consecutive pts. """ emd = EMD() emd.extrema_detection = "simple" t = np.arange(2,13) s = np.array([-1, 0, 1, 1, 0, -1, 0, 3, 0, -9, 0]) expMaxPos = [4, 9] expMaxVal = [1, 3] expMinPos = [7, 11] expMinVal = [-1, -9] maxPos, maxVal, minPos, minVal, nz = emd.find_extrema(t, s) self.assertEqual(maxPos.tolist(), expMaxPos) self.assertEqual(maxVal.tolist(), expMaxVal) self.assertEqual(minPos.tolist(), expMinPos) self.assertEqual(minVal.tolist(), expMinVal)
def test_emd_FIXEH(self): T = np.linspace(0, 2, 200) c1 = 1*np.sin(11*2*np.pi*T+0.1) c2 = 11*np.sin(1*2*np.pi*T+0.1) offset = 9 S = c1 + c2 + offset emd = EMD() # Default state: converge self.assertTrue(emd.FIXE==0) self.assertTrue(emd.FIXE_H==0) # Set 5 iterations per each protoIMF FIXE_H = 6 emd.FIXE_H = FIXE_H # Check flags correctness self.assertTrue(emd.FIXE==0) self.assertTrue(emd.FIXE_H==FIXE_H) # Extract IMFs imfs = emd.emd(S) # Check that IMFs are correct self.assertTrue(imfs.shape[0]==3) close_imf1 = np.allclose(c1[2:-2], imfs[0,2:-2], atol=0.2) self.assertTrue(close_imf1) self.assertTrue(np.allclose(c1, imfs[0], atol=1.)) close_imf2 = np.allclose(c2[2:-2], imfs[1,2:-2], atol=0.21) self.assertTrue(close_imf2) self.assertTrue(np.allclose(c2, imfs[1], atol=1.)) close_offset = np.allclose(offset, imfs[2,2:-2], atol=0.1) self.assertTrue(close_offset) close_offset = np.allclose(offset, imfs[2,1:-1], atol=0.5) self.assertTrue(close_offset)
def test_bound_extrapolation_parabol(self): emd = EMD() emd.extrema_detection = "parabol" emd.nbsym = 1 emd.DTYPE = np.float64 S = [0,-3, 1, 4, 3, 2,-2, 0, 1, 2, 1, 0, 1, 2, 5, 4, 0,-2,-1] S = np.array(S) T = np.arange(len(S)) pp = emd.prepare_points # There are 4 cases for both (L)eft and (R)ight ends. In case of left (L) bound: # L1) ,/ -- ext[0] is min, s[0] < ext[1] (1st max) # L2) / -- ext[0] is min, s[0] > ext[1] (1st max) # L3) ^. -- ext[0] is max, s[0] > ext[1] (1st min) # L4) \ -- ext[0] is max, s[0] < ext[1] (1st min) ## CASE 1 # L1, R1 -- no edge MIN & no edge MIN s = S.copy() t = T.copy() maxPos, maxVal, minPos, minVal, nz = emd.find_extrema(t, s) # Should extrapolate left and right bounds maxExtrema, minExtrema = pp(t, s, \ maxPos, maxVal, minPos, minVal) maxExtrema = np.round(maxExtrema, decimals=3) minExtrema = np.round(minExtrema, decimals=3) self.assertEqual([-1.393,3.25,9,14.25,20.083], maxExtrema[0].tolist()) self.assertEqual([4.125,4.125,2,5.125,5.125], maxExtrema[1].tolist()) self.assertEqual([-4.31,0.929,6.167,11,17.167,23.333], minExtrema[0].tolist()) self.assertEqual([-2.083,-3.018,-2.083,0,-2.042,0], minExtrema[1].tolist()) ## CASE 2 # L2, R2 -- edge MIN, edge MIN s = S[1:-1].copy() t = T[1:-1].copy() maxPos, maxVal, minPos, minVal, nz = emd.find_extrema(t, s) # Should extrapolate left and right bounds maxExtrema, minExtrema = pp(t, s, \ maxPos, maxVal, minPos, minVal) maxExtrema = np.round(maxExtrema, decimals=3) minExtrema = np.round(minExtrema, decimals=3) self.assertEqual([-1.25,3.25,9,14.25,19.75], maxExtrema[0].tolist()) self.assertEqual([4.125,4.125,2,5.125,5.125], maxExtrema[1].tolist()) self.assertEqual([1,6.167,11,17], minExtrema[0].tolist()) self.assertEqual([-3,-2.083,0,-2], minExtrema[1].tolist()) ## CASE 3 # L3, R3 -- no edge MAX & no edge MAX s = S[2:-3].copy() t = T[2:-3].copy() maxPos, maxVal, minPos, minVal, nz = emd.find_extrema(t, s) # Should extrapolate left and right bounds maxExtrema, minExtrema = pp(t, s, \ maxPos, maxVal, minPos, minVal) maxExtrema = np.round(maxExtrema, decimals=3) minExtrema = np.round(minExtrema, decimals=3) self.assertEqual([-2.5,3.25,9,14.25,19.5], maxExtrema[0].tolist()) self.assertEqual([2,4.125,2,5.125,2], maxExtrema[1].tolist()) self.assertEqual([0.333,6.167,11,17.5], minExtrema[0].tolist()) self.assertEqual([-2.083,-2.083,0,0], minExtrema[1].tolist()) ## CASE 4 # L4, R4 -- edge MAX & edge MAX s = S[3:-4].copy() t = T[3:-4].copy() maxPos, maxVal, minPos, minVal, nz = emd.find_extrema(t, s) # Should extrapolate left and right bounds maxExtrema, minExtrema = pp(t, s, \ maxPos, maxVal, minPos, minVal) maxExtrema = np.round(maxExtrema, decimals=3) minExtrema = np.round(minExtrema, decimals=3) self.assertEqual([3,9,14], maxExtrema[0].tolist()) self.assertEqual([4,2,5], maxExtrema[1].tolist()) self.assertEqual([-0.167,6.167,11,17], minExtrema[0].tolist()) self.assertEqual([-2.083,-2.083,0,0], minExtrema[1].tolist())
def test_bound_extrapolation_simple(self): emd = EMD() emd.extrema_detection = "simple" emd.nbsym = 1 emd.DTYPE = np.int64 S = [0,-3, 1, 4, 3, 2,-2, 0, 1, 2, 1, 0, 1, 2, 5, 4, 0,-2,-1] S = np.array(S) T = np.arange(len(S)) pp = emd.prepare_points # There are 4 cases for both (L)eft and (R)ight ends. In case of left (L) bound: # L1) ,/ -- ext[0] is min, s[0] < ext[1] (1st max) # L2) / -- ext[0] is min, s[0] > ext[1] (1st max) # L3) ^. -- ext[0] is max, s[0] > ext[1] (1st min) # L4) \ -- ext[0] is max, s[0] < ext[1] (1st min) ## CASE 1 # L1, R1 -- no edge MIN & no edge MIN s = S.copy() t = T.copy() maxPos, maxVal, minPos, minVal, nz = emd.find_extrema(t, s) # Should extrapolate left and right bounds maxExtrema, minExtrema = pp(t, s, \ maxPos, maxVal, minPos, minVal) self.assertEqual([-1,3,9,14,20], maxExtrema[0].tolist()) self.assertEqual([4,4,2,5,5], maxExtrema[1].tolist()) self.assertEqual([-4,1,6,11,17,23], minExtrema[0].tolist()) self.assertEqual([-2,-3,-2,0,-2,0], minExtrema[1].tolist()) ## CASE 2 # L2, R2 -- edge MIN, edge MIN s = S[1:-1].copy() t = T[1:-1].copy() maxPos, maxVal, minPos, minVal, nz = emd.find_extrema(t, s) # Should extrapolate left and right bounds maxExtrema, minExtrema = pp(t, s, \ maxPos, maxVal, minPos, minVal) self.assertEqual([-1,3,9,14,20], maxExtrema[0].tolist()) self.assertEqual([4,4,2,5,5], maxExtrema[1].tolist()) self.assertEqual([1,6,11,17], minExtrema[0].tolist()) self.assertEqual([-3,-2,0,-2], minExtrema[1].tolist()) ## CASE 3 # L3, R3 -- no edge MAX & no edge MAX s, t = S[2:-3], T[2:-3] maxPos, maxVal, minPos, minVal, nz = emd.find_extrema(t, s) # Should extrapolate left and right bounds maxExtrema, minExtrema = pp(t, s, \ maxPos, maxVal, minPos, minVal) self.assertEqual([-3,3,9,14,19], maxExtrema[0].tolist()) self.assertEqual([2,4,2,5,2], maxExtrema[1].tolist()) self.assertEqual([0,6,11,17], minExtrema[0].tolist()) self.assertEqual([-2,-2,0,0], minExtrema[1].tolist()) ## CASE 4 # L4, R4 -- edge MAX & edge MAX s, t = S[3:-4], T[3:-4] maxPos, maxVal, minPos, minVal, nz = emd.find_extrema(t, s) # Should extrapolate left and right bounds maxExtrema, minExtrema = pp(t, s, \ maxPos, maxVal, minPos, minVal) self.assertEqual([3,9,14], maxExtrema[0].tolist()) self.assertEqual([4,2,5], maxExtrema[1].tolist()) self.assertEqual([0,6,11,17], minExtrema[0].tolist()) self.assertEqual([-2,-2,0,0], minExtrema[1].tolist())