Example #1
0
def test_per_axis_wavelets_and_modes():
    # tests seperate wavelet and edge mode for each axis.
    rstate = np.random.RandomState(1234)
    data = rstate.randn(16, 16, 16)

    # wavelet can be a string or wavelet object
    wavelets = (pywt.Wavelet('haar'), 'sym2', 'db4')

    # mode can be a string or a Modes enum
    modes = ('symmetric', 'periodization',
             pywt._extensions._pywt.Modes.reflect)

    coefs = pywt.dwtn(data, wavelets, modes)
    assert_allclose(pywt.idwtn(coefs, wavelets, modes), data, atol=1e-14)

    coefs = pywt.dwtn(data, wavelets[:1], modes)
    assert_allclose(pywt.idwtn(coefs, wavelets[:1], modes), data, atol=1e-14)

    coefs = pywt.dwtn(data, wavelets, modes[:1])
    assert_allclose(pywt.idwtn(coefs, wavelets, modes[:1]), data, atol=1e-14)

    # length of wavelets or modes doesn't match the length of axes
    assert_raises(ValueError, pywt.dwtn, data, wavelets[:2])
    assert_raises(ValueError, pywt.dwtn, data, wavelets, mode=modes[:2])
    assert_raises(ValueError, pywt.idwtn, coefs, wavelets[:2])
    assert_raises(ValueError, pywt.idwtn, coefs, wavelets, mode=modes[:2])

    # dwt2/idwt2 also support per-axis wavelets/modes
    data2 = data[..., 0]
    coefs2 = pywt.dwt2(data2, wavelets[:2], modes[:2])
    assert_allclose(pywt.idwt2(coefs2, wavelets[:2], modes[:2]), data2,
                    atol=1e-14)
Example #2
0
def test_negative_axes():
    data = np.array([[0, 1, 2, 3],
                     [1, 1, 1, 1],
                     [1, 4, 2, 8]])
    coefs1 = pywt.dwtn(data, 'haar', axes=(1, 1))
    coefs2 = pywt.dwtn(data, 'haar', axes=(-1, -1))
    assert_equal(coefs1, coefs2)

    rec1 = pywt.idwtn(coefs1, 'haar', axes=(1, 1))
    rec2 = pywt.idwtn(coefs1, 'haar', axes=(-1, -1))
    assert_equal(rec1, rec2)
Example #3
0
def test_idwtn_mixed_complex_dtype():
    rstate = np.random.RandomState(0)
    x = rstate.randn(8, 8, 8)
    x = x + 1j*x
    coeffs = pywt.dwtn(x, 'db2')

    x_roundtrip = pywt.idwtn(coeffs, 'db2')
    assert_allclose(x_roundtrip, x, rtol=1e-10)

    # mismatched dtypes OK
    coeffs['a' * x.ndim] = coeffs['a' * x.ndim].astype(np.complex64)
    x_roundtrip2 = pywt.idwtn(coeffs, 'db2')
    assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7)
    assert_(x_roundtrip2.dtype == np.complex128)
Example #4
0
def test_idwtn_none_coeffs():
    data = np.array([[0, 1, 2, 3],
                     [1, 1, 1, 1],
                     [1, 4, 2, 8]])
    data = data + 1j*data  # test with complex data
    coefs = pywt.dwtn(data, 'haar', axes=(1, 1))

    # verify setting coefficients to None is the same as zeroing them
    coefs['dd'] = np.zeros_like(coefs['dd'])
    result_zeros = pywt.idwtn(coefs, 'haar', axes=(1, 1))

    coefs['dd'] = None
    result_none = pywt.idwtn(coefs, 'haar', axes=(1, 1))

    assert_equal(result_zeros, result_none)
