Exemplo n.º 1
0
def get_imfs(signal):
    """"
    Return the imf of a signal
    """
    decomposer = EMD(signal)
    imf = decomposer.decompose()
    return imf
Exemplo n.º 2
0
def plot_imf(signal):
    decomposer = EMD(signal)
    imfs = decomposer.decompose()
    m = len(signal)
    x = np.linspace(0,1,m)
    pyhht.plot_imfs(x, imfs)
    plt.show()
Exemplo n.º 3
0
def get_imfs(signal):
	try:
		# decomposer_signal = EMD(signal, fixe=100, n_imfs=2)
		decomposer_signal = EMD(signal)
		imfs = decomposer_signal.decompose()
		if len(imfs) < 2:
			print("imfs {} +++++++++++++++++++++++++++++++++++++++".format(len(imfs)))
			raise ValueError("imfs {}".format(len(imfs)))
		return imfs[:2]
	except Exception as e:
		raise e
Exemplo n.º 4
0
def process_window(filename, eeg, stage, step):
    # plt.figure()
    s = np.zeros((5, 2501))
    print('step: ', step)
    # t = np.linspace(step*fs*30,step*fs*30+fs*10,fs*10)
    decomposer = EMD(eeg[step * fs * window_len:step * fs * window_len +
                         fs * sample_time])
    imfs = decomposer.decompose()
    # print(len(imfs))
    # plot_imfs(eeg[step*fs*30:step*fs*30+fs*10], imfs, t)
    for imf in imfs:
        analytic_signal = hilbert(imf)
        instantaneous_phase = np.unwrap(np.angle(analytic_signal))
        instantaneous_freq = (np.diff(instantaneous_phase) / (2.0 * np.pi) *
                              fs)
        # print(len(instantaneous_freq))
        for i in range(len(instantaneous_freq)):
            if instantaneous_freq[i] > 1 and instantaneous_freq[i] <= 4:
                s[0][i] += imf[i]
            elif instantaneous_freq[i] > 4 and instantaneous_freq[i] <= 8:
                s[1][i] += imf[i]
            elif instantaneous_freq[i] > 8 and instantaneous_freq[i] <= 12:
                s[2][i] += imf[i]
            elif instantaneous_freq[i] > 12 and instantaneous_freq[i] <= 30:
                s[3][i] += imf[i]
            elif instantaneous_freq[i] > 30 and instantaneous_freq[i] <= 60:
                s[4][i] += imf[i]

    for i in range(5):
        if stage == 'W':
            s[i][-1] = 0
        else:
            s[i][-1] = 1

    # save np array
    Path('./delta').mkdir(parents=True, exist_ok=True)
    Path('./theta').mkdir(parents=True, exist_ok=True)
    Path('./alpha').mkdir(parents=True, exist_ok=True)
    Path('./beta').mkdir(parents=True, exist_ok=True)
    Path('./gamma').mkdir(parents=True, exist_ok=True)

    np.save('./delta/' + filename + '_' + str(step) + '_delta', s[0])
    np.save('./theta/' + filename + '_' + str(step) + '_theta', s[1])
    np.save('./alpha/' + filename + '_' + str(step) + '_alpha', s[2])
    np.save('./beta/' + filename + '_' + str(step) + '_beta', s[3])
    np.save('./gamma/' + filename + '_' + str(step) + '_gamma', s[4])

    pass
Exemplo n.º 5
0
from datetime import datetime
import numpy as np
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.ensemble import AdaBoostRegressor, BaggingRegressor
import xgboost as xgb

np.random.seed(123)

ticker = 'SPY'
stock = pdr.get_data_yahoo(ticker.upper(),
                           start='2009-01-01',
                           end=str(datetime.now())[0:11])
stock = stock.Close
returns = np.log(stock).diff().dropna()

decomposer = EMD(returns)
imfs = decomposer.decompose()
#t = np.linspace(0, 1, len(returns))
#plot_imfs(returns, imfs, t)

imfs = imfs.T
imfs = pd.DataFrame(imfs)

series = returns[len(returns) - 2000:]
series = np.array(series)
series = series.reshape(-1, 1)

D = 4
T = 1
N = 2000
series = series[500:]
Exemplo n.º 6
0
from pyhht import EMD
from pyhht.visualization import plot_imfs
from scipy.signal import hilbert
from pyhht.utils import inst_freq
import matplotlib.pyplot as plt
import numpy as np

lon = []
lon = lon.crop(-0.5, 0.5)
signal = lon._data[5, 57, :]

decomposer = EMD(signal)
imfs = decomposer.decompose()
plot_imfs(signal, imfs, lon.times)
ht = hilbert(imfs)
plt.imshow(np.abs(ht), aspect='auto', origin='lower')


def hht(signal):
    decomposer = EMD(signal)
    imfs = decomposer.decompose()
    ht = hilbert(imfs)
    return imfs, ht
Exemplo n.º 8
0
    2 * np.pi * f[1] * x / Fs) + np.sin(2 * np.pi * f[2] * x / Fs) + np.sin(
        2 * np.pi * f[3] * x / Fs) + np.sin(2 * np.pi * f[4] * x / Fs)
plt.plot(y)
#ext1=y[argrelextrema(y, np.greater)[0]]
#min1=y[argrelextrema(y, np.less)[0]]
##f2 = interp1d(x, y, kind='cubic')
###for i in range(len(ext1)):
##
##
#cubicspline=CSP(x,y)
##plt.plot(f2);
#extarray=cubicspline(ext1);
#minarray=cubicspline(min1);
#larr=np.zeros(176);
#larr=larr+min1     ;
decomposer = EMD(y)
imfs = decomposer.decompose()
plot_imfs(y, imfs, x)
imf1 = []
for i in range(1000):
    imf1.append(imfs[0, i])

