Esempio n. 1
0
def discreteWaveletAnalysis(vx, wDict):
    from utilities import dataFromDict
    try:
        import pywt
    except:
        sys.exit(' Library pywt not installed. Exiting ...')

    # nlevel = 4
    order = 'freq'  # "normal"
    wavelet = dataFromDict('wavelet', wDict, allowNone=False)
    nlevel = dataFromDict('nlevel', wDict, allowNone=False)
    if (wavelet in pywt.wavelist()):
        try:
            wp = pywt.WaveletPacket(vx, wavelet, 'sym', maxlevel=nlevel)
        except:
            print(" Wrong wavelet type given. Reverting to default 'db2'. ")
            wavelet = 'db2'
            wp = pywt.WaveletPacket(vx, wavelet, 'sym', maxlevel=nlevel)

    nodes = wp.get_level(nlevel, order=order)
    labels = [n.path for n in nodes]
    values = np.array([n.data for n in nodes], 'd')
    values = abs(values)

    return values, labels
Esempio n. 2
0
    def denoise_by_wavelets(audio,wavelet = 'dmey',threshold = 9):
        """
        Audio denoising by using wavelet packet decomposition
        Steps 1) Wavelet Packet decomposition 2) Thresholding 3) Reconstruction of wavelet packet decomposition.
        :param audio: 
        :param wavelet: 
        :param threshold: Threshold used to remove noise (Actual threshold = threshold*std of 
                            lowest level detail coefficients of the tree of wavelet packet decomposition)
        :return: Denoised audio
        """
        wp = pywt.WaveletPacket(data=audio, wavelet=wavelet, mode='symmetric')
        new_wp = pywt.WaveletPacket(data=None, wavelet=wavelet, mode='symmetric')

        ld = wp['d'].data
        threshold = threshold*np.std(ld)

        print("Denoising using wavelets for {} levels ... This may take a while".format(wp.maxlevel))

        for i in range(wp.maxlevel):
            paths = [node.path for node in wp.get_level(i+1, 'natural')]

            for path in paths:
                new_wp[path] = pywt.threshold(wp[path].data,threshold)

        new_wp.reconstruct(update=True)
        return new_wp.data
Esempio n. 3
0
    def denoise_wpa(self, Xin, Nin):
        # print("Xin len " + str(len(Xin)))
        X = pywt.WaveletPacket(Xin, self.waveletName, 'symmetric',
                               self.wlevels)
        N = pywt.WaveletPacket(Nin, self.waveletName, 'symmetric',
                               self.wlevels)
        Y = pywt.WaveletPacket(data=None,
                               wavelet=self.waveletName,
                               mode='symmetric')
        # print("X len" + str(X.maxlevel))
        # the output of pywt.wavedec will be arrays (trees) of size/length wlevels+1
        # so at the index of 1[wlevels] we have the "leaf node"
        nBands = pow(2, self.wlevels)
        XleafNodes = [node.path for node in X.get_level(self.wlevels, 'freq')]
        Ak = self.linearAk(nBands, self.akSlope)
        # print(Ak)
        # print(XleafNodes)
        bandId = 0
        numOfBands = len(XleafNodes)
        counter = 0
        for node in XleafNodes:
            bandAk = Ak[bandId]
            bandId += 1
            XbandData = X[node].data
            NbandData = N[node].data
            YbandData = self.denoise_band(XbandData, NbandData, bandAk)
            Y[node] = YbandData
            counter = counter + 1

        # reconstructing the audio from Y
        Yaudio = Y.reconstruct(update=False)
        return Yaudio
Esempio n. 4
0
def data_wt(f, lenf_r, day, n, wavelet, mode):
    f_r = np.empty(shape=(lenf_r, day, pow(2, n), 3))
    for s in range(lenf_r):
        f_i = f[s:day + s] / np.mean(f[s:day + s])
        f_i_r = np.empty(shape=(day, pow(2, n), 3))
        for i in range(3):
            a = f_i[:, i]
            a_w = pywt.WaveletPacket(data=a,
                                     wavelet=wavelet,
                                     mode=mode,
                                     maxlevel=n)
            # 获取特定层数的所有节点
            npn = [node.path for node in a_w.get_level(n, 'natural')]
            for j in range(len(npn)):
                new_aw = pywt.WaveletPacket(data=None,
                                            wavelet=wavelet,
                                            mode=mode)
                new_aw[npn[j]] = a_w[npn[j]]
                a_r_j = new_aw.reconstruct(update=True)
                f_i_r[:, j, i] = a_r_j
        f_r[s] = f_i_r
    print(f_r[-1])
    c = np.zeros(shape=(day, ))
    for i in range(pow(2, n)):
        c = c + f_r[-1, :, i, 0]
    print(c - f_i[:, 0])
    return f_r
