Ejemplo n.º 1
0
    def test_eemd_simpleRun(self):
        T = np.linspace(0, 1, 100)
        S = np.sin(2*np.pi*T)

        eemd = EEMD(trials=10, max_imf=1)
        eemd.EMD.FIXE_H = 5
        eemd.eemd(S)
Ejemplo n.º 2
0
def nonlinear_trend_test(trend):
    #Use surrogate method to test for EEMD trend significance
    t = len(trend)
    ts = trend.reshape(1, -1)  #reshape into 2d array for surrogate methods
    ts_sur = timeseries.surrogates.Surrogates(
        ts)  #generate an instance of surrogate class
    sur_list = [
        ts
    ]  #original time series is the first item in the surrogate list
    # Assign EEMD to `eemd` variable
    eemd = EEMD()
    eemd.noise_seed(12345)
    #detect extrema using parabolic method
    emd = eemd.EMD
    emd.extrema_detection = "parabol"
    for i in range(19):  #0.05 significance level for one-sided test
        sur = ts_sur.refined_AAFT_surrogates(
            ts, 100
        )  #Return surrogates using the iteratively refined amplitude adjusted Fourier transform method.
        #detrend surrogate
        eIMFs_n = eemd.eemd(sur.flatten(), np.arange(t))
        sur_trend = eIMFs_n[-1]
        sur_list.append(sur_trend)
    ta_list = [timeAsymmetry(ts.flatten())
               for ts in sur_list]  #test statistic: time asymmetry
    return np.array(ta_list)
Ejemplo n.º 3
0
def read_data():
    """
    读取data下面所有文件
    :param time_steps: 采样率,输入数据的长度,步长
    :return:
    """
    eemd = EEMD()
    emd = eemd.EMD
    emd.extrema_detection = "parabol"
    for item in os.listdir('../data'):
        # 每读取一个文件,保存一个
        print("start...{%s}" % item)
        # 获取文件名
        short_name, _ = os.path.splitext(item)
        time_series = read_matdata('../data/' + item)
        # 将故障样本拆分为训练样本长度
        input_length = time_series.shape[0] // TIME_PERIODS
        # 三维矩阵,记录每个输入样本长度,每个分量,信号信息
        x = np.zeros((input_length, IMF_LENGTH, TIME_PERIODS))
        # 获取序列最大长度,去掉信号后面的余数
        idx_last = -(time_series.shape[0] % TIME_PERIODS)
        # 切片分割(input_length, time_steps)
        clips = time_series[:idx_last].reshape(-1, TIME_PERIODS)
        # 对每个样本做eemd处理
        for i in range(clips.shape[0]):
            eimfs = eemd.eemd(clips[i])
            print("start emf...%s-%d" % (item, i))
            print(eimfs)
            x[i] = eimfs[0:IMF_LENGTH]
        # 将每个输入样本拉平,存储
        b = x.reshape(input_length, -1)
        np.savetxt('../emd_data/' + short_name + '.txt', b)
        print(x)
Ejemplo n.º 4
0
def rolling_EEMD(sym, column, win, per, perend):
    datablock = get_data_for_EEMD(sym, column, per, perend)
    winlength = int(win * 24 * 12)
    t = np.linspace(0, winlength - 1, winlength)
    eemd = EEMD()
    emd = eemd.EMD
    emd.extrema_detection = "parabol"
    nIMF = []
    last = []
    dlast = []
    timelist = []
    timearray = datablock.index[(winlength):]
    for i in tqdm(range(winlength, datablock.__len__(), 1)):
        datawindow = datablock.iloc[i - winlength:i]
        # Execute EEMD on window
        maximf = 6
        eIMFs = eemd.eemd(datawindow.tolist(), t, max_imf=maximf)
        nIMFs = eIMFs.shape[0]
        nIMF.append(nIMFs)
        last.append(eIMFs[0:nIMFs, -1])
        d = eIMFs[0:nIMFs, -1] - eIMFs[0:nIMFs, -2]
        dlast.append(d)
        timelist.append(datawindow.index[-1])
    lastdf = pd.DataFrame(last, index=timearray)
    dlastdf = pd.DataFrame(dlast, index=timearray)
    return [lastdf, dlastdf]
