Python pywt.Wavelet() Examples

The following are 30 code examples of pywt.Wavelet(). 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: utils.py    From mne-features with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def _wavelet_coefs(data, wavelet_name='db4'):
    """Compute Discrete Wavelet Transform coefficients.

    Parameters
    ----------
    data : ndarray, shape (n_channels, n_times)

    wavelet_name : str (default: db4)
         Wavelet name (to be used with ``pywt.Wavelet``). The full list of
         Wavelet names are given by: ``[name for family in pywt.families() for
         name in pywt.wavelist(family)]``.

    Returns
    -------
    coefs : list of ndarray
         Coefficients of a DWT (Discrete Wavelet Transform). ``coefs[0]`` is
         the array of approximation coefficient and ``coefs[1:]`` is the list
         of detail coefficients.
    """
    wavelet = pywt.Wavelet(wavelet_name)
    levdec = min(pywt.dwt_max_level(data.shape[-1], wavelet.dec_len), 6)
    coefs = pywt.wavedec(data, wavelet=wavelet, level=levdec)
    return coefs 
Example #2
Source File: test_swt.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_swt_dtypes():
    wavelet = pywt.Wavelet('haar')
    for dt_in, dt_out in zip(dtypes_in, dtypes_out):
        errmsg = "wrong dtype returned for {0} input".format(dt_in)

        # swt
        x = np.ones(8, dtype=dt_in)
        (cA2, cD2), (cA1, cD1) = pywt.swt(x, wavelet, level=2)
        assert_(cA2.dtype == cD2.dtype == cA1.dtype == cD1.dtype == dt_out,
                "swt: " + errmsg)

        # swt2
        with warnings.catch_warnings():
            warnings.simplefilter('ignore', FutureWarning)
            x = np.ones((8, 8), dtype=dt_in)
            cA, (cH, cV, cD) = pywt.swt2(x, wavelet, level=1)[0]
            assert_(cA.dtype == cH.dtype == cV.dtype == cD.dtype == dt_out,
                    "swt2: " + errmsg) 
Example #3
Source File: test_multilevel.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_waverecn_coeff_reshape_odd():
    # verify round trip is correct:
    #   wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn
    rng = np.random.RandomState(1234)
    x1 = rng.randn(35, 33)
    for mode in pywt.Modes.modes:
        for wave in ['haar', ]:
            w = pywt.Wavelet(wave)
            maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len)
            if maxlevel == 0:
                continue
            coeffs = pywt.wavedecn(x1, w, mode=mode)
            coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs)
            coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices)
            x1r = pywt.waverecn(coeffs2, w, mode=mode)
            # truncate reconstructed values to original shape
            x1r = x1r[[slice(s) for s in x1.shape]]
            assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4) 
Example #4
Source File: test_multilevel.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_wavedecn_coeff_reshape_even():
    # verify round trip is correct:
    #   wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn
    # This is done for wavedec{1, 2, n}
    rng = np.random.RandomState(1234)
    params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec},
              'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2},
              'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}}
    N = 28
    for f in params:
        x1 = rng.randn(*([N] * params[f]['d']))
        for mode in pywt.Modes.modes:
            for wave in wavelist:
                w = pywt.Wavelet(wave)
                maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len)
                if maxlevel == 0:
                    continue

                coeffs = params[f]['dec'](x1, w, mode=mode)
                coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs)
                coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices,
                                               output_format=f)
                x1r = params[f]['rec'](coeffs2, w, mode=mode)

                assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4) 
Example #5
Source File: test_multidim.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_3D_reconstruct_complex():
    # All dimensions even length so `take` does not need to be specified
    data = np.array([
        [[0, 4, 1, 5, 1, 4],
         [0, 5, 26, 3, 2, 1],
         [5, 8, 2, 33, 4, 9],
         [2, 5, 19, 4, 19, 1]],
        [[1, 5, 1, 2, 3, 4],
         [7, 12, 6, 52, 7, 8],
         [2, 12, 3, 52, 6, 8],
         [5, 2, 6, 78, 12, 2]]])
    data = data + 1j

    wavelet = pywt.Wavelet('haar')
    d = pywt.dwtn(data, wavelet)
    # idwtn creates even-length shapes (2x dwtn size)
    original_shape = [slice(None, s) for s in data.shape]
    assert_allclose(data, pywt.idwtn(d, wavelet)[original_shape],
                    rtol=1e-13, atol=1e-13) 