Esempio n. 5
0
    def transform(self, X, y=None):
        def Energy(coeffs, k):
            return np.sqrt(np.sum(np.array(coeffs[-k])**2)) / len(coeffs[-k])

        def getEnergy(wp):
            coefs = np.asarray([n.data for n in wp.get_leaf_nodes(True)])
            return np.asarray(
                [Energy(coefs, i) for i in range(2**wp.maxlevel)])

        if X.shape[2] == 1:
            return np.array([
                getEnergy(
                    pywt.WaveletPacket(data=x,
                                       wavelet='db4',
                                       mode='symmetric',
                                       maxlevel=4)) for x in X[:, :, 0]
            ])
        de = np.array([
            getEnergy(
                pywt.WaveletPacket(data=x,
                                   wavelet='db4',
                                   mode='symmetric',
                                   maxlevel=4)) for x in X[:, :, 0]
        ])
        fe = np.array([
            getEnergy(
                pywt.WaveletPacket(data=x,
                                   wavelet='db4',
                                   mode='symmetric',
                                   maxlevel=4)) for x in X[:, :, 1]
        ])
        return np.concatenate((de, fe), axis=1)
Esempio n. 6
0
def reconstruct():
    """ Take only the lowest-frequency component of the WPT. """

    npzfile = np.load("./data/rawInputs.npz")
    raw = npzfile['arr_0']
    wave, waveTS, dataE, dataRT = raw[0], raw[1], raw[2], raw[3]

    wp = pywt.WaveletPacket(data=wave,
                            wavelet='haar',
                            mode='symmetric',
                            maxlevel=3)
    new_wp = pywt.WaveletPacket(data=None, wavelet='haar', mode='symmetric')
    new_wp['aaa'] = wp['aaa'].data
    newWave = new_wp.reconstruct(update=False)

    # plots
    fig = plt.figure(figsize=(8, 5), facecolor='w')
    a1 = plt.subplot(111)
    a1.set_title("Energy %.1f keV  RiseTime %.1f ns" % (dataE, dataRT))
    a1.set_ylabel("ADC [A.U.]", y=0.95, ha='right')
    a1.set_xlabel("Time (ns)", x=0.95, ha='right')
    a1.plot(waveTS, wave, color='blue', alpha=0.8, label='Original Waveform')
    a1.plot(np.arange(0,
                      len(newWave) * 10, 10),
            newWave,
            color='red',
            label='Lvl3 Haar Denoised WF')
    a1.legend(loc=4)
    plt.show(block=False)
    plt.savefig("./plots/denoised-wf.pdf")
Esempio n. 7
0
def test_reconstructing_data():
    x = [1, 2, 3, 4, 5, 6, 7, 8]
    wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='sym')

    # Create another Wavelet Packet and feed it with some data.
    new_wp = pywt.WaveletPacket(data=None, wavelet='db1', mode='sym')
    new_wp['aa'] = wp['aa'].data
    new_wp['ad'] = [-2., -2.]

    # For convenience, :attr:`Node.data` gets automatically extracted
    # from the :class:`Node` object:
    new_wp['d'] = wp['d']

    # Reconstruct data from aa, ad, and d packets.
    assert_allclose(new_wp.reconstruct(update=False), x, rtol=1e-12)

    # The node's :attr:`~Node.data` will not be updated
    assert_(new_wp.data is None)

    # When `update` is True:
    assert_allclose(new_wp.reconstruct(update=True), x, rtol=1e-12)
    assert_allclose(new_wp.data, np.arange(1, 9), rtol=1e-12)

    assert_([n.path
             for n in new_wp.get_leaf_nodes(False)] == ['aa', 'ad', 'd'])
    assert_([n.path for n in new_wp.get_leaf_nodes(True)] ==
            ['aaa', 'aad', 'ada', 'add', 'daa', 'dad', 'dda', 'ddd'])