plt.subplot(2, 1, 1)
plt.plot(x, imf1)
plt.xlabel('IMF 1')
plt.ylabel('Amplitude')
plt.show()
imf2 = []
for i in range(1000):
    imf2.append(imfs[1, i])
Exemplo n.º 9
0
def detrend(y, x = None, method = "emd", sg_kwargs = None):
    """Detrend a timeseries according to four methods

    Detrending methods include, "linear", "constant", using a low-pass
        Savitzky-Golay filter, and using eigen mode decomposition (default).

    Parameters
    ----------

    y : array
       The series to be detrended.
    x : array
       The time axis for the timeseries. Necessary for use with
       the Savitzky-Golay filters method since the series should be evenly spaced.
    method : str
        The type of detrending:
        - linear: the result of a linear least-squares fit to y is subtracted from y.
        - constant: only the mean of data is subtrated.
        - "savitzky-golay", y is filtered using the Savitzky-Golay filters and the resulting filtered series is subtracted from y.
        - "emd" (default): Empirical mode decomposition. The last mode is assumed to be the trend and removed from the series
    sg_kwargs : dict
        The parameters for the Savitzky-Golay filters. see pyleoclim.utils.filter.savitzy_golay for details.

    Returns
    -------

    ys : array
        The detrended timeseries.

    See also
    --------

    pylecolim.utils.filter.savitzky_golay : Filtering using Savitzy-Golay

    pylecolim.utils.tsutils.preprocess : pre-processes a times series using standardization and detrending.

    """
    y = np.array(y)

    if x is not None:
        x = np.array(x)

    if method == "linear":
        ys = signal.detrend(y,type='linear')
    elif method == 'constant':
        ys = signal.detrend(y,type='constant')
    elif method == "savitzky-golay":
        # Check that the timeseries is uneven and interpolate if needed
        if x is None:
            raise ValueError("A time axis is needed for use with the Savitzky-Golay filter method")
        # Check whether the timeseries is unvenly-spaced and interpolate if needed
        if len(np.unique(np.diff(x)))>1:
            warnings.warn("Timeseries is not evenly-spaced, interpolating...")
            x_interp, y_interp = interp(x,y,bounds_error=False,fill_value='extrapolate')
        else:
            x_interp = x
            y_interp = y
        sg_kwargs = {} if sg_kwargs is None else sg_kwargs.copy()
        # Now filter
        y_filt = savitzky_golay(y_interp,**sg_kwargs)
        # Put it all back on the original x axis
        y_filt_x = np.interp(x,x_interp,y_filt)
        ys = y-y_filt_x
    elif method == "emd":
        imfs = EMD(y).decompose()
        if np.shape(imfs)[0] == 1:
            trend = np.zeros(np.size(y))
        else:
            trend = imfs[-1]
        ys = y - trend
    else:
        raise KeyError('Not a valid detrending method')

    return ys
Exemplo n.º 10
0
########################################################################

# Generate linear chirp (simple)
T = 1e-6
T = T
"""FM = LFM.chirp(Fs=Fs,T=T, fStart=40e3, fStop=60e3, nChirps=4, direction='up')
sig_t1 = np.real(FM.getSymbolSig(0))

FM = LFM.chirp(Fs=Fs,T=T, fStart=10e3, fStop=40e3, nChirps=4, direction='up')
sig_t2 = np.real(FM.getSymbolSig(1))

sig_t = sig_t1+sig_t2
t = np.linspace(-T/2, (T/2)-dt, len(sig_t))"""

decomposer = EMD(np.real(sig_t))
imfs = decomposer.decompose()
print('len(imfs)', len(imfs))

fig = plt.figure(figsize=(7, 5))
axs = fig.subplots(len(imfs) + 1, 1)
axs[0].plot(sig_t)
axs[0].set_yticklabels([])
axs[0].set_xticklabels([])
axs[0].set_ylabel('$\Re\{s(t)\}$')

for i in range(1, len(imfs) + 1):
    axs[i].plot(t, imfs[i - 1])
    axs[i].set_ylabel('I ' + str(i))
    axs[i].set_yticklabels([])
    if i < len(imfs):
Exemplo n.º 11
0
"""
Spyder Editor

This is a temporary script file.
"""

from pyhht import EMD
import numpy as np
import matplotlib.pyplot as plt

time = np.linspace(0, 1000, 1000)
a = np.sin(np.pi * 2 * time / 100)
b = np.sin(np.pi * 2 * time / 200)
data = a + b

exterma = EMD.exterma(data)
top, bot, mean = EMD.envelope(exterma[0], exterma[1], 1000)
#IMFs = EMD.emd(data)

# PLOT 1 SIGNAL
plt.figure(figsize=(20, 8))
plt.plot(time, data, 'black')
plt.gca().axes.get_xaxis().set_ticks([])
plt.gca().axes.get_yaxis().set_ticks([])
plt.savefig("/home/nabobalis/signal.svg", dpi=300, bbox_inches='tight')
# PLOT 2 EXTERAM POINTS

plt.figure(figsize=(20, 8))
plt.plot(time, data, 'black')
plt.scatter(exterma[0][0], exterma[0][1], c='red', s=250)
plt.scatter(exterma[1][0], exterma[1][1], c='green', s=250)
Exemplo n.º 12
0
def get_imfs_emd(signal):
    decomposer_signal = EMD(signal)
    return decomposer_signal.decompose()