def main():
    e = exchange.Exchange('../lib/binance.db')

    start = datetime.datetime(2018, 8, 1)
    end = datetime.datetime(2019, 8, 1)

    params = parameter_estimation.calculate_parameters(start, end, 6, e)

    eemd = EEMD()
    emd = eemd.EMD

    eIMFs_rate = eemd.eemd(np.array([p[1] for p in params]))

    fig, axs = plt.subplots(eIMFs_rate.shape[0],
                            figsize=(12, eIMFs_rate.shape[0] * 3))
    rate = np.zeros(eIMFs_rate.shape[1])

    for ax, IMF in zip(axs, eIMFs_rate):
        #ax.plot(IMF)
        ax.plot(IMF)
        analytic_signal = hilbert(IMF)
        phase = np.unwrap(np.angle(analytic_signal))
        freq = np.diff(phase) / (2 * np.pi * 0.25)
        print(np.mean(1 / freq))

    plt.tight_layout()
    plt.show()
Ejemplo n.º 6
0
    def test_eemd_passingArgumentsViaDict(self):
        trials = 10
        noise_kind = 'uniform'
        spline_kind = 'linear'

        # Making sure that we are not testing default options
        eemd = EEMD()

        self.assertFalse(eemd.trials == trials,
                         self.cmp_msg(eemd.trials, trials))

        self.assertFalse(eemd.noise_kind == noise_kind,
                         self.cmp_msg(eemd.noise_kind, noise_kind))

        self.assertFalse(eemd.EMD.spline_kind == spline_kind,
                         self.cmp_msg(eemd.EMD.spline_kind, spline_kind))

        # Testing for passing attributes via params
        eemd = EEMD(trials=trials,
                    noise_kind=noise_kind,
                    spline_kind=spline_kind)

        self.assertTrue(eemd.trials == trials,
                        self.cmp_msg(eemd.trials, trials))

        self.assertTrue(eemd.noise_kind == noise_kind,
                        self.cmp_msg(eemd.noise_kind, noise_kind))

        self.assertTrue(eemd.EMD.spline_kind == spline_kind,
                        self.cmp_msg(eemd.EMD.spline_kind, spline_kind))
Ejemplo n.º 7
0
    def test_eemd_noiseSeed(self):
        T = np.linspace(0, 1, 100)
        S = np.sin(2*np.pi*T+ 4**T) + np.cos( (T-0.4)**2)

        # Compare up to machine epsilon
        cmpMachEps = lambda x, y: np.abs(x-y)<=2*np.finfo(x.dtype).eps

        config = {"processes": 1}
        eemd = EEMD(trials=10, **config)

        # First run random seed
        eIMF1 = eemd(S)

        # Second run with defined seed, diff than first
        eemd.noise_seed(12345)
        eIMF2 = eemd(S)

        # Extremly unlikely to have same seed, thus different results
        msg_false = "Different seeds, expected different outcomes"
        if eIMF1.shape == eIMF2.shape:
            self.assertFalse(np.all(cmpMachEps(eIMF1,eIMF2)), msg_false)

        # Third run with same seed as with 2nd
        eemd.noise_seed(12345)
        eIMF3 = eemd(S)

        # Using same seeds, thus expecting same results
        msg_true = "Used same seed, expected same results"
        self.assertTrue(np.all(cmpMachEps(eIMF2,eIMF3)), msg_true)
Ejemplo n.º 8
0
def FEI(_data, NFFT = 1024):    
    N = len(_data)
    width = _data.shape[1]
    n = NFFT
    _data = (np.vstack((np.zeros((n,width)), zmean(_data),np.zeros((n-N%n,width)))))
    # w = signal.windows.chebwin(n, 100).reshape((n,1))
    # y = np.zeros_like(_data, dtype=complex)
    # for ii in range(0, len(_data)-n, n//2):
    #     Y = _data[ii:ii+n,:]*w
    #     k =  (1j*2*pi*fftfreq(len(Y), dt).reshape((n,1)))
    #     y[ii:ii+n,:] = (ifft(np.vstack((np.zeros((1,width)),fft(Y, axis=0)[1:]/(k[1:]))), axis=0))
    # _datai = zmean(np.real(y))
    _datai = zmean(integ(_data))
    # return _datai[n:N+n]
    _dataI = np.zeros_like(_datai)
    for ii in range(0, len(_data)-n, n):
        for jj in range(width):
            F0 = featExt(_datai[ii:ii+n,jj])
            eemd = EEMD(noise_width=0.15)
            eIMFs = eemd.eemd(_datai[ii:ii+n,jj]).T
            F = []
            for kk in range(eIMFs.shape[1]):
                F.append(featExt(eIMFs[:,kk]))
            nn = norm(np.array(F)**2-F0, axis=1).argmin()
            _dataI[ii:ii+n,jj] = eIMFs[:,nn]
    return _dataI[n:N+n]  