Esempio n. 8
0
def reconstructExample():
    x = [1, 2, 3, 4, 5, 6, 7, 8]
    wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')

    # Now create a new Wavelet Packet and set its nodes with some data.
    new_wp = pywt.WaveletPacket(data=None, wavelet='db1', mode='symmetric')
    new_wp['aa'] = wp['aa'].data
    new_wp['ad'] = [-2., -2.]

    # For convenience, Node.data gets automatically extracted from the Node object:
    new_wp['d'] = wp['d']

    # And reconstruct the data from the aa, ad and d packets.
    print(new_wp.reconstruct(update=False))
    # [ 1.  2.  3.  4.  5.  6.  7.  8.]

    # If the update param in the reconstruct method is set to False, the node's data will not be updated.
    print(new_wp.data)
    # None

    # Otherwise, the data attribute will be set to the reconstructed value.
    print(new_wp.reconstruct(update=True))
    # [ 1.  2.  3.  4.  5.  6.  7.  8.]

    print(new_wp.data)
    # [ 1.  2.  3.  4.  5.  6.  7.  8.]

    print([n.path for n in new_wp.get_leaf_nodes(False)])
    # ['aa', 'ad', 'd']

    print([n.path for n in new_wp.get_leaf_nodes(True)])
Esempio n. 9
0
def gety():
    ys = sampley()
    ploty(ys, "original")

    wp = pywt.WaveletPacket(data=ys, wavelet='db4')

    new_wp = pywt.WaveletPacket(data=None, wavelet='db4')
    new_wp['a'] = wp['a'].data
    recy = new_wp.reconstruct()
    afilt = np.fft.fft(recy)
    abins = np.fft.fftfreq(len(wp['a'].data), d=1 / 400)
    todrop = np.where(abins < len(wp['a'].data) / 4) or np.where(
        abins > 3 * len(wp['a'].data) / 4)
    afilt[todrop] = 0
    recy = np.fft.ifft(afilt)
    ploty(recy, "a")

    new_wp = pywt.WaveletPacket(data=None, wavelet='db4')
    #new_wp['a'] = np.zeros(len(wp['a'].data))
    new_wp['d'] = wp['d'].data
    recy = new_wp.reconstruct()
    afilt = np.fft.fft(recy)
    abins = np.fft.fftfreq(len(wp['d'].data), d=1 / 400)
    todrop = np.where(abins < len(wp['d'].data) / 4) or np.where(
        abins > 3 * len(wp['d'].data) / 4)
    afilt[todrop] = 0
    recy = np.fft.ifft(afilt)
    ploty(recy, "d")

    plt.show()
Esempio n. 10
0
 def run(self, data) -> list:
     close = data.close.values[:-7]
     wavelet = 'db3'
     level = 4
     wp = pywt.WaveletPacket(close, wavelet, maxlevel=level)
     wl_list = []
     for i in range(level):
         new_wp = pywt.WaveletPacket(None, wavelet, maxlevel=level)
         node = 'a' * (i + 1)
         new_wp[node] = wp[node]
         wl = new_wp.reconstruct()
         wl_list.append(wl)
     for i, wl in enumerate(wl_list):
         if i < level - 1:
             continue
         self._add_technique('WL{0}'.format(i + 1),
                             wl,
                             x_axis=np.arange(wl.size))
         # node_list = ['daa', 'ada', 'aad']
         # wld_list = []
         # for i in range(level):
         #     new_wp = pywt.WaveletPacket(None, wavelet, maxlevel=level)
         #     node = node_list[i]
         #     new_wp[node] = wp[node]
         #     wld = new_wp.reconstruct()
         #     wld_list.append(wld)
         # for i, wl in enumerate(wld_list):
         #     self._add_technique('D{0}'.format(i + 1), wl, 2, x_axis=np.arange(wl.size))
         return super().run(data)
