def permu(d1, d2, d3, d4, d5):

    pd1 = []
    pd2 = []
    pd3 = []
    pd4 = []
    pd5 = []

    for i in range(0, 500):
        X = d1[i]
        print(i)
        pd1.append(entropy.permutation_entropy(X, 3, 1))
    for i in range(0, 500):
        X = d2[i]
        print(i)
        pd2.append(entropy.permutation_entropy(X, 3, 1))
    for i in range(0, 500):
        X = d3[i]
        print(i)
        pd3.append(entropy.permutation_entropy(X, 3, 1))
    for i in range(0, 500):
        X = d4[i]
        print(i)
        pd4.append(entropy.permutation_entropy(X, 3, 1))
    for i in range(0, 500):
        X = d5[i]
        print(i)
        pd5.append(entropy.permutation_entropy(X, 3, 1))

    return (pd1, pd2, pd3, pd4, pd5)
Esempio n. 2
0
def MsPE_n(time_series, delay, m_start=3, m_end=7, plotting=False):
    """This function returns a suitable embedding dimension, given a time series and embedding delay, based on the 
    dimenion normalized MsPE at the optimum delay for a range of dimensions n.

    Args:
       ts (array):  Time series (1d).
       delay (int):  Optimum delay from MsPE.
       m_start (int):  minimum dimension in dimension search. Default is 3.
       m_end (int):  maximum dimension in dimension search. Default is 8.
       
    Kwargs:
       plotting (bool): Plotting for user interpretation. defaut is False.

    Returns:
       (int): n, The embedding dimension for permutation formation.

    """
    from pyentrp import entropy as ent
    import numpy as np
    MnPE = []
    for m in range(m_start, m_end + 1):
        PE = ent.permutation_entropy(time_series, m, delay) / (np.log(2))
        NPE = PE / (m - 1)
        MnPE = np.append(MnPE, NPE)
    dim = np.argmax(MnPE)

    if plotting == True:
        D = delay
        MSPE = []
        MdoPE = []
        for delay in range(1, int(1.5 * D)):
            for m in range(m_start, m_end + 1):
                PE = ent.permutation_entropy(time_series, m, delay)
                NPE = PE / (m - 1)
                MSPE = np.append(MSPE, NPE)

            MdoPE = np.concatenate((MdoPE, MSPE), axis=0)
            MSPE = []
        MdoPE = MdoPE.reshape((int(1.5 * D) - 1, 1 + m_end - m_start)).T
        import matplotlib.pyplot as plt
        plt.figure(1)
        TextSize = 17
        plt.figure(figsize=(8, 3))
        for m in range(0, m_end - m_start + 1):
            plt.plot(np.linspace(1,
                                 int(1.5 * D) - 1, len(MdoPE[m])),
                     MdoPE[m],
                     label='n = ' + str(m + m_start),
                     linewidth=2)
        plt.plot([D, D], [0, 1.3], 'r--')
        plt.xticks(size=TextSize)
        plt.yticks(size=TextSize)
        plt.ylabel(r'$H/(n-1)$', size=TextSize)
        plt.xlabel(r'$\tau$', size=TextSize)
        plt.legend(loc='lower right', borderaxespad=0.)
        plt.show()

    return dim + m_start
Esempio n. 3
0
def n_op(time_series, delay):
    """This function returns a suitable embedding dimension, given a time series, based on the multi-scale permutation entropy algorithm.

    Args:
       delay (int): dimension n from the method of multi-scale permutation entropy.
       ts (array):  Time series array (1d).

    Returns:
       (int): n, The embedding dimension for permutation formation.

    """

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    import networkx as nx
    from scipy import sparse
    from ripser import ripser
    from pyentrp import entropy as ent
    import numpy as np

    #returns an embedding dimenion suitable based on maximum permutation entropy per symbol
    m_start, m_end = 3, 7

    MnPE = []
    for m in range(m_start, m_end + 1):
        PE = ent.permutation_entropy(time_series, m, delay) / (np.log(2))
        NPE = PE / (m - 1)
        MnPE = np.append(MnPE, NPE)
    dim = np.argmax(MnPE)
    return dim + m_start