Ejemplo n.º 9
0
    def test_eemd_simpleRun():
        T = np.linspace(0, 1, 100)
        S = np.sin(2*np.pi*T)

        config = {"processes": 1}
        eemd = EEMD(trials=10, max_imf=1, **config)
        eemd.EMD.FIXE_H = 5
        eemd.eemd(S)
Ejemplo n.º 10
0
 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)
Ejemplo n.º 11
0
    def test_imfs_and_residue_accessor(self):
        S = np.random.random(100)
        eemd = EEMD(trials=5, max_imf=2, parallel=False)
        eIMFs = eemd(S)

        imfs, residue = eemd.get_imfs_and_residue()
        self.assertEqual(eIMFs.shape[0], imfs.shape[0],
                         "Compare number of components")
        self.assertEqual(len(residue), 100, "Check if residue exists")
Ejemplo n.º 12
0
    def extract_imfs(self, signal):
        eemd = EEMD()
        eemd.eemd(signal)
        res = eemd.get_imfs_and_residue()
        imfs = list(res)[0]
        # drop the noise/ high frequency imfs, may incur index error due to the signal is too simple
        imfs_left = imfs[-1:]

        return imfs_left # np.array type
def main():

    #load data

    e = exchange.Exchange('../lib/binance.db')

    start = int(datetime.datetime(2018, 7, 1).timestamp() * 1000)
    #end = int(datetime.datetime(2018, 8, 1).timestamp() * 1000)
    end = int(datetime.datetime(2019, 7, 1).timestamp() * 1000)

    print('Loading order data...')

    number_of_orders, prices = e.get_total_orders_ts('BTCUSDT',
                                                     24 * 60 * 60 * 1000,
                                                     start, end)  #hourly data

    print('done')

    buy_orders = np.array([b for s, b in number_of_orders])
    sell_orders = np.array([s for s, b in number_of_orders])

    t = [i for i, o in enumerate(buy_orders)]

    eemd = EEMD()
    emd = eemd.EMD

    eIMFs_buys = eemd.eemd(buy_orders)
    eIMFs_sells = eemd.eemd(sell_orders)

    if eIMFs_buys.shape[0] != eIMFs_sells.shape[0]:
        print('size mismatch')

    n = min(eIMFs_buys.shape[0], eIMFs_sells.shape[0])

    fig, axs = plt.subplots(3, figsize=(12, 9), sharex=True)

    axs[0].plot(prices)
    axs[0].set_ylabel('Price')

    buys = np.sum(eIMFs_buys[1:-2], axis=0)
    sells = np.sum(eIMFs_sells[1:-2], axis=0)

    axs[1].plot(buys, color='g')
    axs[1].plot(sells, color='r')

    axs[2].plot(calculate_returns(prices), color='b')

    ax3 = axs[2].twinx()
    ax3.plot((0, len(prices)), (0.5, 0.5))
    ax3.plot(buys - sells)

    plt.xlabel("Time /days")

    #plt.tight_layout()

    plt.show()
Ejemplo n.º 14
0
    def test_eemd_simpleRun(self):
        T = np.linspace(0, 1, 100)
        S = np.sin(2 * np.pi * T)

        config = {"processes": 1}
        eemd = EEMD(trials=10, max_imf=1, **config)
        eemd.EMD.FIXE_H = 5
        eemd.eemd(S)

        self.assertTrue('pool' in eemd.__dict__)
Ejemplo n.º 15
0
    def test_eemd_notParallel(self):
        S = np.random.random(100)

        eemd = EEMD(trials=5, max_imf=2, parallel=False)
        eemd.EMD.FIXE_H = 2
        eIMFs = eemd.eemd(S)

        self.assertTrue(eIMFs.shape[0] > 0)
        self.assertTrue(eIMFs.shape[1], len(S))
        self.assertFalse('pool' in eemd.__dict__)