Esempio n. 11
0
def __check_pywt(features=None):
    """Check for available functionality within pywt

    Parameters
    ----------
    features : list of str
      List of known features to check such as 'wp reconstruct',
      'wp reconstruct fixed'
    """
    import pywt
    import numpy as np
    data = np.array(
        [0.57316901,  0.65292526,  0.75266733,  0.67020084,  0.46505364,
         0.76478331,  0.33034164,  0.49165547,  0.32979941,  0.09696717,
         0.72552711,  0.4138999,   0.54460628,  0.786351,    0.50096306,
         0.72436454,  0.2193098,  -0.0135051,   0.34283984,  0.65596245,
         0.49598417,  0.39935064,  0.26370727,  0.05572373,  0.40194438,
         0.47004551,  0.60327258,  0.25628266,  0.32964893,  0.24009889])
    mode = 'per'
    wp = pywt.WaveletPacket(data, 'sym2', mode)
    wp2 = pywt.WaveletPacket(data=None, wavelet='sym2', mode=mode)
    try:
        for node in wp.get_level(2): wp2[node.path] = node.data
    except:
        raise ImportError(
            "Failed to reconstruct WP by specifying data in the layer")

    if 'wp reconstruct fixed' in features:
        rec = wp2.reconstruct()
        if np.linalg.norm(rec[:len(data)] - data) > 1e-3:
            raise ImportError(
                "Failed to reconstruct WP correctly")
    return True
Esempio n. 12
0
def test_wavelet_packet_dtypes():
    N = 32
    for dtype in [np.float32, np.float64, np.complex64, np.complex128]:
        x = np.random.randn(N).astype(dtype)
        if np.iscomplexobj(x):
            x = x + 1j * np.random.randn(N).astype(x.real.dtype)
        wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
        # no unnecessary copy made
        assert_(wp.data is x)

        # assiging to a node should not change supported dtypes
        wp['d'] = wp['d'].data
        assert_equal(wp['d'].data.dtype, x.dtype)

        # full decomposition
        wp.get_level(wp.maxlevel)

        # reconstruction from coefficients should preserve dtype
        r = wp.reconstruct(False)
        assert_equal(r.dtype, x.dtype)
        assert_allclose(r, x, atol=1e-5, rtol=1e-5)

    # first element of the tuple is the input dtype
    # second element of the tuple is the transform dtype
    dtype_pairs = [
        (np.uint8, np.float64),
        (np.intp, np.float64),
    ]
    if hasattr(np, "complex256"):
        dtype_pairs += [
            (np.complex256, np.complex128),
        ]
    if hasattr(np, "half"):
        dtype_pairs += [
            (np.half, np.float32),
        ]
    for (dtype, transform_dtype) in dtype_pairs:
        x = np.arange(N, dtype=dtype)
        wp = pywt.WaveletPacket(x, wavelet='db1', mode='symmetric')

        # no unnecessary copy made of top-level data
        assert_(wp.data is x)

        # full decomposition
        wp.get_level(wp.maxlevel)

        # reconstructed data will have modified dtype
        r = wp.reconstruct(False)
        assert_equal(r.dtype, transform_dtype)
        assert_allclose(r, x.astype(transform_dtype), atol=1e-5, rtol=1e-5)
Esempio n. 13
0
def return_iwv_PACKET_fix_levels(x, fs, max_level, mother_wv, idx_levels):
    n = len(x)

    nico = pywt.WaveletPacket(data=x, wavelet=mother_wv, maxlevel=max_level)
    mylevels = [node.path for node in nico.get_level(max_level, 'freq')]

    print('inverse WV!')
    gato = pywt.WaveletPacket(data=None, wavelet=mother_wv, maxlevel=max_level)

    for idx in idx_levels:
        gato[mylevels[idx]] = nico[mylevels[idx]].data
    outsignal = gato.reconstruct(update=False)

    return outsignal
Esempio n. 14
0
def frequency_draw(data2: np.ndarray):
    wp = pywt.WaveletPacket(data=data2,
                            wavelet='db3',
                            mode='symmetric',
                            maxlevel=2)  #2层小波包分解
    new_wp = pywt.WaveletPacket(data=None,
                                wavelet='db3',
                                mode='symmetric',
                                maxlevel=2)  #新建小波包树用来重构4个节点系数

    new_wp['aa'] = wp['aa']
    LL = new_wp.reconstruct(update=False)

    del (new_wp['aa'])
    new_wp['ad'] = wp['ad']
    LH = new_wp.reconstruct(update=False)

    del (new_wp['a'])
    new_wp['da'] = wp['da']
    HL = new_wp.reconstruct(update=False)

    del (new_wp['da'])
    new_wp['dd'] = wp['dd']
    HH = new_wp.reconstruct(update=False)

    #4个频率分量的能量
    LLPE = np.sum(LL * LL)
    LHPE = np.sum(LH * LH)
    HLPE = np.sum(HL * HL)
    HHPE = np.sum(HH * HH)
    E = [LLPE, LHPE, HLPE, HHPE]
    P = E / np.sum(E)
    WE = -np.sum(np.log2(P) * P)  #信息熵
    WIQ = np.sum(P * E)  #信息量
    S = np.array([LL, LH, HL, HH])  #小波系数矩阵4*33
    U, sigma, VT = np.linalg.svd(S, full_matrices=1, compute_uv=1)
    feature = np.empty(10)
    feature[0] = LLPE
    feature[1] = LHPE
    feature[2] = HLPE
    feature[3] = HHPE
    feature[4] = WE
    feature[5] = WIQ
    feature[6] = sigma[0]
    feature[7] = sigma[1]
    feature[8] = sigma[2]
    feature[9] = sigma[3]

    return feature
