Python pywt.dwt() Examples

The following are 22 code examples of pywt.dwt(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pywt , or try the search function .
Example #1
Source File: test_concurrent.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def _assert_all_coeffs_equal(coefs1, coefs2):
    # return True only if all coefficients of SWT or DWT match over all levels
    if len(coefs1) != len(coefs2):
        return False
    for (c1, c2) in zip(coefs1, coefs2):
        if isinstance(c1, tuple):
            # for swt, swt2, dwt, dwt2, wavedec, wavedec2
            for a1, a2 in zip(c1, c2):
                assert_array_equal(a1, a2)
        elif isinstance(c1, dict):
            # for swtn, dwtn, wavedecn
            for k, v in c1.items():
                assert_array_equal(v, c2[k])
        else:
            return False
    return True 
Example #2
Source File: test_dwt_idwt.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_dwt_idwt_basic():
    x = [3, 7, 1, 1, -2, 5, 4, 6]
    cA, cD = pywt.dwt(x, 'db2')
    cA_expect = [5.65685425, 7.39923721, 0.22414387, 3.33677403, 7.77817459]
    cD_expect = [-2.44948974, -1.60368225, -4.44140056, -0.41361256,
                 1.22474487]
    assert_allclose(cA, cA_expect)
    assert_allclose(cD, cD_expect)

    x_roundtrip = pywt.idwt(cA, cD, 'db2')
    assert_allclose(x_roundtrip, x, rtol=1e-10)

    # mismatched dtypes OK
    x_roundtrip2 = pywt.idwt(cA.astype(np.float64), cD.astype(np.float32),
                             'db2')
    assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7)
    assert_(x_roundtrip.dtype == np.float64) 
Example #3
Source File: test_modes.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_dwt_short_input_allmodes():
    # some test cases where the input is shorter than the DWT filter
    x = [1, 2, 3]
    wavelet = 'db2'
    # manually pad each end by the filter size (4 for 'db2' used here)
    padded_x = {'zero': [0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0],
                'constant': [1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3],
                'symmetric': [3, 3, 2, 1, 1, 2, 3, 3, 2, 1, 1],
                'reflect': [1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3],
                'periodic': [3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1],
                'smooth': [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7],
                }
    for mode, xpad in padded_x.items():
        # DWT of the manually padded array.  will discard edges later so
        # symmetric mode used here doesn't matter.
        cApad, cDpad = pywt.dwt(xpad, wavelet, mode='symmetric')

        # central region of the padded output (unaffected by mode  )
        expected_result = (cApad[2:-2], cDpad[2:-2])

        cA, cD = pywt.dwt(x, wavelet, mode)
        assert_allclose(cA, expected_result[0], rtol=1e-7, atol=1e-8)
        assert_allclose(cD, expected_result[1], rtol=1e-7, atol=1e-8) 
Example #4
Source File: test_dwt_idwt.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_dwt_idwt_partial_complex():
    x = np.asarray([3, 7, 1, 1, -2, 5, 4, 6])
    x = x + 0.5j*x

    cA, cD = pywt.dwt(x, 'haar')
    cA_rec_expect = np.array([5.0+2.5j, 5.0+2.5j, 1.0+0.5j, 1.0+0.5j,
                              1.5+0.75j, 1.5+0.75j, 5.0+2.5j, 5.0+2.5j])
    cA_rec = pywt.idwt(cA, None, 'haar')
    assert_allclose(cA_rec, cA_rec_expect)

    cD_rec_expect = np.array([-2.0-1.0j, 2.0+1.0j, 0.0+0.0j, 0.0+0.0j,
                              -3.5-1.75j, 3.5+1.75j, -1.0-0.5j, 1.0+0.5j])
    cD_rec = pywt.idwt(None, cD, 'haar')
    assert_allclose(cD_rec, cD_rec_expect)

    assert_allclose(cA_rec + cD_rec, x) 
Example #5
Source File: test_dwt_idwt.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_idwt_single_axis():
    x = [[3, 7, 1, 1],
         [-2, 5, 4, 6]]

    x = np.asarray(x)
    x = x + 1j*x   # test with complex data
    cA, cD = pywt.dwt(x, 'db2', axis=-1)

    x0 = pywt.idwt(cA[0], cD[0], 'db2', axis=-1)
    x1 = pywt.idwt(cA[1], cD[1], 'db2', axis=-1)

    assert_allclose(x[0], x0)
    assert_allclose(x[1], x1) 