Ejemplo n.º 16
0
def hht(data, time, freqsol=33, timesol=50):
    #   freqsol give frequency - axis resolution for hilbert - spectrum
    #   timesol give time - axis resolution for hilbert - spectrum
    t0 = time[0]
    t1 = time[-1]
    dt = (t1 - t0) / (len(time) - 1)

    eemd = EEMD()
    imfs = eemd.eemd(data)
    freq, amp = FAhilbert(imfs, dt)

    #     fw0 = np.min(np.min(freq)) # maximum frequency
    #     fw1 = np.max(np.max(freq)) # maximum frequency

    #     if fw0 <= 0:
    #         fw0 = np.min(np.min(freq[freq > 0])) # only consider positive frequency

    #     fw = fw1-fw0
    tw = t1 - t0

    bins = np.linspace(0, 12, freqsol)  #np.logspace(0, 10, freqsol, base=2.0)
    p = np.digitize(freq, 2**bins)
    t = np.ceil((timesol - 1) * (time - t0) / tw)
    t = t.astype(int)

    hilbert_spectrum = np.zeros([timesol, freqsol])
    for i in range(len(time)):
        for j in range(imfs.shape[0] - 1):
            if p[i, j] >= 0 and p[i, j] < freqsol:
                hilbert_spectrum[t[i], p[i, j]] += amp[i, j]

    hilbert_spectrum = abs(hilbert_spectrum)
    fig1 = plt.figure(figsize=(5, 5))
    plot_imfs(data, imfs, time_samples=time, fig=fig1)

    fig2 = plt.figure(figsize=(5, 5))
    plot_frequency(data, freq.T, time_samples=time, fig=fig2)

    fig0 = plt.figure(figsize=(5, 5))
    ax = plt.gca()
    c = ax.contourf(
        np.linspace(t0, t1, timesol), bins, hilbert_spectrum.T
    )  #, colors=('whites','lategray','navy','darkgreen','gold','red')
    ax.invert_yaxis()
    ax.set_yticks(np.linspace(1, 11, 11))
    Yticks = [float(math.pow(2, p))
              for p in np.linspace(1, 11, 11)]  # make 2^periods
    ax.set_yticklabels(Yticks)
    ax.set_xlabel('Time', fontsize=8)
    ax.set_ylabel('Period', fontsize=8)
    position = fig0.add_axes([0.2, 0.05, 0.6, 0.01])
    cbar = plt.colorbar(c, cax=position, orientation='horizontal')
    cbar.set_label('Power')
    plt.show()
Ejemplo n.º 17
0
def x_eemd(x):
    """
    eemd变换
    :param x: 代表采样数据[m,n],m代表每个周期的样本,n代表采样点
    :return: 返回每个样本IMF分量,[m,IMF,n]
    """
    eemd = EEMD()
    emd = eemd.EMD
    emd.extrema_detection = "parabol"
    for i in range(x.shape[0]):
        eIMFs = eemd.eemd(x[i])
        print(eIMFs)
def main():

    #load data

    e = exchange.Exchange('../lib/binance.db')

    start = int(datetime.datetime(2018, 7, 1).timestamp() * 1000)
    end = int(datetime.datetime(2019, 7, 1).timestamp() * 1000)

    print('Loading order data...')

    number_of_orders, prices = e.get_total_orders_ts('BTCUSDT', 60 * 60 * 1000, start, end) #hourly data

    print('done')

    buy_orders  = np.array([b for s, b in number_of_orders])
    sell_orders = np.array([s for s, b in number_of_orders])

    t = [i for i, o in enumerate(buy_orders)]

    eemd = EEMD()
    emd = eemd.EMD

    eIMFs = eemd.eemd(buy_orders - sell_orders)
    n = eIMFs.shape[0]




    fig, axs = plt.subplots(n + 3, figsize=(12,9), sharex=True)

    axs[0].plot(prices)
    axs[0].set_ylabel('Price')

    axs[1].plot(buy_orders - sell_orders, color='g')
    axs[1].set_ylabel('Orders - (Buy - sell)')

    axs[2].plot(calculate_returns(prices))

    for i in range(n):

        axs[i + 3].plot(eIMFs[i], color='g')
        axs[i + 3].set_ylabel('eIMF ' + str(i + 1))


    plt.xlabel("Time /days")
    #plt.tight_layout()


    plt.show()