Esempio n. 4
0
def PE(ts, n=5, tau=10, normalize=False):
    """This function takes a time series and calculates Permutation Entropy (PE).
    
    Args:
       ts (array):  Time series (1d).
       n (int): Permutation dimension. Default is 5.
       tau (int): Permutation delay. Default is 10.
       
    Kwargs:
       normalize (bool): Normalizes the permutation entropy on scale from 0 to 1. defaut is False.

    Returns:
       (float): PE, the permutation entropy.

    """
    from pyentrp import entropy as ent
    import math
    import numpy as np

    PE = ent.permutation_entropy(ts, n, tau)
    ME = 1
    if normalize == True: ME = np.log2(math.factorial(n))
    PE = PE / ME

    return PE
Esempio n. 5
0
 def test_permutationEntropy(self):
     self.assertEqual(
         np.round(
             ent.permutation_entropy(PERM_ENTROPY_BANDT, order=2, delay=1),
             3), 0.918)
     self.assertEqual(
         np.round(
             ent.permutation_entropy(PERM_ENTROPY_BANDT, order=3, delay=1),
             3), 1.522)
     # Assert that a fully random vector has an entropy of 0.99999...
     self.assertEqual(
         np.round(
             ent.permutation_entropy(RANDOM_TIME_SERIES,
                                     order=3,
                                     delay=1,
                                     normalize=True), 3), 0.999)
def permu(d1):
    pd1 = []
    print("Permutation started")
    for i in range(d1.shape[0]):
        X = d1[i]
        pd1.append(entropy.permutation_entropy(X, 3, 1))
    print("Permutation Finished")
    return (pd1)
Esempio n. 7
0
def perm_entrp(l):
    """
    Permutation entropy
    :param l:
    :return:
    """
    start = time.time()
    se = e.permutation_entropy(l)
    elapsed_time = time.time() - start
    logger.debug("Elapsed time to calculate Permutation entropy value is %s",
                 elapsed_time)
    return se