Example #6
Source File: denoising.py    From ApneaECGAnalysis with MIT License 5 votes vote down vote up
def denoise_ecg(ecg_segment):
	"""
	Remove baseline drafts from ECG signal.
	:param ecg_segment: ecg record, a numpy array.
	:return: denoised ecg record, a numpy array.
	
	Example:
	denoising_ecg = denoise_ecg(raw_ecg)
	"""
	
	denoising_wd_level = 6
	denoising_wd_wavelet = "db6"
	coffes_set = []
	cA_signal = np.reshape(ecg_segment, len(ecg_segment))
	for index_dec in range(denoising_wd_level):
		cA, cD = pywt.dwt(cA_signal, denoising_wd_wavelet)
		coffes_set.append(cD)
		cA_signal = cA
	coffes_set.append(cA_signal)
	coffes_set[denoising_wd_level] = np.zeros(len(coffes_set[denoising_wd_level]))
	
	cA_signal = coffes_set[denoising_wd_level]
	for index_dec in range(denoising_wd_level):
		cD_signal = coffes_set[denoising_wd_level - 1 - index_dec]
		if len(cD_signal) != len(cA_signal):
			cA_signal = np.delete(cA_signal, len(cA_signal) - 1, axis=0)
		cA_signal = pywt.idwt(cA_signal, cD_signal, denoising_wd_wavelet)
	cA_signal = np.reshape(cA_signal, (len(ecg_segment), 1))
	return cA_signal 
Example #7
Source File: dtcwt.py    From scikit-ued with MIT License 5 votes vote down vote up
def _single_tree_analysis_1d(data, first_stage, wavelet, level, mode, axis):
    """
    Single tree of the forward dual-tree complex wavelet transform.
    
    Parameters
    ----------
    data : ndarray, ndim 1
    first_stage : Wavelet object
    wavelet : 2-tuple of Wavelet object
    level : int
    mode : str
    axis : int

    Returns
    -------
    [cA_n, cD_n, cD_n-1, ..., cD2, cD1] : list
        Ordered list of coefficients arrays
        where `n` denotes the level of decomposition. The first element
        (`cA_n`) of the result is approximation coefficients array and the
        following elements (`cD_n` - `cD_1`) are details coefficients arrays.
    """
    approx, first_detail = dwt(data=data, wavelet=first_stage, mode=mode, axis=axis)
    # Use of a deque vs. a list is because deque.appendleft is O(1)
    coeffs_list = deque([first_detail])
    for i, wav in zip(range(level - 1), cycle(wavelet)):
        approx, detail = dwt(data=approx, wavelet=wav, mode=mode, axis=axis)
        coeffs_list.appendleft(detail)

    # Format list ot be compatible to PyWavelet's format. See pywt.wavedec source.
    coeffs_list.appendleft(approx)
    return coeffs_list 
Example #8
Source File: neural_data.py    From neural-finance with Apache License 2.0 5 votes vote down vote up
def wavy(arr):
    cA, cD = pywt.dwt(arr, 'db2', mode='symmetric')
    y = pywt.idwt(cA, cD, 'db2')
    return y 
Example #9
Source File: test_modes.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_default_mode():
    # The default mode should be 'symmetric'
    x = [1, 2, 1, 5, -1, 8, 4, 6]
    cA, cD = pywt.dwt(x, 'db2')
    cA2, cD2 = pywt.dwt(x, 'db2', mode='symmetric')
    assert_allclose(cA, cA2)
    assert_allclose(cD, cD2)
    assert_allclose(pywt.idwt(cA, cD, 'db2'), x) 
Example #10
Source File: test_modes.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwt_idwt_allmodes():
    # Test that :func:`dwt` and :func:`idwt` can be performed using every mode
    x = [1, 2, 1, 5, -1, 8, 4, 6]
    dwt_result_modes = {
        'zero': ([-0.03467518, 1.73309178, 3.40612438, 6.32928585, 6.95094948],
                 [-0.12940952, -2.15599552, -5.95034847, -1.21545369,
                 -1.8625013]),
        'constant': ([1.28480404, 1.73309178, 3.40612438, 6.32928585,
                      7.51935555],
                     [-0.48296291, -2.15599552, -5.95034847, -1.21545369,
                      0.25881905]),
        'symmetric': ([1.76776695, 1.73309178, 3.40612438, 6.32928585,
                       7.77817459],
                      [-0.61237244, -2.15599552, -5.95034847, -1.21545369,
                       1.22474487]),
        'reflect': ([2.12132034, 1.73309178, 3.40612438, 6.32928585,
                     6.81224877],
                    [-0.70710678, -2.15599552, -5.95034847, -1.21545369,
                     -2.38013939]),
        'periodic': ([6.9162743, 1.73309178, 3.40612438, 6.32928585,
                      6.9162743],
                     [-1.99191082, -2.15599552, -5.95034847, -1.21545369,
                      -1.99191082]),
        'smooth': ([-0.51763809, 1.73309178, 3.40612438, 6.32928585,
                    7.45000519],
                   [0, -2.15599552, -5.95034847, -1.21545369, 0]),
        'periodization': ([4.053172, 3.05257099, 2.85381112, 8.42522221],
                          [0.18946869, 4.18258152, 4.33737503, 2.60428326])
    }

    for mode in pywt.Modes.modes:
        cA, cD = pywt.dwt(x, 'db2', mode)
        assert_allclose(cA, dwt_result_modes[mode][0], rtol=1e-7, atol=1e-8)
        assert_allclose(cD, dwt_result_modes[mode][1], rtol=1e-7, atol=1e-8)
        assert_allclose(pywt.idwt(cA, cD, 'db2', mode), x, rtol=1e-10) 