Ejemplo n.º 19
0
def eemd(signal):
    """
    eemd分解
    :param signal:采样信号
    :return:
    """
    # Assign EEMD to `eemd` variable
    eemd = EEMD()
    # Say we want detect extrema using parabolic method
    emd = eemd.EMD
    emd.extrema_detection = "parabol"
    # Execute EEMD on S
    eIMFs = eemd.eemd(S)
    return eIMFs
Ejemplo n.º 20
0
    def test_eemd_ensemble_stats(self):
        T = np.linspace(0, 2 * np.pi, 100)
        S = np.sin(T) + 3 * np.sin(3 * T + 0.1) + 0.2 * (T + 0.5) * (T - 2)
        eemd = EEMD(trials=20, separate_trends=True)

        eIMFs = eemd(S)
        self.assertEqual(type(eemd.all_imfs), dict,
                         "All imfs are stored as a dict")
        self.assertTrue(np.all(eIMFs == eemd.ensemble_mean()),
                        "eIMFs are the mean over ensemble")
        self.assertEqual(eemd.ensemble_count(),
                         [len(imfs) for imfs in eemd.all_imfs.values()])
        self.assertEqual(type(eemd.ensemble_std()), np.ndarray,
                         "Ensemble std exists and it's a numpy array")
Ejemplo n.º 21
0
    def test_eemd_passingCustomEMD(self):

        spline_kind = "linear"
        params = {"spline_kind": spline_kind}

        eemd = EEMD()
        self.assertFalse(eemd.EMD.spline_kind==spline_kind,
                "Not"+self.cmp_msg(eemd.EMD.spline_kind, spline_kind))

        from PyEMD import EMD

        emd = EMD(**params)

        eemd = EEMD(ext_EMD=emd)
        self.assertTrue(eemd.EMD.spline_kind==spline_kind,
                self.cmp_msg(eemd.EMD.spline_kind, spline_kind))
Ejemplo n.º 22
0
    def test_default_call_EEMD():
        T = np.arange(50)
        S = np.cos(T * 0.1)
        max_imf = 2

        eemd = EEMD()
        eemd(S, T, max_imf)
Ejemplo n.º 23
0
def Plot_IMF(obs, mod, site_id):
    print('Process on IMF ' + 'No.' + str(site_id) + '!')
    data = (obs.extractDatasites(lat=obs.lat, lon=obs.lat)).data[:, site_id]
    time = mod.time[~data.mask]
    y = (mod.extractDatasites(lat=obs.lat, lon=obs.lat)).data[:, site_id]
    time_y = mod.time[~y.mask]
    d_mod = []
    d_mod.append(y)
    fig1 = plt.figure(figsize=(4 * (len(d_mod) + 1), 8))
    fig2 = plt.figure(figsize=(4 * (len(d_mod) + 1), 8))
    fig3 = plt.figure(figsize=(5, 5))
    fig4 = plt.figure(figsize=(5, 5))

    fig1.subplots_adjust(wspace=0.5, hspace=0.3)
    fig2.subplots_adjust(wspace=0.5, hspace=0.3)

    eemd = EEMD(trials=5)
    imfs = eemd.eemd(data.compressed())
    fig3, freq = hht(data.compressed(), imfs, time, 1, fig3)
    if len(imfs) >= 1:
        fig1 = plot_imfs(data.compressed(),
                         imfs,
                         time_samples=time,
                         fig=fig1,
                         no=1,
                         m=len(d_mod))
        fig2 = plot_frequency(data.compressed(),
                              freq.T,
                              time_samples=time,
                              fig=fig2,
                              no=1,
                              m=len(d_mod))
    imfs2 = eemd.eemd(y.compressed())
    fig4, freq2 = hht(y.compressed(), imfs2, time_y, 1, fig4)
    if len(imfs) >= 1:
        fig1 = plot_imfs(y.compressed(),
                         imfs2,
                         time_samples=time_y,
                         fig=fig1,
                         no=2,
                         m=len(d_mod))
        fig2 = plot_frequency(y.compressed(),
                              freq2.T,
                              time_samples=time_y,
                              fig=fig2,
                              no=2,
                              m=len(d_mod))