Example #6
Source File: test_multidim.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_stride():
    wavelet = pywt.Wavelet('haar')

    for dtype in ('float32', 'float64'):
        data = np.array([[0, 4, 1, 5, 1, 4],
                         [0, 5, 6, 3, 2, 1],
                         [2, 5, 19, 4, 19, 1]],
                        dtype=dtype)

        for mode in pywt.Modes.modes:
            expected = pywt.dwtn(data, wavelet)
            strided = np.ones((3, 12), dtype=data.dtype)
            strided[::-1, ::2] = data
            strided_dwtn = pywt.dwtn(strided[::-1, ::2], wavelet)
            for key in expected.keys():
                assert_allclose(strided_dwtn[key], expected[key]) 
Example #7
Source File: test_multidim.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_idwtn_missing():
    # Test to confirm missing data behave as zeroes
    data = np.array([
        [0, 4, 1, 5, 1, 4],
        [0, 5, 6, 3, 2, 1],
        [2, 5, 19, 4, 19, 1]])

    wavelet = pywt.Wavelet('haar')

    coefs = pywt.dwtn(data, wavelet)

    # No point removing zero, or all
    for num_missing in range(1, len(coefs)):
        for missing in combinations(coefs.keys(), num_missing):
            missing_coefs = coefs.copy()
            for key in missing:
                del missing_coefs[key]
            LL = missing_coefs.get('aa', None)
            HL = missing_coefs.get('da', None)
            LH = missing_coefs.get('ad', None)
            HH = missing_coefs.get('dd', None)

            assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet),
                            pywt.idwtn(missing_coefs, 'haar'), atol=1e-15) 
Example #8
Source File: test_multidim.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_error_on_invalid_keys():
    data = np.array([
        [0, 4, 1, 5, 1, 4],
        [0, 5, 6, 3, 2, 1],
        [2, 5, 19, 4, 19, 1]])

    wavelet = pywt.Wavelet('haar')

    LL, (HL, LH, HH) = pywt.dwt2(data, wavelet)

    # unexpected key
    d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH, 'ff': LH}
    assert_raises(ValueError, pywt.idwtn, d, wavelet)

    # mismatched key lengths
    d = {'a': LL, 'da': HL, 'ad': LH, 'dd': HH}
    assert_raises(ValueError, pywt.idwtn, d, wavelet) 
Example #9
Source File: test_wavelet.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_custom_wavelet():
    haar_custom1 = pywt.Wavelet('Custom Haar Wavelet',
                                filter_bank=_CustomHaarFilterBank())
    haar_custom1.orthogonal = True
    haar_custom1.biorthogonal = True

    val = np.sqrt(2) / 2
    filter_bank = ([val]*2, [-val, val], [val]*2, [val, -val])
    haar_custom2 = pywt.Wavelet('Custom Haar Wavelet',
                                filter_bank=filter_bank)

    # check expected default wavelet properties
    assert_(~haar_custom2.orthogonal)
    assert_(~haar_custom2.biorthogonal)
    assert_(haar_custom2.symmetry == 'unknown')
    assert_(haar_custom2.family_name == '')
    assert_(haar_custom2.short_family_name == '')
    assert_(haar_custom2.vanishing_moments_phi == 0)
    assert_(haar_custom2.vanishing_moments_psi == 0)

    # Some properties can be set by the user
    haar_custom2.orthogonal = True
    haar_custom2.biorthogonal = True 