Example #11
Source File: test_modes.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_invalid_modes():
    x = np.arange(4)
    assert_raises(ValueError, pywt.dwt, x, 'db2', 'unknown')
    assert_raises(ValueError, pywt.dwt, x, 'db2', -1)
    assert_raises(ValueError, pywt.dwt, x, 'db2', 7)
    assert_raises(TypeError, pywt.dwt, x, 'db2', None)

    assert_raises(ValueError, pywt.Modes.from_object, 'unknown')
    assert_raises(ValueError, pywt.Modes.from_object, -1)
    assert_raises(ValueError, pywt.Modes.from_object, 7)
    assert_raises(TypeError, pywt.Modes.from_object, None) 
Example #12
Source File: test_dwt_idwt.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwt_idwt_axis_excess():
    x = [[3, 7, 1, 1],
         [-2, 5, 4, 6]]
    # can't transform over axes that aren't there
    assert_raises(ValueError,
                  pywt.dwt, x, 'db2', 'symmetric', axis=2)

    assert_raises(ValueError,
                  pywt.idwt, [1, 2, 4], [4, 1, 3], 'db2', 'symmetric', axis=1) 
Example #13
Source File: test_dwt_idwt.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_idwt_axis_arg():
    x = [[3, 7, 1, 1],
         [-2, 5, 4, 6]]

    cA, cD = pywt.dwt(x, 'db2', axis=1)

    x_ = pywt.idwt(cA, cD, 'db2', axis=-1)
    x = pywt.idwt(cA, cD, 'db2', axis=1)

    assert_allclose(x_, x) 
Example #14
Source File: test_dwt_idwt.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwt_axis_arg():
    x = [[3, 7, 1, 1],
         [-2, 5, 4, 6]]

    cA_, cD_ = pywt.dwt(x, 'db2', axis=-1)
    cA, cD = pywt.dwt(x, 'db2', axis=1)

    assert_allclose(cA_, cA)
    assert_allclose(cD_, cD) 
Example #15
Source File: study_wave.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def plot_signal_decomp(data, w, title):
    """Decompose and plot a signal S.
    S = An + Dn + Dn-1 + ... + D1
    """
    w = pywt.Wavelet(w)
    a = data
    ca = []
    cd = []
    for i in range(5):
        (a, d) = pywt.dwt(a, w, mode)
        ca.append(a)
        cd.append(d)

    rec_a = []
    rec_d = []

    for i, coeff in enumerate(ca):
        coeff_list = [coeff, None] + [None] * i
        rec_a.append(pywt.waverec(coeff_list, w))

    for i, coeff in enumerate(cd):
        coeff_list = [None, coeff] + [None] * i
        rec_d.append(pywt.waverec(coeff_list, w))

    fig = plt.figure()
    ax_main = fig.add_subplot(len(rec_a) + 1, 1, 1)
    ax_main.set_title(title)
    ax_main.plot(data)
    ax_main.set_xlim(0, len(data) - 1)

    for i, y in enumerate(rec_a):
        ax = fig.add_subplot(len(rec_a) + 1, 2, 3 + i * 2)
        ax.plot(y, 'r')
        ax.set_xlim(0, len(y) - 1)
        ax.set_ylabel("A%d" % (i + 1))

    for i, y in enumerate(rec_d):
        ax = fig.add_subplot(len(rec_d) + 1, 2, 4 + i * 2)
        ax.plot(y, 'g')
        ax.set_xlim(0, len(y) - 1)
        ax.set_ylabel("D%d" % (i + 1)) 
Example #16
Source File: test_dwt_idwt.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwt_single_axis():
    x = [[3, 7, 1, 1],
         [-2, 5, 4, 6]]

    cA, cD = pywt.dwt(x, 'db2', axis=-1)

    cA0, cD0 = pywt.dwt(x[0], 'db2')
    cA1, cD1 = pywt.dwt(x[1], 'db2')

    assert_allclose(cA[0], cA0)
    assert_allclose(cA[1], cA1)

    assert_allclose(cD[0], cD0)
    assert_allclose(cD[1], cD1) 