Esempio n. 15
0
 def run(self, data) -> list:
     close_all = data.close.values
     wavelet = 'db2'
     level = 4
     wla = [np.nan]
     for i in range(close_all.size):
         close = close_all[:i + 1]
         wp = pywt.WaveletPacket(close, wavelet, maxlevel=level)
         new_wp = pywt.WaveletPacket(None, wavelet, maxlevel=level)
         node = 'a' * level
         new_wp[node] = wp[node]
         wl = new_wp.reconstruct()
         wla.append(wl[i])
     self._add_technique('WLA', wla, x_axis=np.arange(len(wla)))
     return super().run(data)
Esempio n. 16
0
def mjdWaveform():

    # Load a data and a temp waveform
    npzfile = np.load("./data/rawInputs.npz")
    raw = npzfile['arr_0']
    wave, waveTS, dataE, dataRT = raw[0], raw[1], raw[2], raw[3]

    wp = pywt.WaveletPacket(wave, 'db2', 'symmetric', maxlevel=4)
    nodes = wp.get_level(4, order='freq', decompose=True)
    yWT = np.array([n.data for n in nodes], 'd')
    yWT = abs(yWT)
    waveletYTrans = yWT  # final coeff's (used in process-waveforms)
    rec = wp.reconstruct(update=True)

    # plots
    fig = plt.figure(figsize=(8, 8), facecolor='w')

    a1 = plt.subplot(311)
    a1.plot(waveTS, wave, color='blue')

    a2 = plt.subplot(312)
    a2.imshow(waveletYTrans,
              interpolation='nearest',
              aspect="auto",
              origin="lower",
              extent=[0, 1, 0, len(waveletYTrans)],
              cmap='jet')

    a3 = plt.subplot(313)
    a3.plot(waveTS, rec, color='red')

    plt.show()
def _compare_trees1(
    wavelet_str: str,
    max_lev: int = 3,
    pywt_boundary: str = "zero",
    ptwt_boundary: str = "zero",
    length: int = 256,
    batch_size: int = 1,
):
    data = np.random.rand(batch_size, length)
    wavelet = pywt.Wavelet(wavelet_str)
    twp = WaveletPacket(torch.from_numpy(data), wavelet, mode=ptwt_boundary)
    nodes = twp.get_level(max_lev)
    twp_lst = []
    for node in nodes:
        twp_lst.append(twp[node])
    torch_res = torch.cat(twp_lst, -1).numpy()

    np_batches = []
    for batch_index in range(batch_size):
        wp = pywt.WaveletPacket(data=data[batch_index],
                                wavelet=wavelet,
                                mode=pywt_boundary)
        nodes = [node.path for node in wp.get_level(max_lev, "freq")]
        np_lst = []
        for node in nodes:
            np_lst.append(wp[node].data)
        np_res = np.concatenate(np_lst, -1)
        np_batches.append(np_res)
    np_batches = np.stack(np_batches, 0)
    assert np.allclose(torch_res, np_batches)
Esempio n. 18
0
    def __reverse_single_level(self, wp):

        # local bindings
        level_paths = self.__level_paths

        # define wavelet packet to use
        WP = pywt.WaveletPacket(data=None,
                                wavelet=self._wavelet,
                                mode=self._mode,
                                maxlevel=self.__level)

        # prepare storage
        signal_shape = wp.shape[:1] + self._inshape[1:]
        signal = np.zeros(signal_shape)
        Ntime_points = self._intimepoints
        for indexes in _get_indexes(signal_shape, self._dim):
            if __debug__:
                debug('MAP_', " %s" % (indexes, ), lf=False, cr=True)

            for path, level_data in zip(level_paths, wp[indexes]):
                WP[path] = level_data

            signal[indexes] = WP.reconstruct(True)[:Ntime_points]

        return signal