Ejemplo n.º 24
0
 def eemd_decompose(a, t):
     eemd = EEMD(trials=200, noise_width=0.4)(a)
     eimfs, res = eemd[:-1], eemd[-1]  #这的参数有问题!!!!!!!!!!!!!!!!!!!!!
     vis = Visualisation()
     vis.plot_imfs(imfs=eimfs, residue=res, t=t, include_residue=True)
     vis.plot_instant_freq(t, imfs=eimfs)  #
     vis.show()
     return eimfs, res
Ejemplo n.º 25
0
def find_interval(signal, fs, imf_no=1):
    """
    Compute the interval setting for the TIV. 
    Calculating a hilbert transform from the instrinct mode functions (imfs).
    This is based on the hilbert-huang transform assuming non-stationarity of the given dataset.
    The function returns a suggested interval (most powerful frequency) based on the weighted average. 
    The weights are the calculated instantaneous energies. 
    
    Parameters
    ----------
    signal: 1d np.ndarray
        a one dimensional array which contains the brightness temperature (perturbation) of one pixel over time.
    fs: int 
        the fps which was used to record the imagery 
    imf_no: int (default 1)
        The imf which will be used to calculate the interval on. IMF 1 is the one with the highest frequency.
    Returns
    -------
    recommended_interval : float
        The found most powerful interval in float. Needs rounding to the next int.
    
    """
    eemd = EEMD()
    imfs = eemd.eemd(signal)
    imf = imfs[imf_no - 1, :]

    sig = hilbert(imf)

    energy = np.square(np.abs(sig))
    phase = np.arctan2(sig.imag, sig.real)
    omega = np.gradient(np.unwrap(phase))

    omega = fs / (2 * math.pi) * omega
    #omegaIdx = np.floor((omega-F[0])/FResol)+1;
    #freqIdx = 1/omegaIdx;

    insf = omega
    inse = energy

    rel_inse = inse / np.nanmax(inse)
    insf_weigthed_mean = np.average(insf, weights=rel_inse)
    insp = 1 / insf_weigthed_mean
    recommended_interval = np.round(fs * insp, 1)

    gc.collect()
    return (recommended_interval)
Ejemplo n.º 26
0
def ee(data, drawflag):
    data.shape = (len(data),)
    x = np.linspace(1, len(data), len(data))
    eemd = EEMD()
    # Say we want detect extrema using parabolic method
    emd = eemd.EMD
    emd.extrema_detection = "parabol"
    print(colored("decomposing - EEmd mode...", 'green'))
    imfs = eemd.eemd(data, x)
    if drawflag == 1:
        size = imfs.shape
        plt.figure(figsize=(20, 18))
        for loop in range(1, size[0]+1):
            plt.subplot(size[0], 1, loop)
            plt.plot(x, imfs[loop-1])
            plt.title(loop)
        plt.show()
    return imfs
Ejemplo n.º 27
0
    def test_separate_trends(self):
        T = np.linspace(0, 2 * np.pi, 100)
        S = np.sin(T) + 3 * np.sin(3 * T + 0.1) + 0.2 * (T + 0.5) * (T - 2)
        eemd = EEMD(trials=20, separate_trends=True)

        eIMFs = eemd(S)
        for imf in eIMFs[:-1]:
            self.assertLess(abs(imf.mean()), 0.5)
        self.assertGreaterEqual(eIMFs[-1].mean(), 1)
Ejemplo n.º 28
0
def emd(signal):
    emd_cls = EEMD()
    imfs = emd_cls(signal)
    vkur = np.zeros(len(signal))
    temp = [imf for imf in imfs if stats.kurtosis(imf) > 0]
    for imf in temp:
        vkur += imf
    hbSignal = abs(fftpack.hilbert(vkur))

    return hbSignal