Example #10
Source File: test_wavelet.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def check_coefficients(wavelet):
    epsilon = 5e-11
    level = 10
    w = pywt.Wavelet(wavelet)
    # Lowpass filter coefficients sum to sqrt2
    res = np.sum(w.dec_lo)-np.sqrt(2)
    msg = ('[RMS_REC > EPSILON] for Wavelet: %s, rms=%.3g' % (wavelet, res))
    assert_(res < epsilon, msg=msg)
    # sum even coef = sum odd coef = 1 / sqrt(2)
    res = np.sum(w.dec_lo[::2])-1./np.sqrt(2)
    msg = ('[RMS_REC > EPSILON] for Wavelet: %s, rms=%.3g' % (wavelet, res))
    assert_(res < epsilon, msg=msg)

    res = np.sum(w.dec_lo[1::2])-1./np.sqrt(2)
    msg = ('[RMS_REC > EPSILON] for Wavelet: %s, rms=%.3g' % (wavelet, res))
    assert_(res < epsilon, msg=msg)
    # Highpass filter coefficients sum to zero
    res = np.sum(w.dec_hi)
    msg = ('[RMS_REC > EPSILON] for Wavelet: %s, rms=%.3g' % (wavelet, res))
    assert_(res < epsilon, msg=msg) 
Example #11
Source File: test_multidim.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_3D_reconstruct():
    data = np.array([
        [[0, 4, 1, 5, 1, 4],
         [0, 5, 26, 3, 2, 1],
         [5, 8, 2, 33, 4, 9],
         [2, 5, 19, 4, 19, 1]],
        [[1, 5, 1, 2, 3, 4],
         [7, 12, 6, 52, 7, 8],
         [2, 12, 3, 52, 6, 8],
         [5, 2, 6, 78, 12, 2]]])

    wavelet = pywt.Wavelet('haar')
    for mode in pywt.Modes.modes:
        d = pywt.dwtn(data, wavelet, mode=mode)
        assert_allclose(data, pywt.idwtn(d, wavelet, mode=mode),
                        rtol=1e-13, atol=1e-13) 
Example #12
Source File: test_wavelet.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_wavelet_properties():
    w = pywt.Wavelet('db3')

    # Name
    assert_(w.name == 'db3')
    assert_(w.short_family_name == 'db')
    assert_(w.family_name, 'Daubechies')

    # String representation
    fields = ('Family name', 'Short name', 'Filters length', 'Orthogonal',
              'Biorthogonal', 'Symmetry')
    for field in fields:
        assert_(field in str(w))

    # Filter coefficients
    dec_lo = [0.03522629188210, -0.08544127388224, -0.13501102001039,
              0.45987750211933, 0.80689150931334, 0.33267055295096]
    dec_hi = [-0.33267055295096, 0.80689150931334, -0.45987750211933,
              -0.13501102001039, 0.08544127388224, 0.03522629188210]
    rec_lo = [0.33267055295096, 0.80689150931334, 0.45987750211933,
              -0.13501102001039, -0.08544127388224, 0.03522629188210]
    rec_hi = [0.03522629188210, 0.08544127388224, -0.13501102001039,
              -0.45987750211933, 0.80689150931334, -0.33267055295096]
    assert_allclose(w.dec_lo, dec_lo)
    assert_allclose(w.dec_hi, dec_hi)
    assert_allclose(w.rec_lo, rec_lo)
    assert_allclose(w.rec_hi, rec_hi)

    assert_(len(w.filter_bank) == 4)

    # Orthogonality
    assert_(w.orthogonal)
    assert_(w.biorthogonal)

    # Symmetry
    assert_(w.symmetry)

    # Vanishing moments
    assert_(w.vanishing_moments_phi == 0)
    assert_(w.vanishing_moments_psi == 3) 
Example #13
Source File: test_swt.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_swt2_axes():
    atol = 1e-14
    current_wavelet = pywt.Wavelet('db2')
    input_length_power = int(np.ceil(np.log2(max(
        current_wavelet.dec_len,
        current_wavelet.rec_len))))
    input_length = 2**(input_length_power)
    X = np.arange(input_length**2).reshape(input_length, input_length)
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', FutureWarning)
        (cA1, (cH1, cV1, cD1)) = pywt.swt2(X, current_wavelet, level=1)[0]
        # opposite order
        (cA2, (cH2, cV2, cD2)) = pywt.swt2(X, current_wavelet, level=1,
                                           axes=(1, 0))[0]
        assert_allclose(cA1, cA2, atol=atol)
        assert_allclose(cH1, cV2, atol=atol)
        assert_allclose(cV1, cH2, atol=atol)
        assert_allclose(cD1, cD2, atol=atol)

        # duplicate axes not allowed
        assert_raises(ValueError, pywt.swt2, X, current_wavelet, 1,
                      axes=(0, 0))
        # too few axes
        assert_raises(ValueError, pywt.swt2, X, current_wavelet, 1, axes=(0, )) 