Esempio n. 19
0
def test_removing_nodes():
    x = [1, 2, 3, 4, 5, 6, 7, 8]
    wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='sym')
    wp.get_level(2)

    dataleafs = [n.data for n in wp.get_leaf_nodes(False)]
    expected = np.array([[5., 13.], [-2, -2], [-1, -1], [0, 0]])

    for i in range(4):
        assert_allclose(dataleafs[i], expected[i, :], atol=1e-12)

    node = wp['ad']
    del (wp['ad'])
    dataleafs = [n.data for n in wp.get_leaf_nodes(False)]
    expected = np.array([[5., 13.], [-1, -1], [0, 0]])

    for i in range(3):
        assert_allclose(dataleafs[i], expected[i, :], atol=1e-12)

    wp.reconstruct()
    # The reconstruction is:
    assert_allclose(wp.reconstruct(),
                    np.array([2., 3., 2., 3., 6., 7., 6., 7.]),
                    rtol=1e-12)

    # Restore the data
    wp['ad'].data = node.data

    dataleafs = [n.data for n in wp.get_leaf_nodes(False)]
    expected = np.array([[5., 13.], [-2, -2], [-1, -1], [0, 0]])

    for i in range(4):
        assert_allclose(dataleafs[i], expected[i, :], atol=1e-12)

    assert_allclose(wp.reconstruct(), np.arange(1, 9), rtol=1e-12)
Esempio n. 20
0
 def waveletPacket(self, packlevel):
     """After obtaining the frame, the Wavelet Packet Energy (WPE) feature 
     is obtain from the frame using the Wavelet Packe method.
     Parameters
     ----------
     packlevel: int, the quantity of the frequency bands of the frequency. Larger
     packlevel, higher frequency resolution and more generated features. 
     2^ packlevel must smaller than the frame data.
     """
     Energy = []
     Flatness = []
     self.maxWPE = []
     for clipindex in xrange(len(self.cutclip)):
         tempE = []
         tempF = []
         wp= pywt.WaveletPacket(data=self.cutclip[clipindex,:],wavelet='db1',mode='symmetric',  maxlevel = packlevel)
         for i in xrange(packlevel+1):
             for index, node in enumerate(wp.get_level(i)):
                 d = wp[node.path].data
                 E = np.log(np.sqrt(np.sum(d ** 2)))
                 F = np.exp(np.mean(np.log(np.abs(d)))) / np.mean(np.abs(d))
                 tempE.append(E)
                 tempF.append(F)
         maxnumE = float(max(tempE))
         temp = list(np.array(tempE) / maxnumE) # this function will deliminate the effect of the amplitude
         self.maxWPE.append(maxnumE)
         Energy.append(tempE)
         Flatness.append(tempF)
     self.maxWPE = np.array(self.maxWPE)
     self.WPE = np.matrix(Energy)
     self.WPE = self.checkmatrix(self.WPE)
     self.WPF = np.matrix(Flatness)
     self.WPF = self.checkmatrix(self.WPF)
Esempio n. 21
0
def wpe2(matrix):
    t_wpe = np.zeros((matrix.shape[0], 16))
    # Step1: The Wavelet Packet Decomposition using the Daubechies wavelet in mode symmetric.
    for i in range(matrix.shape[0]):
        wp = pywt.WaveletPacket(data=matrix[i], wavelet='db1', mode='symmetric')

        # Step2: Computing the Wavelet Packet Energy of each of 16 Wavelet Packet Decomposition sub-bands.
        t_wpe[i, 0] = wpe(wp['aaaa'].data)
        t_wpe[i, 1] = wpe(wp['aaad'].data)
        t_wpe[i, 2] = wpe(wp['aada'].data)
        t_wpe[i, 3] = wpe(wp['aadd'].data)

        t_wpe[i, 4] = wpe(wp['adaa'].data)
        t_wpe[i, 5] = wpe(wp['adad'].data)
        t_wpe[i, 6] = wpe(wp['adda'].data)
        t_wpe[i, 7] = wpe(wp['addd'].data)

        t_wpe[i, 8] = wpe(wp['daaa'].data)
        t_wpe[i, 9] = wpe(wp['daad'].data)
        t_wpe[i,10] = wpe(wp['dada'].data)
        t_wpe[i,11] = wpe(wp['dadd'].data)

        t_wpe[i,12] = wpe(wp['ddaa'].data)
        t_wpe[i,13] = wpe(wp['ddad'].data)
        t_wpe[i,14] = wpe(wp['ddda'].data)
        t_wpe[i,15] = wpe(wp['dddd'].data)

    return t_wpe