Example #17
Source File: test_dwt_idwt.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwt_idwt_basic_complex():
    x = np.asarray([3, 7, 1, 1, -2, 5, 4, 6])
    x = x + 0.5j*x
    cA, cD = pywt.dwt(x, 'db2')
    cA_expect = np.asarray([5.65685425, 7.39923721, 0.22414387, 3.33677403,
                            7.77817459])
    cA_expect = cA_expect + 0.5j*cA_expect
    cD_expect = np.asarray([-2.44948974, -1.60368225, -4.44140056, -0.41361256,
                            1.22474487])
    cD_expect = cD_expect + 0.5j*cD_expect
    assert_allclose(cA, cA_expect)
    assert_allclose(cD, cD_expect)

    x_roundtrip = pywt.idwt(cA, cD, 'db2')
    assert_allclose(x_roundtrip, x, rtol=1e-10) 
Example #18
Source File: test_dwt_idwt.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwt_idwt_dtypes():
    wavelet = pywt.Wavelet('haar')
    for dt_in, dt_out in zip(dtypes_in, dtypes_out):
        x = np.ones(4, dtype=dt_in)
        errmsg = "wrong dtype returned for {0} input".format(dt_in)

        cA, cD = pywt.dwt(x, wavelet)
        assert_(cA.dtype == cD.dtype == dt_out, "dwt: " + errmsg)

        x_roundtrip = pywt.idwt(cA, cD, wavelet)
        assert_(x_roundtrip.dtype == dt_out, "idwt: " + errmsg) 
Example #19
Source File: test_matlab_compatibility.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon):
    # PyWavelets result
    pa, pd = pywt.dwt(data, w, pmode)

    # calculate error measures
    rms_a = np.sqrt(np.mean((pa - ma) ** 2))
    rms_d = np.sqrt(np.mean((pd - md) ** 2))

    msg = ('[RMS_A > EPSILON] for Mode: %s, Wavelet: %s, '
           'Length: %d, rms=%.3g' % (pmode, wavelet, len(data), rms_a))
    assert_(rms_a < epsilon, msg=msg)

    msg = ('[RMS_D > EPSILON] for Mode: %s, Wavelet: %s, '
           'Length: %d, rms=%.3g' % (pmode, wavelet, len(data), rms_d))
    assert_(rms_d < epsilon, msg=msg) 
Example #20
Source File: test_concurrent.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_concurrent_dwt():
    # dwt on 1D data calls the Cython dwt_single
    # other cases call dwt_axis
    for dwt_func, x in zip([pywt.dwt, pywt.dwt2, pywt.dwtn],
                           [np.ones(8), np.eye(16), np.eye(16)]):
        transform = partial(dwt_func, wavelet='haar')
        for _ in range(10):
            arrs = [x.copy() for _ in range(100)]
            with futures.ThreadPoolExecutor(max_workers=max_workers) as ex:
                results = list(ex.map(transform, arrs))

        # validate result from  one of the concurrent runs
        expected_result = transform(x)
        _assert_all_coeffs_equal([expected_result, ], [results[-1], ]) 
Example #21
Source File: test_perfect_reconstruction.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def check_reconstruction(pmode, mmode, wavelet, dtype):
    data_size = list(range(2, 40)) + [100, 200, 500, 1000, 2000, 10000,
                                      50000, 100000]
    np.random.seed(12345)
    # TODO: smoke testing - more failures for different seeds

    if dtype == np.float32:
        # was 3e-7 has to be lowered as db21, db29, db33, db35, coif14, coif16 were failing
        epsilon = 6e-7
    else:
        epsilon = 5e-11

    for N in data_size:
        data = np.asarray(np.random.random(N), dtype)

        # compute dwt coefficients
        pa, pd = pywt.dwt(data, wavelet, pmode)

        # compute reconstruction
        rec = pywt.idwt(pa, pd, wavelet, pmode)

        if len(data) % 2:
            rec = rec[:len(data)]

        rms_rec = np.sqrt(np.mean((data-rec)**2))
        msg = ('[RMS_REC > EPSILON] for Mode: %s, Wavelet: %s, '
               'Length: %d, rms=%.3g' % (pmode, wavelet, len(data), rms_rec))
        assert_(rms_rec < epsilon, msg=msg) 
Example #22
Source File: test_deprecations.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_mode_equivalence():
    old_new = [('zpd', 'zero'),
               ('cpd', 'constant'),
               ('sym', 'symmetric'),
               ('ppd', 'periodic'),
               ('sp1', 'smooth'),
               ('per', 'periodization')]
    x = np.arange(8.)
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', DeprecationWarning)
        for old, new in old_new:
            assert_array_equal(pywt.dwt(x, 'db2', mode=old),
                               pywt.dwt(x, 'db2', mode=new))