Example #5
0
def test_wavelet_decomposition3d_and_reconstruction3d():
    # Test 3D wavelet decomposition and reconstruction and verify that
    # they perform as expected
    x = np.random.rand(16, 16, 16)
    mode = 'sym'
    wbasis = pywt.Wavelet('db5')
    nscales = 1
    wavelet_coeffs = wavelet_decomposition3d(x, wbasis, mode, nscales)
    aaa = wavelet_coeffs[0]
    reference = pywt.dwtn(x, wbasis, mode)
    aaa_reference = reference['aaa']
    assert all_almost_equal(aaa, aaa_reference)

    reconstruction = wavelet_reconstruction3d(wavelet_coeffs, wbasis, mode,
                                              nscales)
    reconstruction_reference = pywt.idwtn(reference, wbasis, mode)
    assert all_almost_equal(reconstruction, reconstruction_reference)
    assert all_almost_equal(reconstruction, x)
    assert all_almost_equal(reconstruction_reference, x)

    wbasis = pywt.Wavelet('db1')
    nscales = 3
    wavelet_coeffs = wavelet_decomposition3d(x, wbasis, mode, nscales)
    shape_true = (nscales + 1, )
    assert all_equal(np.shape(wavelet_coeffs), shape_true)

    reconstruction = wavelet_reconstruction3d(wavelet_coeffs, wbasis, mode,
                                              nscales)
    assert all_almost_equal(reconstruction, x)
Example #6
0
def test_idwtn_axes():
    data = np.array([[0, 1, 2, 3],
                     [1, 1, 1, 1],
                     [1, 4, 2, 8]])
    data = data + 1j*data  # test with complex data
    coefs = pywt.dwtn(data, 'haar', axes=(1, 1))
    assert_allclose(pywt.idwtn(coefs, 'haar', axes=(1, 1)), data, atol=1e-14)
Example #7
0
def test_ignore_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)
    d = {"aa": LL, "da": HL, "ad": LH, "dd": HH, "foo": LH, "a": HH}

    assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet), pywt.idwtn(d, wavelet), atol=1e-15)
Example #8
0
def test_idwtn_take():
    data = np.array([
        [[1, 4, 1, 5, 1, 4],
         [0, 5, 6, 3, 2, 1],
         [2, 5, 19, 4, 19, 1]],
        [[1, 5, 1, 2, 3, 4],
         [7, 12, 6, 52, 7, 8],
         [5, 2, 6, 78, 12, 2]]])
    wavelet = pywt.Wavelet('haar')
    d = pywt.dwtn(data, wavelet)

    assert_(data.shape != pywt.idwtn(d, wavelet).shape)
    assert_allclose(data, pywt.idwtn(d, wavelet, take=data.shape), atol=1e-15)

    # Check shape for take not equal to data.shape
    data = np.random.randn(51, 17, 68)
    d = pywt.dwtn(data, wavelet)
    assert_equal((2, 2, 2), pywt.idwtn(d, wavelet, take=2).shape)
    assert_equal((52, 18, 68), pywt.idwtn(d, wavelet, take=0).shape)
Example #9
0
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:
        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 #10
0
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 #11
0
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 #12
0
def test_ignore_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)
    d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH,
         'foo': LH, 'a': HH}

    assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet),
                    pywt.idwtn(d, wavelet), atol=1e-15)
Example #13
0
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')

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

    assert_allclose(pywt.idwt2((LL, (HL, None, HH)), wavelet),
                    pywt.idwtn(d, 'haar'), atol=1e-15)
Example #14
0
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 #15
0
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 #16
0
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 #17
0
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 wavelet in ['cmor', 'shan', 'fbsp']:
            # skip these CWT families to avoid warnings
            continue
        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 #18
0
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 #19
0
reconstructed = pywt.idwt2(coeffs2, 'bior1.3')
fig = plt.figure()
plt.imshow(reconstructed, interpolation="nearest", cmap=plt.cm.gray)

# Check that reconstructed image is close to the original
np.testing.assert_allclose(original, reconstructed, atol=1e-13, rtol=1e-13)


# Now do the same with dwtn/idwtn, to show the difference in their signatures

coeffsn = pywt.dwtn(original, 'bior1.3')
fig = plt.figure()
for i, key in enumerate(['aa', 'ad', 'da', 'dd']):
    ax = fig.add_subplot(2, 2, i + 1)
    ax.imshow(coeffsn[key], origin='image', interpolation="nearest",
              cmap=plt.cm.gray)
    ax.set_title(titles[i], fontsize=12)

fig.suptitle("dwtn coefficients", fontsize=14)