Esempio n. 22
0
def extration_wavelet_packet(wavFile):

    sig, fs = librosa.load(wavFile)
    # print("fs is ",fs)
    # print("signal length is ", len(sig))
    N_signal = len(sig)
    n_level = 6
    #N_sub = N_signal/(2**n_level)
    #print sig
    #print ("N sub is ",N_sub)
    # x = sig.reshape((len(sig),1))
    # print x

    wp = pywt.WaveletPacket(data=sig, wavelet='db3', mode='symmetric')
    #
    # print wp.data
    #print wp.maxlevel
    #print len(wp.data)
    Node = []
    N_limit = 16
    limit = 0
    for node in wp.get_level(6, 'natural'):
            Node.append(node.path)

    print("sub sample is ",len(Node))

    TC = get_teager_energy(wp,Node,n_level,N_limit)
    print ("TC is ",TC)

    return TC
Esempio n. 23
0
def test_packet_harbo_lvl3():
    """From Jensen, La Cour-Harbo, Rippels in Mathematics, Chapter 8 (page 89)."""
    data = np.array([56.0, 40.0, 8.0, 24.0, 48.0, 48.0, 40.0, 16.0])

    class _MyHaarFilterBank(object):
        @property
        def filter_bank(self):
            """Unscaled Haar wavelet filters."""
            return (
                [1 / 2, 1 / 2.0],
                [-1 / 2.0, 1 / 2.0],
                [1 / 2.0, 1 / 2.0],
                [1 / 2.0, -1 / 2.0],
            )

    wavelet = pywt.Wavelet("unscaled Haar Wavelet",
                           filter_bank=_MyHaarFilterBank())

    twp = WaveletPacket(torch.from_numpy(data), wavelet, mode="reflect")
    twp_nodes = twp.get_level(3)
    twp_lst = []
    for node in twp_nodes:
        twp_lst.append(torch.squeeze(twp[node]))
    torch_res = torch.stack(twp_lst).numpy()
    wp = pywt.WaveletPacket(data=data, wavelet=wavelet, mode="reflect")
    pywt_nodes = [node.path for node in wp.get_level(3, "freq")]
    np_lst = []
    for node in pywt_nodes:
        np_lst.append(wp[node].data)
    np_res = np.concatenate(np_lst)
    assert np.allclose(torch_res, np_res)
Esempio n. 24
0
def waveletTransform(signalRaw, level=4, wavelet='db2', order='freq'):
    """ Use PyWavelets to do a wavelet transform. """
    wp = pywt.WaveletPacket(signalRaw, wavelet, 'symmetric', maxlevel=level)
    nodes = wp.get_level(level, order=order)
    yWT = np.array([n.data for n in nodes], 'd')
    yWT = abs(yWT)
    return wp.data, yWT
Esempio n. 25
0
def get_wavelet_envelopes(frames, level=5, window_type='hann'):
    '''
    Decomposes input audio with wavelet packets and calculates energy envelopes of their components

    Parameters:
    frames          : overlapping signal frames for short-time analysis
    level           : number of levels of wavelet decomposition, 2**level gives the final number of wavelet components
    window_type     : type of windowing function to apply

    Returns numpy 2D array af 
    '''

    frame_size = len(frames[0])
    num_bands = 2**level
    output_envelopes = {i: [] for i in range(num_bands)}
    windowing = es.Windowing(type='hann', size=frame_size)

    for frame in frames:
        wp = pywt.WaveletPacket(data=windowing(frame),
                                wavelet='db1',
                                mode='zero',
                                maxlevel=level)
        for i in range(num_bands):
            band_key = bin(i).replace('0b', '').zfill(level).replace(
                '0', 'a').replace('1', 'd')
            output_envelopes[i].append(np.std(wp[band_key].data))

    output_array = []
    for item in output_envelopes.values():
        output_array.append(list(item))

    return np.array(output_array)