Example #14
Source File: wavelets.py    From opensurfaces with MIT License 6 votes vote down vote up
def compute_wavelet_feature_vector(image, wavelet='db6'):
    image_np = np.array(image)
    rgb = [image_np[:, :, i] for i in (0, 1, 2)]

    if isinstance(wavelet, basestring):
        wavelet = pywt.Wavelet(wavelet)

    feature_vector = []
    for c in rgb:
        level = pywt.dwt_max_level(min(c.shape[0], c.shape[1]), wavelet.dec_len)
        levels = pywt.wavedec2(c, wavelet, mode='sym', level=level)
        for coeffs in levels:
            if not isinstance(coeffs, tuple):
                coeffs = (coeffs,)
            for w in coeffs:
                w_flat = w.flatten()
                feature_vector += [float(np.mean(w_flat)), float(np.std(w_flat))]

    return feature_vector 
Example #15
Source File: test_matlab_compatibility.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def test_accuracy_pymatbridge():
    rstate = np.random.RandomState(1234)
    # max RMSE (was 1.0e-10, is reduced to 5.0e-5 due to different coefficents)
    epsilon = 5.0e-5
    epsilon_pywt_coeffs = 1.0e-10
    mlab.start()
    try:
        for wavelet in wavelets:
            w = pywt.Wavelet(wavelet)
            mlab.set_variable('wavelet', wavelet)
            for N in _get_data_sizes(w):
                data = rstate.randn(N)
                mlab.set_variable('data', data)
                for pmode, mmode in modes:
                    ma, md = _compute_matlab_result(data, wavelet, mmode)
                    yield _check_accuracy, data, w, pmode, ma, md, wavelet, epsilon
                    ma, md = _load_matlab_result_pywt_coeffs(data, wavelet, mmode)
                    yield _check_accuracy, data, w, pmode, ma, md, wavelet, epsilon_pywt_coeffs

    finally:
        mlab.stop() 
Example #16
Source File: test_matlab_compatibility.py    From DeepLearning_Wavelet-LSTM with MIT License 6 votes vote down vote up
def _compute_matlab_result(data, wavelet, mmode):
    """ Compute the result using MATLAB.

    This function assumes that the Matlab variables `wavelet` and `data` have
    already been set externally.
    """
    if np.any((wavelet == np.array(['coif6', 'coif7', 'coif8', 'coif9', 'coif10', 'coif11', 'coif12', 'coif13', 'coif14', 'coif15', 'coif16', 'coif17'])),axis=0):
        w = pywt.Wavelet(wavelet)
        mlab.set_variable('Lo_D', w.dec_lo)
        mlab.set_variable('Hi_D', w.dec_hi)
        mlab_code = ("[ma, md] = dwt(data, Lo_D, Hi_D, 'mode', '%s');" % mmode)
    else:
        mlab_code = "[ma, md] = dwt(data, wavelet, 'mode', '%s');" % mmode
    res = mlab.run_code(mlab_code)
    if not res['success']:
        raise RuntimeError("Matlab failed to execute the provided code. "
                           "Check that the wavelet toolbox is installed.")
    # need np.asarray because sometimes the output is a single float64
    ma = np.asarray(mlab.get_variable('ma'))
    md = np.asarray(mlab.get_variable('md'))
    return ma, md 
Example #17
Source File: test_dwt_idwt.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwt_wavelet_kwd():
    x = np.array([3, 7, 1, 1, -2, 5, 4, 6])
    w = pywt.Wavelet('sym3')
    cA, cD = pywt.dwt(x, wavelet=w, mode='constant')
    cA_expect = [4.38354585, 3.80302657, 7.31813271, -0.58565539, 4.09727044,
                 7.81994027]
    cD_expect = [-1.33068221, -2.78795192, -3.16825651, -0.67715519,
                 -0.09722957, -0.07045258]
    assert_allclose(cA, cA_expect)
    assert_allclose(cD, cD_expect) 