# Now reconstruct and plot the original image
reconstructed = pywt.idwtn(coeffsn, 'bior1.3')
fig = plt.figure()
plt.imshow(reconstructed, interpolation="nearest", cmap=plt.cm.gray)

# Check that reconstructed image is close to the original
np.testing.assert_allclose(original, reconstructed, atol=1e-13, rtol=1e-13)


plt.show()
Example #20
0
def test_idwtn_axes_subsets():
    data = np.array(np.random.standard_normal((4, 4, 4, 4)))
    # test all combinations of 3 out of 4 axes transformed
    for axes in combinations((0, 1, 2, 3), 3):
        coefs = pywt.dwtn(data, 'haar', axes=axes)
        assert_allclose(pywt.idwtn(coefs, 'haar', axes=axes), data, atol=1e-14)
Example #21
0
 def time_idwtn(self, D, n, wavelet):
     pywt.idwtn(self.data, wavelet)
Example #22
0
def wavelet_reconstruction3d(coeff_list, wbasis, mode, nscales):
    """Discrete 3D multiresolution wavelet reconstruction

    Compute a discrete 3D multiresolution wavelet reconstruction
    from a given wavelet coefficient list.
    Utilizes a `PyWavelet
    <http://www.pybytes.com/pywavelets/ref/other-functions.html>`_
    function ``pywt.dwtn``

    Parameters
    ----------
    coeff_list : `list`
        A list of wavelet approximation and detail coefficients
        organized in the following way
        ```[caaaN, (aadN, adaN, addN, daaN, dadN, ddaN, dddN), ...
        (aad1, ada1, add1, daa1, dad1, dda1, ddd1)]```.

        The abbreviations refer to

        ``aaa`` = approx. on 1st dim, approx. on 2nd dim, approx. on 3rd dim,

        ``aad`` = approx. on 1st dim, approx. on 2nd dim, detail on3rd dim,

        ``ada`` = approx. on 1st dim, detail on 3nd dim, approx. on 3rd dim,

        ``add`` = approx. on 1st dim, detail on 3nd dim, detail on 3rd dim,

        ``daa`` = detail on 1st dim, approx. on 2nd dim, approx. on 3rd dim,

        ``dad`` = detail on 1st dim, approx. on 2nd dim, detail on 3rd dim,

        ``dda`` = detail on 1st dim, detail on 2nd dim, approx. on 3rd dim,

        ``ddd`` = detail on 1st dim, detail on 2nd dim, detail on 3rd dim,

        ``N`` = the number of scaling levels

    wbasis :  ``_pywt.Wavelet``
        Describes properties of a selected wavelet basis.
        For more information see PyWavelet `documentation
        <http://www.pybytes.com/pywavelets/ref/wavelets.html>`_

    mode : `str`
        Signal extention mode. For possible extensions see the
        `signal extenstion modes
        <http://www.pybytes.com/pywavelets/ref/\
signal-extension-modes.html>`_
        of PyWavelets.

    nscales : `int`
        Number of scales in the coefficient list.

    Returns
    -------
    x : `numpy.ndarray`.
        A wavalet reconstruction.
    """
    aaa = coeff_list[0]
    (aad, ada, add, daa, dad, dda, ddd) = coeff_list[1]
    coeff_dict = {'aaa': aaa, 'aad': aad, 'ada': ada, 'add': add,
                  'daa': daa, 'dad': dad, 'dda': dda, 'ddd': ddd}
    for tpl in coeff_list[2:]:
        aaa = pywt.idwtn(coeff_dict, wbasis, mode)
        (aad, ada, add, daa, dad, dda, ddd) = tpl
        coeff_dict = {'aaa': aaa, 'aad': aad, 'ada': ada, 'add': add,
                      'daa': daa, 'dad': dad, 'dda': dda, 'ddd': ddd}

    x = pywt.idwtn(coeff_dict, wbasis, mode)
    return x