Esempio n. 26
0
def WPT(X):
    y = []
    for x in X:
        wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
        temp = [node.data[0] for node in wp.get_level(wp.maxlevel, 'natural')]
        y.append(temp)
    return np.array(y)
Esempio n. 27
0
    def wavelet_tree(self, wavelet='db1', analyze_level=6):
        sound = self.org_sound
        # 进行小波包分解
        wp = pywt.WaveletPacket(data=sound, wavelet=wavelet, mode='sym')
        # 获取小波包分解树的各个节点名称
        node_names = [
            node.path for node in wp.get_level(analyze_level, 'natural')
        ]
        # 获取 概要部分节点名称 和 细节部分节点名称
        node_names_approx = node_names[:(2**analyze_level // 2)]
        node_names_detail = node_names[(2**analyze_level // 2):]
        # 分别获取 概要部分的信号 和 细节部分的信号
        approx_array = [pywt.upcoef('a', wp[node].data, wavelet, level=analyze_level) \
                        for node in node_names_approx]
        detail_array = [pywt.upcoef('d', wp[node].data, wavelet, level=analyze_level) \
                        for node in node_names_detail]

        self.approx_array = approx_array
        self.detail_array = detail_array
        self.wave_mode = 'wavelet_tree'
        self.level = analyze_level

        self.col_name = [node.path for node in \
                         wp.get_level(analyze_level, 'natural')]
        return approx_array, detail_array
Esempio n. 28
0
def getFeature(path):
    with open(path, 'r', encoding='utf-8') as f:
        for line in f:
            a = line.split(',')
            a = np.array(a).astype(float)
            x, y = signal.butter(1, 0.4, 'highpass')
            a = signal.filtfilt(x, y, a)
        u = [0 for i in range(8)]
        for i in range(100):
            wp = pywt.WaveletPacket(a[10000 * i:10000 * (i + 1)],
                                    wavelet='db3',
                                    mode='symmetric',
                                    maxlevel=3)
            u[0] += np.linalg.norm(wp['aaa'].data, ord=None)
            u[1] += np.linalg.norm(wp['aad'].data, ord=None)
            u[2] += np.linalg.norm(wp['ada'].data, ord=None)
            u[3] += np.linalg.norm(wp['add'].data, ord=None)
            u[4] += np.linalg.norm(wp['daa'].data, ord=None)
            u[5] += np.linalg.norm(wp['dad'].data, ord=None)
            u[6] += np.linalg.norm(wp['dda'].data, ord=None)
            u[7] += np.linalg.norm(wp['ddd'].data, ord=None)
        u[0] /= 100
        u[1] /= 100
        u[2] /= 100
        u[3] /= 100
        u[4] /= 100
        u[5] /= 100
        u[6] /= 100
        u[7] /= 100
    return u
Esempio n. 29
0
    def create_wavelet_packet(self):
        for item in self.hamming_window_list:
            item = np.array(item)
            wp = pywt.WaveletPacket(data=item,
                                    wavelet='db1',
                                    mode='symmetric',
                                    maxlevel=4)
            self.wavelet_list.append(wp['aaaa'].data)
            self.wavelet_list.append(wp['aaad'].data)
            self.wavelet_list.append(wp['aada'].data)
            self.wavelet_list.append(wp['aadd'].data)
            self.wavelet_list.append(wp['adaa'].data)
            self.wavelet_list.append(wp['adad'].data)
            self.wavelet_list.append(wp['adda'].data)
            self.wavelet_list.append(wp['addd'].data)
            self.wavelet_list.append(wp['daaa'].data)
            self.wavelet_list.append(wp['daad'].data)
            self.wavelet_list.append(wp['dada'].data)
            self.wavelet_list.append(wp['dadd'].data)
            self.wavelet_list.append(wp['ddaa'].data)
            self.wavelet_list.append(wp['ddad'].data)
            self.wavelet_list.append(wp['ddda'].data)
            self.wavelet_list.append(wp['dddd'].data)

        self.standard_deviation()
        print(
            f'Wavelet packet created + calculated std. deviation from {[self.data_type]}'
        )
Esempio n. 30
0
def test_wavelet_packet_structure():
    x = [1, 2, 3, 4, 5, 6, 7, 8]
    wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='sym')

    assert_(wp.data == [1, 2, 3, 4, 5, 6, 7, 8])
    assert_(wp.path == '')
    assert_(wp.level == 0)
    assert_(wp['ad'].maxlevel == 3)