Example #18
Source File: test_functions.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_intwave_orthogonal():
    w = pywt.Wavelet('db1')
    int_psi, x = pywt.integrate_wavelet(w, precision=12)
    ix = x < 0.5
    # For x < 0.5, the integral is equal to x
    assert_allclose(int_psi[ix], x[ix])
    # For x > 0.5, the integral is equal to (1 - x)
    # Ignore last point here, there x > 1 and something goes wrong
    assert_allclose(int_psi[~ix][:-1], 1 - x[~ix][:-1], atol=1e-10) 
Example #19
Source File: test_functions.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_scal2frq_scale():
    scale = 2
    w = pywt.Wavelet('db1')
    expected = 1. / scale
    result = pywt.scale2frequency(w, scale, precision=12)
    assert_almost_equal(result, expected, decimal=3) 
Example #20
Source File: test_dwt_idwt.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwt_coeff_len():
    x = np.array([3, 7, 1, 1, -2, 5, 4, 6])
    w = pywt.Wavelet('sym3')
    ln_modes = [pywt.dwt_coeff_len(len(x), w.dec_len, mode) for mode in
                pywt.Modes.modes]

    expected_result = [6, ] * len(pywt.Modes.modes)
    expected_result[pywt.Modes.modes.index('periodization')] = 4

    assert_allclose(ln_modes, expected_result)
    ln_modes = [pywt.dwt_coeff_len(len(x), w, mode) for mode in
                pywt.Modes.modes]
    assert_allclose(ln_modes, expected_result) 
Example #21
Source File: test_multidim.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwdtn_idwtn_allwavelets():
    rstate = np.random.RandomState(1234)
    r = rstate.randn(16, 16)
    # test 2D case only for all wavelet types
    wavelist = pywt.wavelist()
    if 'dmey' in wavelist:
        wavelist.remove('dmey')
    for wavelet in wavelist:
        if isinstance(pywt.DiscreteContinuousWavelet(wavelet), pywt.Wavelet):
            for mode in pywt.Modes.modes:
                coeffs = pywt.dwtn(r, wavelet, mode=mode)
                assert_allclose(pywt.idwtn(coeffs, wavelet, mode=mode),
                                r, rtol=1e-7, atol=1e-7) 
Example #22
Source File: wavelet.py    From vampyre with MIT License 5 votes vote down vote up
def recon(self,z1):
        """
        Wavelet reconstruction:  coefficients -> image
        """
        coeffs = pywt.array_to_coeffs(z1, self.coeff_slices, \
            output_format='wavedec2')
        z0 = pywt.waverec2(coeffs, wavelet=self.wavelet, mode=self.mode)
        return z0 
Example #23
Source File: test_multidim.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_idwtn_idwt2():
    data = np.array([
        [0, 4, 1, 5, 1, 4],
        [0, 5, 6, 3, 2, 1],
        [2, 5, 19, 4, 19, 1]])

    wavelet = pywt.Wavelet('haar')

    LL, (HL, LH, HH) = pywt.dwt2(data, wavelet)
    d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH}

    for mode in pywt.Modes.modes:
        assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet, mode=mode),
                        pywt.idwtn(d, wavelet, mode=mode),
                        rtol=1e-14, atol=1e-14) 
Example #24
Source File: test_multidim.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_idwtn_idwt2_complex():
    data = np.array([
        [0, 4, 1, 5, 1, 4],
        [0, 5, 6, 3, 2, 1],
        [2, 5, 19, 4, 19, 1]])
    data = data + 1j
    wavelet = pywt.Wavelet('haar')

    LL, (HL, LH, HH) = pywt.dwt2(data, wavelet)
    d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH}

    for mode in pywt.Modes.modes:
        assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet, mode=mode),
                        pywt.idwtn(d, wavelet, mode=mode),
                        rtol=1e-14, atol=1e-14) 