Esempio n. 8
0
def extract_feature(X):
    X = X.astype(float)
    stft = np.abs(librosa.stft(X))
    mfccs = np.mean(librosa.feature.mfcc(y=X, sr=SAMPLE_RATE, n_mfcc=40).T,
                    axis=0)
    chroma = np.mean(librosa.feature.chroma_stft(S=stft, sr=SAMPLE_RATE).T,
                     axis=0)
    mel = np.mean(librosa.feature.melspectrogram(X, sr=SAMPLE_RATE).T, axis=0)
    shannon = [ent.shannon_entropy(X)]
    sample = ent.sample_entropy(X, 1)
    per = [ent.permutation_entropy(X)]
    fft = np.fft.fft(X) / len(X)
    fft = np.abs(fft[:len(X) // 7])
    fft = [fft[0]]
    return mfccs, chroma, mel, shannon, sample, per, fft
Esempio n. 9
0
def permutation_entropy(signal_df, channels):
    '''
    Calculate permutation entropy of sensor signals.

    :param signal_df: dataframe housing desired sensor signals
    :param channels: channels of signal to measure permutation entropy
    :return: dataframe of calculated permutation entropy for each signal channel
    '''
    from pyentrp import entropy as ent
    permutation_entropy_df = pd.DataFrame()

    for channel in channels:
        current_perm_ent = ent.permutation_entropy(signal_df[channel], 4, 1)
        permutation_entropy_df[channel +
                               '_permutation_entropy'] = [current_perm_ent]

    return permutation_entropy_df
Esempio n. 10
0
def MsPE(ts, n=5, delay_end=200, plotting=False, normalize=False):
    """This function takes a time series and calculates Multi-scale Permutation Entropy (MsPE) 
        over multiple time scales
    
    Args:
       ts (array):  Time series (1d).
       n (int): Permutation dimension. Default is 5.
       delay_end (int): maximum delay in search. default is 200.
       
    Kwargs:
       plotting (bool): Plotting for user interpretation. defaut is False.
       normalize (bool): Normalizes the permutation entropy on scale from 0 to 1. defaut is False.

    Returns:
       (array): MsPE, the permutation entropy over multiple time scales.

    """
    from pyentrp import entropy as ent
    import math
    import numpy as np

    MSPE = []
    delays = []
    m = n
    for delay in np.arange(1, delay_end):
        PE = ent.permutation_entropy(ts, m, delay)
        ME = 1
        if normalize == True: ME = np.log2(math.factorial(n))
        PE = PE / ME
        MSPE = np.append(MSPE, PE)
        delays.append(delay)

    if plotting == True:
        import matplotlib.pyplot as plt
        plt.figure(2)
        TextSize = 17
        plt.figure(figsize=(8, 3))
        plt.plot(delays, MSPE, marker='.')
        plt.xticks(size=TextSize)
        plt.yticks(size=TextSize)
        plt.ylabel(r'$h(3)$', size=TextSize)
        plt.xlabel(r'$\tau$', size=TextSize)
        plt.show()
    return delays, MSPE
def extract_feature(X):
    X = X.astype(float)
    stft = np.abs(librosa.stft(X))
    mfccs = np.mean(librosa.feature.mfcc(y=X, sr=SAMPLE_RATE, n_mfcc=40).T,
                    axis=0)
    chroma = np.mean(librosa.feature.chroma_stft(S=stft, sr=SAMPLE_RATE).T,
                     axis=0)
    mel = np.mean(librosa.feature.melspectrogram(X, sr=SAMPLE_RATE).T, axis=0)
    shannon = [ent.shannon_entropy(X)]
    sample = ent.sample_entropy(X, 1)
    spectral = [np.round(spectral_entropy(X, SAMPLE_RATE), 2)]
    per = [ent.permutation_entropy(X)]
    energy_ent = [energy_entropy(X)]
    energy_sig = [energy(X)]
    zero_cross = [zero_crossing_rate(X)]
    f, psd = welch(X, nfft=1024, fs=SAMPLE_RATE, noverlap=896, nperseg=1024)
    fft = np.fft.fft(X) / len(X)
    fft = np.abs(fft[:len(X) // 7])
    fft = [fft[0]]

    return np.concatenate(
        (mfccs, chroma, mel, shannon, sample, spectral, per, energy_ent,
         energy_sig, zero_cross, psd, chroma, fft))
Esempio n. 12
0
hurst = m[0]*2.0
hurst

#farctal dimension (correlation dimension)= slope of the line fitted to log(r) vs log(C(r))
# If the correlation dimension is constant for all ‘m’ the time series will be deterministic
#if the correlation exponentincreases with increase in ‘m’ the time series will be stochastic.
h01 = nolds.corr_dim(F,2,debug_plot=True)
h01

#lyap_r = estimate largest lyapunov exponent
h1=nolds.lyap_r(F,emb_dim=2,debug_plot=True)
h1

#lyap_e = estimate whole spectrum of lyapunov exponents
h2=nolds.lyap_e(F)
h2

from pyentrp import entropy as ent
T1=np.std(F)
T1
k= 0.2*T1
k

#sample entropy
h = nolds.sampen(F,3,tolerance=k)
h

#permutation entropy
h2=ent.permutation_entropy(F,order=3,normalize=True)
h2
Esempio n. 13
0
 def basicalPE1D(self, normalize, order=3, delay=1):
     PEnt = np.zeros(self.length)
     for i in range(self.length):
         tempStr = self.base[i]
         PEnt[i] = ent.permutation_entropy(tempStr, order, delay, normalize)
     return (PEnt)
Esempio n. 14
0
    def calculate_rri_nonlinear_statistics(self,
                                           rri,
                                           diff_rri,
                                           diff2_rri,
                                           suffix=''):

        # Empty dictionary
        rri_nonlinear_statistics = dict()

        # Non-linear RR statistics
        if len(rri) > 1:
            rri_nonlinear_statistics['rri_approximate_entropy' + suffix] = \
                self.safe_check(pyeeg.ap_entropy(rri, M=2, R=0.1*np.std(rri)))
            rri_nonlinear_statistics['rri_sample_entropy' + suffix] = \
                self.safe_check(ent.sample_entropy(rri, sample_length=2, tolerance=0.1*np.std(rri))[0])
            rri_nonlinear_statistics['rri_multiscale_entropy' + suffix] = \
                self.safe_check(ent.multiscale_entropy(rri, sample_length=2, tolerance=0.1*np.std(rri))[0])
            rri_nonlinear_statistics['rri_permutation_entropy' + suffix] = \
                self.safe_check(ent.permutation_entropy(rri, m=2, delay=1))
            rri_nonlinear_statistics['rri_multiscale_permutation_entropy' + suffix] = \
                self.safe_check(ent.multiscale_permutation_entropy(rri, m=2, delay=1, scale=1)[0])
            rri_nonlinear_statistics['rri_fisher_info' + suffix] = fisher_info(
                rri, tau=1, de=2)
            hjorth_parameters = hjorth(rri)
            rri_nonlinear_statistics['rri_activity' +
                                     suffix] = hjorth_parameters[0]
            rri_nonlinear_statistics['rri_complexity' +
                                     suffix] = hjorth_parameters[1]
            rri_nonlinear_statistics['rri_morbidity' +
                                     suffix] = hjorth_parameters[2]
            rri_nonlinear_statistics['rri_hurst_exponent' + suffix] = pfd(rri)
            rri_nonlinear_statistics['rri_svd_entropy' + suffix] = svd_entropy(
                rri, tau=2, de=2)
            rri_nonlinear_statistics['rri_petrosian_fractal_dimension' +
                                     suffix] = pyeeg.pfd(rri)
        else:
            rri_nonlinear_statistics['rri_approximate_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['rri_sample_entropy' + suffix] = np.nan
            rri_nonlinear_statistics['rri_multiscale_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['rri_permutation_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['rri_multiscale_permutation_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['rri_fisher_info' + suffix] = np.nan
            rri_nonlinear_statistics['rri_activity' + suffix] = np.nan
            rri_nonlinear_statistics['rri_complexity' + suffix] = np.nan
            rri_nonlinear_statistics['rri_morbidity' + suffix] = np.nan
            rri_nonlinear_statistics['rri_hurst_exponent' + suffix] = np.nan
            rri_nonlinear_statistics['rri_svd_entropy' + suffix] = np.nan
            rri_nonlinear_statistics['rri_petrosian_fractal_dimension' +
                                     suffix] = np.nan

        # Non-linear RR difference statistics
        if len(diff_rri) > 1:
            rri_nonlinear_statistics['diff_rri_approximate_entropy' + suffix] = \
                self.safe_check(pyeeg.ap_entropy(diff_rri, M=2, R=0.1*np.std(rri)))
            rri_nonlinear_statistics['diff_rri_sample_entropy' + suffix] = \
                self.safe_check(ent.sample_entropy(diff_rri, sample_length=2, tolerance=0.1*np.std(rri))[0])
            rri_nonlinear_statistics['diff_rri_multiscale_entropy' + suffix] = \
                self.safe_check(ent.multiscale_entropy(diff_rri, sample_length=2, tolerance=0.1*np.std(rri))[0])
            rri_nonlinear_statistics['diff_rri_permutation_entropy' + suffix] = \
                self.safe_check(ent.permutation_entropy(diff_rri, m=2, delay=1))
            rri_nonlinear_statistics['diff_rri_multiscale_permutation_entropy' + suffix] = \
                self.safe_check(ent.multiscale_permutation_entropy(diff_rri, m=2, delay=1, scale=1)[0])
            rri_nonlinear_statistics['diff_rri_fisher_info' +
                                     suffix] = fisher_info(diff_rri,
                                                           tau=1,
                                                           de=2)
            hjorth_parameters = hjorth(diff_rri)
            rri_nonlinear_statistics['diff_rri_activity' +
                                     suffix] = hjorth_parameters[0]
            rri_nonlinear_statistics['diff_rri_complexity' +
                                     suffix] = hjorth_parameters[1]
            rri_nonlinear_statistics['diff_rri_morbidity' +
                                     suffix] = hjorth_parameters[2]
            rri_nonlinear_statistics['diff_rri_hurst_exponent' +
                                     suffix] = pfd(diff_rri)
            rri_nonlinear_statistics['diff_rri_svd_entropy' +
                                     suffix] = svd_entropy(diff_rri,
                                                           tau=2,
                                                           de=2)
            rri_nonlinear_statistics['diff_rri_petrosian_fractal_dimension' +
                                     suffix] = pyeeg.pfd(diff_rri)
        else:
            rri_nonlinear_statistics['diff_rri_approximate_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['diff_rri_sample_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['diff_rri_multiscale_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['diff_rri_permutation_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['diff_rri_multiscale_permutation_entropy'
                                     + suffix] = np.nan
            rri_nonlinear_statistics['diff_rri_fisher_info' + suffix] = np.nan
            rri_nonlinear_statistics['diff_rri_activity' + suffix] = np.nan
            rri_nonlinear_statistics['diff_rri_complexity' + suffix] = np.nan
            rri_nonlinear_statistics['diff_rri_morbidity' + suffix] = np.nan
            rri_nonlinear_statistics['diff_rri_hurst_exponent' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['diff_rri_svd_entropy' + suffix] = np.nan
            rri_nonlinear_statistics['diff_rri_petrosian_fractal_dimension' +
                                     suffix] = np.nan

        # Non-linear RR difference difference statistics
        if len(diff2_rri) > 1:
            rri_nonlinear_statistics['diff2_rri_shannon_entropy' + suffix] = \
                self.safe_check(ent.shannon_entropy(diff2_rri))
            rri_nonlinear_statistics['diff2_rri_approximate_entropy' + suffix] = \
                self.safe_check(pyeeg.ap_entropy(diff2_rri, M=2, R=0.1*np.std(rri)))
            rri_nonlinear_statistics['diff2_rri_sample_entropy' + suffix] = \
                self.safe_check(ent.sample_entropy(diff2_rri, sample_length=2, tolerance=0.1*np.std(rri))[0])
            rri_nonlinear_statistics['diff2_rri_multiscale_entropy' + suffix] = \
                self.safe_check(ent.multiscale_entropy(diff2_rri, sample_length=2, tolerance=0.1*np.std(rri))[0])
            rri_nonlinear_statistics['diff2_rri_permutation_entropy' + suffix] = \
                self.safe_check(ent.permutation_entropy(diff2_rri, m=2, delay=1))
            rri_nonlinear_statistics['diff2_rri_multiscale_permutation_entropy' + suffix] = \
                self.safe_check(ent.multiscale_permutation_entropy(diff2_rri, m=2, delay=1, scale=1)[0])
            rri_nonlinear_statistics['diff2_rri_fisher_info' +
                                     suffix] = fisher_info(diff2_rri,
                                                           tau=1,
                                                           de=2)
            hjorth_parameters = hjorth(diff2_rri)
            rri_nonlinear_statistics['diff2_rri_activity' +
                                     suffix] = hjorth_parameters[0]
            rri_nonlinear_statistics['diff2_rri_complexity' +
                                     suffix] = hjorth_parameters[1]
            rri_nonlinear_statistics['diff2_rri_morbidity' +
                                     suffix] = hjorth_parameters[2]
            rri_nonlinear_statistics['diff2_rri_hurst_exponent' +
                                     suffix] = pfd(diff2_rri)
            rri_nonlinear_statistics['diff2_rri_svd_entropy' +
                                     suffix] = svd_entropy(diff2_rri,
                                                           tau=2,
                                                           de=2)
            rri_nonlinear_statistics['diff2_rri_petrosian_fractal_dimension' +
                                     suffix] = pyeeg.pfd(diff2_rri)
        else:
            rri_nonlinear_statistics['diff2_rri_shannon_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_approximate_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_sample_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_multiscale_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_permutation_entropy' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_multiscale_permutation_entropy'
                                     + suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_fisher_info' + suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_activity' + suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_complexity' + suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_morbidity' + suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_hurst_exponent' +
                                     suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_svd_entropy' + suffix] = np.nan
            rri_nonlinear_statistics['diff2_rri_petrosian_fractal_dimension' +
                                     suffix] = np.nan

        return rri_nonlinear_statistics
Esempio n. 15
0
df_ = pd.DataFrame(rolling)

sw_1 = rolling[1]
sw_1_ns = rolling[1]
nolds.lyap_r(sw_1, emb_dim = emb_dim)
nolds.lyap_e(sw_1, emb_dim = emb_dim)
nolds.sampen(sw_1, emb_dim= emb_dim)
nolds.hurst_rs(sw_1)
nolds.corr_dim(sw_1, emb_dim=emb_dim)
nolds.dfa(sw_1)
ent.shannon_entropy(sw_1) # is this even valid? we do not have any p_i states i ALSO IGNORES TEMPORAL ORDER - Practical consideration of permutation entropy
ent.sample_entropy(sw_1, sample_length = 10) #what is sample length?
#ent.multiscale_entropy(sw_1, sample_length = 10, tolerance = 0.1*np.std(sw_1)) # what is tolerance?

                      "Practical considerations of permutation entropy: A Tutorial review - how to choose parameters in permutation entropy"
ent.permutation_entropy(sw_1, m=8, delay = emd_dim )  #Reference paper above 
#ent.composite_multiscale_entropy()
lempel_ziv_complexity(sw_1)
gzip_compress_ratio(sw_1_ns, 9)


#https://www.researchgate.net/post/How_can_we_find_out_which_value_of_embedding_dimensions_is_more_accurate
#when choosing emb_dim for Takens, each dimension should have at least 10 dp ==> 10^1 == 1D, 10^2 == 2D, ..., 10^6 == 6D 

#FALSE NEAREST NEIGHBOR FOR DETERMINING MINIMAL EMBEDDING DIMENSION

#MEASURES OF COMPLEXITY
# https://hackaday.io/project/707-complexity-of-a-time-series

# general entropy with discrete pdf - [H = sum_i - p_i * log( p_i)] , we cannot use because we have not well defined states
# Approximate entropy 
Esempio n. 16
0
def get_features(x_,fs_):

    a_,psd_=get_psd_ama(x_,fs_)
    psd_=psd_/np.sum(psd_)
    b = np.where(a_<0.25) 
    feat_1 = psd_[b]
    feat_1 = np.sum(feat_1)
  
    c = np.where((a_ >0.25) & (a_<0.5))
    feat_2 = psd_[c]
    feat_2 = np.sum(feat_2)

    d = np.where((a_ >0.5) & (a_<1.5))
    feat_3 = psd_[d]
    feat_3 = np.sum(feat_3)

    feat_4 = -np.sum(psd_*np.log(psd_))

    peaks, properties = find_peaks(psd_)
    a1 = psd_[peaks]
    a1=np.sort(a1)
    if len(a1)>=3:
        first, second, third=a1[-1], a1[-2], a1[-3]
    elif len(a1)==2:
	    first,second,third=a1[-1], a1[-2], np.min(psd_)
    elif len(a1)==1:
    	first,second,third=a1[-1], np.min(psd_), np.min(psd_)
    elif len(a1)==0:
    	first,second,third=np.max(psd_), np.min(psd_), np.min(psd_)
 
    #print(first, second, third)
    feat_5=first/second
    #print(feat_5)
    feat_6=first/third
    #print(feat_6)
    feat_7 = kurtosis(psd_)
    #print(feat_7)
    feat_8 = skew(psd_) 

    feat_10 = FeatureSpectralFlatness(psd_, fs_)
    #print(feat_10)
    
    feat_11 = a_[np.argmax(psd_)]
    
    #in band vs out of band ratio for feat 1
    feat_12=feat_1/(feat_2+feat_3)
    
    #in band vs out of band ratio for feat 1
    feat_13=feat_2/(feat_1+feat_3)
    
    #in band vs out of band ratio for feat 1
    feat_14=feat_3/(feat_1+feat_2)
    
    #get timeseries entropy (PE)
    lag=1
    feat_15=ent.permutation_entropy(x_,3,lag)
    
   
    
    feat_c=np.hstack((feat_1, feat_2, feat_3, feat_4, feat_5, feat_6, feat_7, feat_8, feat_10, feat_11,feat_12,feat_13,feat_14,feat_15))
    
    return feat_c
Esempio n. 17
0
def delay_op(time_series, plotting=False):
    """This function returns a suitable embedding delay, given a time series, based on the multi-scale permutation entropy algorithm.

    Args:
       ts (array):  Time series array (1d).

    Kwargs:
       plotting (bool): If True then the function will also plot the multi-scale permutation entropy plot for validation purposes.

    Returns:
       (int): tau, The embedding delay for permutation formation.

    """

    #returns delay based on equioprobable permutations
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.gridspec as gridspec
    import networkx as nx
    from scipy import sparse
    from ripser import ripser
    from pyentrp import entropy as ent
    import math
    import numpy as np

    flag = False
    trip = 0.975  #sets trip value for knowing there is approximately a peak
    MSPE = []
    delays = []
    ds = 1  #delay start
    de = 200  #delay end
    m = 3  #embedding dimension
    start = False  #hasn't started yet
    end = False  #hasn't found the first peak after noise yet
    delay = ds
    NPE_previous = 0  #initialize normalized permutation entropy (NPE)
    while end == False:  #While it hasn't found a peak
        ME = np.log2(math.factorial(m))
        PE = ent.permutation_entropy(time_series, m, delay)
        NPE = PE / ME
        delays.append(delay)
        if NPE < trip:
            start = True
        if NPE > trip and start == True and end == False:
            delay_peak = delay
            end = True
            NPE_previous = NPE
        MSPE = np.append(MSPE, NPE)
        if delay > de:  #if it reaches the end
            if flag == True:  #if it didn't find an appropriate delay after the second pass
                print('Warnings (1), (2), or (3):')
                print(
                    '(1) Amplitude of noise is too large and exceeds signal.')
                print(
                    '(2) If no noise or small amount, then time series is signficantly over sampled with'
                )
                print(
                    '    Sampling Frequency greater than 100 times Nyquist rate.'
                )

                print('(3) The time series is from a discrete signal (Map).')
                print('*** Delay = 1 is returned ***')
                delay_peak = 1  #return delay of 1 (probably this is a map)
                end = True
            trip = trip + 0.025  #try again but higher trip value
            flag = True  #sets warning flag that this is the second pass
            delay = 1  #restartes delay to 1
        delay = delay + 1

    L = len(time_series)
    if L / delay_peak < 50:
        print('Warning: delay may be inaccurate due to short time series')
    if plotting == True:
        plt.figure(figsize=(5, 3))
        plt.plot(delays, MSPE, 'k.')
        plt.xlabel(delay)
        plt.ylabel('NPE')
        plt.show()
    return delay_peak
Esempio n. 18
0
def permutation_entropy(X):
    y = ent.permutation_entropy(X, 4, 1)
    return y
Esempio n. 19
0
 def _permutation_entropy(self):
     return permutation_entropy(self.MEAN_SPREAD, order=5, delay=1)
Esempio n. 20
0
def entropy_acc(x, y, z, m):
    x_feat = [ent.permutation_entropy(list(i)) for i in x]
    y_feat = [ent.permutation_entropy(list(i)) for i in y]
    z_feat = [ent.permutation_entropy(list(i)) for i in z]
    m_feat = [ent.permutation_entropy(list(i)) for i in m]
    return x_feat, y_feat, z_feat, m_feat
Esempio n. 21
0
        feat_11 = a[np.argmax(psd)]

        #in band vs out of band ratio for feat 1
        feat_12 = feat_1 / (feat_2 + feat_3)

        #in band vs out of band ratio for feat 1
        feat_13 = feat_2 / (feat_1 + feat_3)

        #in band vs out of band ratio for feat 1
        feat_14 = feat_3 / (feat_1 + feat_2)

        #get timeseries entropy (PE)
        lag = 1
        x_ = br_epoch[:, ix]
        print(x_.shape)
        feat_15 = ent.permutation_entropy(x_, 3, lag)
        feat_c = np.hstack(
            (feat_1, feat_2, feat_3, feat_4, feat_5, feat_6, feat_7, feat_8,
             feat_10, feat_11, feat_12, feat_13, feat_14, feat_15))
        feat = np.vstack((feat, feat_c))
n = feat.shape[0]
print(n)
X0 = np.ones((n, 1))
print(X0.shape)
feat = np.hstack((feat, X0))
print(feat.shape)

df = pd.DataFrame(feat, columns=output_cols)
df.to_csv('/media/shruti/Data/Breathing_project/breathing_talk_devel_new.csv',
          index=None)
Esempio n. 22
0
def MsPE_tau(time_series, delay_end=200, plotting=False):
    """This function takes a time series and uses Multi-scale Permutation Entropy (MsPE) to find the optimum
    delay based on the first maxima in the MsPE plot
    
    Args:
       ts (array):  Time series (1d).
       delay_end (int): maximum delay in search. default is 200.
       
    Kwargs:
       plotting (bool): Plotting for user interpretation. defaut is False.

    Returns:
       (int): tau, The embedding delay for permutation formation.

    """
    trip = 0.9
    from pyentrp import entropy as ent
    import math
    import numpy as np

    MSPE = []
    delays = []
    ds, de = 0, delay_end
    m = 3
    start = False
    end = False
    delay = ds
    NPE_previous = 0
    while end == False:
        delay = delay + 1
        ME = np.log2(math.factorial(m))
        PE = ent.permutation_entropy(time_series, m, delay)
        NPE = PE / ME
        if NPE < trip:
            start = True
        if NPE > trip and start == True and end == False:
            if NPE < NPE_previous:
                delay_peak = delay - 1
                end = True
            NPE_previous = NPE
        MSPE = np.append(MSPE, NPE)
        delays.append(delay)

        if delay > de:
            delay = 1
            trip = trip - 0.05
            if trip < 0.5:
                delay = 1
                end = True

    if plotting == True:
        import matplotlib.pyplot as plt
        plt.figure(2)
        TextSize = 17
        plt.figure(figsize=(8, 3))
        plt.plot(delays, MSPE, marker='.')
        plt.xticks(size=TextSize)
        plt.yticks(size=TextSize)
        plt.ylabel(r'$h(3)$', size=TextSize)
        plt.xlabel(r'$\tau$', size=TextSize)
        plt.show()
    return delay_peak
Esempio n. 23
0
 def test_permutationEntropy(self):
     self.assertEqual(
         np.round(ent.permutation_entropy(TS_SAMPLE_ENTROPY, 3, 5), 4),
         1.7120)