Example #23
0
def pywt_single_level_recon(approx, details, wavelet, mode, recon_shape=None):
    """Return single level wavelet reconstruction from given coefficients.

    Parameters
    ----------
    approx : `array-like`
        Approximation coefficients.
    details : sequence of `array-like`'s
        Detail coefficients. The length of the sequence must be
        ``2 ** ndim - 1``, where ``ndim`` is the number of dimensions
        in ``approx``.
    wavelet :  string or `pywt.Wavelet`
        Specification of the wavelet to be used in the transform.
        Use `pywt.wavelist` to get a list of available wavelets.
    mode : string, optional
        PyWavelets style signal extension mode. See `signal extension modes`_
        for available options.
    recon_shape : sequence of ints, optional
        Shape of the array to be reconstructed. Without this parameter,
        the reconstructed array always has even shape due to upsampling
        by a factor of 2. To get reconstructions with odd shapes, this
        parameter is required.

    Returns
    -------
    recon : `numpy.ndarray`
        The single-level wavelet reconstruction.

    See Also
    --------
    pywt_single_level_decomp : Single-level decomposition, i.e. the
        inverse of this function.
    pywt_multi_level_recon : Multi-level version of the reconstruction.

    Examples
    --------
    Take the coefficients from the example in `pywt_single_level_decomp`
    and reconstruct the original array. Without ``recon_shape``, we get
    a ``(4, 4)`` array as reconstruction:

    >>> approx = [[1.5, 0.5],
    ...           [0.5, 0.5]]
    >>>
    >>> details = ([[ 0.5, 0.5],
    ...             [-0.5, 0.5]],
    ...            [[ 0.5, 0.5],
    ...             [ 0.5, 0.5]],
    ...            [[-0.5, 0.5],
    ...             [-0.5, 0.5]])
    >>> # Gives even shape by default
    >>> pywt_single_level_recon(approx, details, wavelet='haar', mode='zero')
    array([[ 1.,  1.,  1.,  0.],
           [ 1.,  0.,  0.,  0.],
           [ 0.,  1.,  1.,  0.],
           [ 0.,  0.,  0.,  0.]])
    >>> # Original shape can only be recovered if given explicitly
    >>> # in this case
    >>> pywt_single_level_recon(approx, details, wavelet='haar', mode='zero',
    ...                         recon_shape=(3, 3))
    array([[ 1.,  1.,  1.],
           [ 1.,  0.,  0.],
           [ 0.,  1.,  1.]])

    References
    ----------
    .. _signal extension modes:
       https://pywavelets.readthedocs.io/en/latest/ref/signal-extension-\
modes.html
    """
    # Handle input
    approx = np.asarray(approx)
    if len(details) != 2 ** approx.ndim - 1:
        raise ValueError('`details` must be a sequence of length {}, got '
                         'length {}'
                         .format(2 ** approx.ndim - 1, len(details)))
    details = tuple(np.asarray(detail) for detail in details)

    if recon_shape is not None:
        recon_shape, recon_shape_in = tuple(recon_shape), recon_shape
        if any(int(s) != s for s in recon_shape):
            raise ValueError('`recon_shape` may only contain integers, got {}'
                             ''.format(recon_shape_in))

    wavelet = pywt_wavelet(wavelet)
    mode, mode_in = str(mode).lower(), mode
    if mode not in PYWT_SUPPORTED_MODES:
        raise ValueError("mode '{}' not understood".format(mode_in))

    coeff_dict = {}
    dict_keys = pywt_dict_keys(np.ndim(approx))
    if len(details) != len(dict_keys) - 1:
        raise ValueError('wrong number of detail coefficients: expected {}, '
                         'got {}'.format(len(dict_keys) - 1, len(details)))
    coeff_dict[dict_keys[0]] = approx
    coeff_dict.update(zip(dict_keys[1:], details))
    recon = pywt.idwtn(coeff_dict, wavelet, mode)

    if recon_shape is not None:
        recon_slc = []
        for i, (n_recon, n_intended) in enumerate(zip(recon.shape,
                                                      recon_shape)):
            if n_recon == n_intended + 1:
                # Upsampling added one entry too much in this axis, drop
                # last one
                recon_slc.append(slice(-1))
            elif n_recon == n_intended:
                recon_slc.append(slice(None))
            else:
                raise ValueError('in axis {}: expected size {} or {} in '
                                 '`recon_shape`, got {}'
                                 ''.format(i, n_recon - 1, n_recon,
                                           n_intended))

        recon = recon[tuple(recon_slc)]

    return recon