Example #25
Source File: test_multidim.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwt2_idwt2_dtypes():
    wavelet = pywt.Wavelet('haar')
    for dt_in, dt_out in zip(dtypes_in, dtypes_out):
        x = np.ones((4, 4), dtype=dt_in)
        errmsg = "wrong dtype returned for {0} input".format(dt_in)

        cA, (cH, cV, cD) = pywt.dwt2(x, wavelet)
        assert_(cA.dtype == cH.dtype == cV.dtype == cD.dtype,
                "dwt2: " + errmsg)

        x_roundtrip = pywt.idwt2((cA, (cH, cV, cD)), wavelet)
        assert_(x_roundtrip.dtype == dt_out, "idwt2: " + errmsg) 
Example #26
Source File: test_multidim.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwtn_idwtn_dtypes():
    wavelet = pywt.Wavelet('haar')
    for dt_in, dt_out in zip(dtypes_in, dtypes_out):
        x = np.ones((4, 4), dtype=dt_in)
        errmsg = "wrong dtype returned for {0} input".format(dt_in)

        coeffs = pywt.dwtn(x, wavelet)
        for k, v in coeffs.items():
            assert_(v.dtype == dt_out, "dwtn: " + errmsg)

        x_roundtrip = pywt.idwtn(coeffs, wavelet)
        assert_(x_roundtrip.dtype == dt_out, "idwtn: " + errmsg) 
Example #27
Source File: test_multidim.py    From DeepLearning_Wavelet-LSTM with MIT License 5 votes vote down vote up
def test_dwt2_dimension_error():
    data = np.ones(16)
    wavelet = pywt.Wavelet('haar')

    # wrong number of input dimensions
    assert_raises(ValueError, pywt.dwt2, data, wavelet)

    # too many axes
    data2 = np.ones((8, 8))
    assert_raises(ValueError, pywt.dwt2, data2, wavelet, axes=(0, 1, 1)) 
Example #28
Source File: dtcwt.py    From scikit-ued with MIT License 5 votes vote down vote up
def dt_max_level(data, first_stage, wavelet, axis=-1):
    """
    Returns the maximum decomposition level possible from the dual-tree complex wavelet transform.

    Parameters
    ----------
    data : ndarray
        Input data. Can be of any dimension.
    first_stage : str
        Wavelet to use for the first stage. See :func:`skued.available_first_stage_filters` for a list of suitable arguments
    wavelet : str
        Wavelet to use in stages > 1. Must be appropriate for the dual-tree complex wavelet transform.
        See :func:`skued.available_dt_filters` for possible values.
    axis : int, optional
        Axis over which to compute the transform. Default is -1
        
    Returns
    -------
    max_level : int
        Maximum decomposition level.
    """
    real_wavelet, imag_wavelet = dualtree_wavelet(wavelet)
    return dwt_max_level(
        data_len=data.shape[axis],
        filter_len=max([real_wavelet.dec_len, imag_wavelet.dec_len]),
    ) 
Example #29
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 #30
Source File: dtcwt.py    From scikit-ued with MIT License 5 votes vote down vote up
def _single_tree_synthesis_1d(coeffs, first_stage, wavelet, mode, axis):
    """
    Single tree of the inverse dual-tree complex wavelet transform.

    Parameters
    ----------
    coeffs : list
    first_stage : Wavelet object
    wavelet : 2-tuple of Wavelet objects
    mode : str
    axis : int

    Returns
    -------
    reconstructed : ndarray, ndim 1
    """
    # Determine the level except first stage:
    # The order of wavelets depends on whether
    # the level is even or odd.
    level = len(coeffs) - 1
    approx, detail_coeffs, first_stage_detail = coeffs[0], coeffs[1:-1], coeffs[-1]

    # Set the right alternating order between real and imag wavelet
    if level % 2 == 1:
        wavelet = reversed(wavelet)

    # In the case of level = 1, coeffs[1:-1] is an empty list. Then, the following
    # loop is not run since zip() iterates as long as the shortest iterable.
    for detail, wav in zip(detail_coeffs, cycle(wavelet)):
        approx = _normalize_size_axis(approx, detail, axis=axis)
        approx = idwt(cA=approx, cD=detail, wavelet=wav, mode=mode, axis=axis)

    approx = _normalize_size_axis(approx, first_stage_detail, axis=axis)
    return idwt(
        cA=approx, cD=first_stage_detail, wavelet=first_stage, mode=mode, axis=axis
    )