Ejemplo n.º 29
0
    def test_eemd_noiseSeed(self):
        T = np.linspace(0, 1, 100)
        S = np.sin(2 * np.pi * T + 4**T) + np.cos((T - 0.4)**2)

        # Compare up to machine epsilon
        cmpMachEps = lambda x, y: np.abs(x - y) <= 2 * np.finfo(x.dtype).eps

        config = {"processes": 1}
        eemd = EEMD(trials=10, **config)

        # First run random seed
        eIMF1 = eemd(S)

        # Second run with defined seed, diff than first
        eemd.noise_seed(12345)
        eIMF2 = eemd(S)

        # Extremly unlikely to have same seed, thus different results
        msg_false = "Different seeds, expected different outcomes"
        if eIMF1.shape == eIMF2.shape:
            self.assertFalse(np.all(cmpMachEps(eIMF1, eIMF2)), msg_false)

        # Third run with same seed as with 2nd
        eemd.noise_seed(12345)
        eIMF3 = eemd(S)

        # Using same seeds, thus expecting same results
        msg_true = "Used same seed, expected same results"
        self.assertTrue(np.all(cmpMachEps(eIMF2, eIMF3)), msg_true)
Ejemplo n.º 30
0
    def emdT(signal, t):
        from PyEMD import EEMD
        import numpy as np
        import pylab as plt
        # Define signal

        # Assign EEMD to `eemd` variable
        eemd = EEMD()
        # Say we want detect extrema using parabolic method
        emd = eemd.EMD
        emd.extrema_detection = "simple"
        # Execute EEMD on S
        S = signal[0][:]
        S = S[20000:25000]
        t = t[20000:25000]

        eIMFs = eemd.eemd(S, t)
        nIMFs = eIMFs.shape[0]
        # Plot results
        plt.figure(figsize=(20, 12))
        plt.subplot(nIMFs + 1, 1, 1)
        plt.subplots_adjust(hspace=0.01)
        plt.xticks([])
        plt.plot(t, S, color='black')
        for n in range(nIMFs):
            if n < 7:
                plt.subplot(nIMFs + 1, 1, n + 2)
                plt.plot(t, eIMFs[n], color='black')
                plt.ylabel("eIMF %i" % (n + 1))
                plt.locator_params(axis='y', nbins=2)
                plt.xticks([])
            elif n == 7:
                plt.subplot(nIMFs + 1, 1, n + 2)
                plt.plot(t, eIMFs[n], color='black')
                plt.ylabel("eIMF %i" % (n + 1))
                plt.locator_params(axis='y', nbins=2)

        plt.xlabel("Time [s]")
        plt.show()
Ejemplo n.º 31
0
def prepare_data():
    con = engine.connect()
    # con.execute("truncate DOdataPrecictOnly")
    # con.execute("INSERT INTO DOdataPrecictOnly(Date,`Dissolved Oxygen`) ( SELECT Date,`Dissolved Oxygen` FROM DOdata order by Date ASC)")
    rv = con.execute("select `Dissolved Oxygen` from DOdataPrecictOnly")

    do = []
    for i in rv:
        print(i)
        do.append(i[0])

    DO = []
    for i in range(0, len(do)):
        DO.append([do[i]])
    scaler_DO = MinMaxScaler(feature_range=(0, 1))
    DO = scaler_DO.fit_transform(DO)
    # DO = isolutionforest(DO)

    eemd = EEMD()
    eemd.noise_seed(12345)
    imfs = eemd.eemd(DO.reshape(-1), None, 8)
    con.close()

    return imfs, scaler_DO
Ejemplo n.º 32
0
    def test_eemd_unsupportedNoiseKind(self):
        noise_kind = "whoever_supports_this_is_wrong"
        eemd = EEMD(noise_kind=noise_kind)

        with self.assertRaises(ValueError):
            eemd.generate_noise(1., 100)
Ejemplo n.º 33
0
from PyEMD import EEMD
import numpy as np
import pylab as plt

# Define signal
t = np.linspace(0, 1, 200)

sin = lambda x,p: np.sin(2*np.pi*x*t+p)
S = 3*sin(18,0.2)*(t-0.2)**2
S += 5*sin(11,2.7)
S += 3*sin(14,1.6)
S += 1*np.sin(4*2*np.pi*(t-0.8)**2)
S += t**2.1 -t

# Assign EEMD to `eemd` variable
eemd = EEMD()

# Say we want detect extrema using parabolic method
emd = eemd.EMD
emd.extrema_detection="parabol"

# Execute EEMD on S
eIMFs = eemd.eemd(S, t)
nIMFs = eIMFs.shape[0]

# Plot results
plt.figure(figsize=(12,9))
plt.subplot(nIMFs+1, 1, 1)
plt.plot(t, S, 'r')

for n in range(nIMFs):