Example #1
0
def test_fswavedecnresult():
    data = np.ones((32, 32))
    levels = (1, 2)
    result = pywt.fswavedecn(data, 'sym2', levels=levels)

    # can access the lowpass band via .approx or via __getitem__
    approx_key = (0, ) * data.ndim
    assert_array_equal(result[approx_key], result.approx)

    dkeys = result.detail_keys()
    # the approximation key shouldn't be present in the detail_keys
    assert_(approx_key not in dkeys)

    # can access all detail coefficients and they have matching ndim
    for k in dkeys:
        d = result[k]
        assert_equal(d.ndim, data.ndim)

    # can assign modified coefficients
    result[k] = np.zeros_like(d)

    # assigning a differently sized array raises a ValueError
    assert_raises(ValueError, result.__setitem__,
                  k, np.zeros(tuple([s + 1 for s in d.shape])))

    # warns on assigning with a non-matching dtype
    assert_warns(UserWarning, result.__setitem__,
                 k, np.zeros_like(d).astype(np.float32))

    # all coefficients are stacked into result.coeffs (same ndim)
    assert_equal(result.coeffs.ndim, data.ndim)
def test_fswavedecn_fswaverecn_variable_wavelets_and_modes():
    # test with differing number of transform levels per axis
    rstate = np.random.RandomState(0)
    ndim = 3
    data = rstate.standard_normal((16, ) * ndim)
    wavelets = ('haar', 'db2', 'sym3')
    modes = ('periodic', 'symmetric', 'periodization')
    T = pywt.fswavedecn(data, wavelet=wavelets, mode=modes)
    for ax in range(ndim):
        # expect approx + dwt_max_level detail coeffs along each axis
        assert_equal(len(T.coeff_slices[ax]),
                     pywt.dwt_max_level(data.shape[ax], wavelets[ax]) + 1)

    rec = pywt.fswaverecn(T)
    assert_allclose(rec, data, atol=1e-14)

    # number of wavelets doesn't match number of axes
    assert_raises(ValueError, pywt.fswavedecn, data, wavelets[:2])

    # number of modes doesn't match number of axes
    assert_raises(ValueError,
                  pywt.fswavedecn,
                  data,
                  wavelets[0],
                  mode=modes[:2])
def test_fswavedecnresult():
    data = np.ones((32, 32))
    levels = (1, 2)
    result = pywt.fswavedecn(data, 'sym2', levels=levels)

    # can access the lowpass band via .approx or via __getitem__
    approx_key = (0, ) * data.ndim
    assert_array_equal(result[approx_key], result.approx)

    dkeys = result.detail_keys()
    # the approximation key shouldn't be present in the detail_keys
    assert_(approx_key not in dkeys)

    # can access all detail coefficients and they have matching ndim
    for k in dkeys:
        d = result[k]
        assert_equal(d.ndim, data.ndim)

    # can assign modified coefficients
    result[k] = np.zeros_like(d)

    # assigning a differently sized array raises a ValueError
    assert_raises(ValueError, result.__setitem__, k,
                  np.zeros(tuple([s + 1 for s in d.shape])))

    # warns on assigning with a non-matching dtype
    assert_warns(UserWarning, result.__setitem__, k,
                 np.zeros_like(d).astype(np.float32))

    # all coefficients are stacked into result.coeffs (same ndim)
    assert_equal(result.coeffs.ndim, data.ndim)
Example #4
0
def test_fswavedecn_fswaverecn_zero_levels():
    # zero level transform gives coefs matching the original data
    rstate = np.random.RandomState(0)
    ndim = 2
    data = rstate.standard_normal((8, )*ndim)
    T = pywt.fswavedecn(data, 'haar', levels=0)
    assert_array_equal(T.coeffs, data)
    rec = pywt.fswaverecn(T)
    assert_array_equal(T.coeffs, rec)
def test_fswavedecn_fswaverecn_zero_levels():
    # zero level transform gives coefs matching the original data
    rstate = np.random.RandomState(0)
    ndim = 2
    data = rstate.standard_normal((8, ) * ndim)
    T = pywt.fswavedecn(data, 'haar', levels=0)
    assert_array_equal(T.coeffs, data)
    rec = pywt.fswaverecn(T)
    assert_array_equal(T.coeffs, rec)
def test_fswavedecn_fswaverecn_axes_subsets():
    """Fully separable DWT over only a subset of axes"""
    rstate = np.random.RandomState(0)
    # use anisotropic data to result in unique number of levels per axis
    data = rstate.standard_normal((4, 8, 16, 32))
    # test all combinations of 3 out of 4 axes transformed
    for axes in combinations((0, 1, 2, 3), 3):
        T = pywt.fswavedecn(data, 'haar', axes=axes)
        rec = pywt.fswaverecn(T)
        assert_allclose(rec, data, atol=1e-14)

    # some axes exceed data dimensions
    assert_raises(ValueError, pywt.fswavedecn, data, 'haar', axes=(1, 5))
Example #7
0
def test_fswavedecn_fswaverecn_axes_subsets():
    """Fully separable DWT over only a subset of axes"""
    rstate = np.random.RandomState(0)
    # use anisotropic data to result in unique number of levels per axis
    data = rstate.standard_normal((4, 8, 16, 32))
    # test all combinations of 3 out of 4 axes transformed
    for axes in combinations((0, 1, 2, 3), 3):
        T = pywt.fswavedecn(data, 'haar', axes=axes)
        rec = pywt.fswaverecn(T)
        assert_allclose(rec, data, atol=1e-14)

    # some axes exceed data dimensions
    assert_raises(ValueError, pywt.fswavedecn, data, 'haar', axes=(1, 5))
Example #8
0
def test_fswavedecn_fswaverecn_variable_levels():
    # test with differing number of transform levels per axis
    rstate = np.random.RandomState(0)
    ndim = 3
    data = rstate.standard_normal((16, )*ndim)
    T = pywt.fswavedecn(data, 'haar', levels=(1, 2, 3))
    rec = pywt.fswaverecn(T)
    assert_allclose(rec, data, atol=1e-14)

    # levels doesn't match number of axes
    assert_raises(ValueError, pywt.fswavedecn, data, 'haar', levels=(1, 1))
    assert_raises(ValueError, pywt.fswavedecn, data, 'haar', levels=(1, 1, 1, 1))

    # levels too large for array size
    assert_warns(UserWarning, pywt.fswavedecn, data, 'haar',
                 levels=int(np.log2(np.min(data.shape)))+1)
Example #9
0
def test_fswavedecn_fswaverecn_variable_levels():
    # test with differing number of transform levels per axis
    rstate = np.random.RandomState(0)
    ndim = 3
    data = rstate.standard_normal((16, )*ndim)
    T = pywt.fswavedecn(data, 'haar', levels=(1, 2, 3))
    rec = pywt.fswaverecn(T)
    assert_allclose(rec, data, atol=1e-14)

    # levels doesn't match number of axes
    assert_raises(ValueError, pywt.fswavedecn, data, 'haar', levels=(1, 1))
    assert_raises(ValueError, pywt.fswavedecn, data, 'haar', levels=(1, 1, 1, 1))

    # levels too large for array size
    assert_warns(UserWarning, pywt.fswavedecn, data, 'haar',
                 levels=int(np.log2(np.min(data.shape)))+1)
def test_fswavedecn_fswaverecn_roundtrip():
    # verify proper round trip result for 1D through 4D data
    # same DWT as wavedecn/waverecn so don't need to test all modes/wavelets
    rstate = np.random.RandomState(0)
    for ndim in range(1, 5):
        for dt_in, dt_out in zip(dtypes_in, dtypes_out):
            for levels in (1, None):
                data = rstate.standard_normal((8, ) * ndim)
                data = data.astype(dt_in)
                T = pywt.fswavedecn(data, 'haar', levels=levels)
                rec = pywt.fswaverecn(T)
                if data.real.dtype in [np.float32, np.float16]:
                    assert_allclose(rec, data, rtol=1e-6, atol=1e-6)
                else:
                    assert_allclose(rec, data, rtol=1e-14, atol=1e-14)
                assert_(T.coeffs.dtype == dt_out)
                assert_(rec.dtype == dt_out)
Example #11
0
def test_fswavedecn_fswaverecn_roundtrip():
    # verify proper round trip result for 1D through 4D data
    # same DWT as wavedecn/waverecn so don't need to test all modes/wavelets
    rstate = np.random.RandomState(0)
    for ndim in range(1, 5):
        for dt_in, dt_out in zip(dtypes_in, dtypes_out):
            for levels in (1, None):
                data = rstate.standard_normal((8, )*ndim)
                data = data.astype(dt_in)
                T = pywt.fswavedecn(data, 'haar', levels=levels)
                rec = pywt.fswaverecn(T)
                if data.real.dtype in [np.float32, np.float16]:
                    assert_allclose(rec, data, rtol=1e-6, atol=1e-6)
                else:
                    assert_allclose(rec, data, rtol=1e-14, atol=1e-14)
                assert_(T.coeffs.dtype == dt_out)
                assert_(rec.dtype == dt_out)
Example #12
0
def test_fswavedecn_fswaverecn_variable_wavelets_and_modes():
    # test with differing number of transform levels per axis
    rstate = np.random.RandomState(0)
    ndim = 3
    data = rstate.standard_normal((16, )*ndim)
    wavelets = ('haar', 'db2', 'sym3')
    modes = ('periodic', 'symmetric', 'periodization')
    T = pywt.fswavedecn(data, wavelet=wavelets, mode=modes)
    for ax in range(ndim):
        # expect approx + dwt_max_level detail coeffs along each axis
        assert_equal(len(T.coeff_slices[ax]),
                     pywt.dwt_max_level(data.shape[ax], wavelets[ax])+1)

    rec = pywt.fswaverecn(T)
    assert_allclose(rec, data, atol=1e-14)

    # number of wavelets doesn't match number of axes
    assert_raises(ValueError, pywt.fswavedecn, data, wavelets[:2])

    # number of modes doesn't match number of axes
    assert_raises(ValueError, pywt.fswavedecn, data, wavelets[0], mode=modes[:2])
            val = rstate.rand(1)[0]
            img[slices] = val
    return img


# create an anisotropic piecewise constant image
img = mondrian((128, 128))

# perform DWT
coeffs_dwt = pywt.wavedecn(img, wavelet='db1', level=None)

# convert coefficient dictionary to a single array
coeff_array_dwt, _ = pywt.coeffs_to_array(coeffs_dwt)

# perform fully seperable DWT
fswavedecn_result = pywt.fswavedecn(img, wavelet='db1')

nnz_dwt = np.sum(coeff_array_dwt != 0)
nnz_fswavedecn = np.sum(fswavedecn_result.coeffs != 0)

print("Number of nonzero wavedecn coefficients = {}".format(np.sum(nnz_dwt)))
print("Number of nonzero fswavedecn coefficients = {}".format(np.sum(nnz_fswavedecn)))

img = mondrian()
fig, axes = plt.subplots(1, 3)
imshow_kwargs = dict(cmap=plt.cm.gray, interpolation='nearest')
axes[0].imshow(img, **imshow_kwargs)
axes[0].set_title('Anisotropic Image')
axes[1].imshow(coeff_array_dwt != 0, **imshow_kwargs)
axes[1].set_title('Nonzero DWT\ncoefficients\n(N={})'.format(nnz_dwt))
axes[2].imshow(fswavedecn_result.coeffs != 0, **imshow_kwargs)
Example #14
0
def gz_ckernel(xp,
               yp,
               zp,
               prisms,
               dim=None,
               dens=None,
               wavelet='db1',
               levels=1,
               thresh=1.0e-4):
    """
    Calculates the compressed kernel matrix of gz.

    .. note:: The coordinate system of the input parameters is to be
        x -> North, y -> East and z -> **DOWN**.

    .. note:: All input values in **SI** units(!) and output in **mGal**!

    Parameters:

    * xp, yp, zp : arrays
        Arrays with the x, y, and z coordinates of the computation points.
    * prisms : list of :class:`~geoist.mesher.Prism`
        The density model used to calculate the gravitational effect.
        Prisms must have the property ``'density'``. Prisms that don't have
        this property will be ignored in the computations. Elements of *prisms*
        that are None will also be ignored. *prisms* can also be a
        :class:`~geoist.mesher.PrismMesh`.
    * dens : float or None
        If not None, will use this value instead of the ``'density'`` property
        of the prisms. Use this, e.g., for sensitivity matrix building.

    Returns:

    * res : csr_matrix
        The compressed kernel calculated on xp, yp, zp of prisms.

    """
    if xp.shape != yp.shape or xp.shape != zp.shape:
        raise ValueError("Input arrays xp, yp, and zp must have same length!")
    size = len(xp)
    n_prism = len(prisms)
    if dim is None:
        dim = [int(numpy.power(n_prism, 1. / 3.))] * 3
    res = numpy.zeros((size, n_prism), dtype=numpy.float)
    x1 = numpy.zeros(n_prism, dtype=numpy.float)
    x2 = numpy.zeros(n_prism, dtype=numpy.float)
    y1 = numpy.zeros(n_prism, dtype=numpy.float)
    y2 = numpy.zeros(n_prism, dtype=numpy.float)
    z1 = numpy.zeros(n_prism, dtype=numpy.float)
    z2 = numpy.zeros(n_prism, dtype=numpy.float)
    density = numpy.zeros(n_prism, dtype=numpy.float)
    for i, prism in enumerate(prisms):
        x1[i] = prism.x1
        x2[i] = prism.x2
        y1[i] = prism.y1
        y2[i] = prism.y2
        z1[i] = prism.z1
        z2[i] = prism.z2
        density[i] = prism.props['density']
    if dens is not None:
        density = dens
    count = 0
    data = []
    indices = []
    indptr = [0]
    tmpptr = 0
    for i, x in enumerate(xp):
        tmp = numpy.zeros(n_prism, dtype=numpy.float)
        _prism.gz_prisms(xp[i], yp[i], zp[i], x1, x2, y1, y2, z1, z2, density,
                         tmp)
        tmp = pywt.fswavedecn(tmp.reshape(*dim), wavelet, levels=levels)
        for key in tmp.detail_keys():
            maxa = numpy.max(numpy.abs(tmp[key]))
            filt_data = numpy.abs(tmp[key]) < (thresh * maxa)
            count += numpy.sum(filt_data)
            tmp[key][filt_data] = 0.0
        rowdata = tmp.coeffs.ravel() * G * SI2MGAL
        data.append(rowdata[rowdata != 0.0])
        tmpind = numpy.where(rowdata != 0.0)[0]
        indices.append(tmpind)
        tmpptr += len(tmpind)
        indptr.append(tmpptr)
    res = csr_matrix((numpy.hstack(data), numpy.hstack(indices), indptr),
                     shape=(len(xp), len(prisms)))
    return res
Example #15
0
            val = rstate.rand(1)[0]
            img[slices] = val
    return img


# create an anisotropic piecewise constant image
img = mondrian((128, 128))

# perform DWT
coeffs_dwt = pywt.wavedecn(img, wavelet='db1', level=None)

# convert coefficient dictionary to a single array
coeff_array_dwt, _ = pywt.coeffs_to_array(coeffs_dwt)

# perform fully seperable DWT
fswavedecn_result = pywt.fswavedecn(img, wavelet='db1')

nnz_dwt = np.sum(coeff_array_dwt != 0)
nnz_fswavedecn = np.sum(fswavedecn_result.coeffs != 0)

print("Number of nonzero wavedecn coefficients = {}".format(np.sum(nnz_dwt)))
print("Number of nonzero fswavedecn coefficients = {}".format(np.sum(nnz_fswavedecn)))

img = mondrian()
fig, axes = plt.subplots(1, 3)
imshow_kwargs = dict(cmap=plt.cm.gray, interpolation='nearest')
axes[0].imshow(img, **imshow_kwargs)
axes[0].set_title('Anisotropic Image')
axes[1].imshow(coeff_array_dwt != 0, **imshow_kwargs)
axes[1].set_title('Nonzero DWT\ncoefficients\n(N={})'.format(nnz_dwt))
axes[2].imshow(fswavedecn_result.coeffs != 0, **imshow_kwargs)
Example #16
0
import numpy as np
from matplotlib import pyplot as plt
import pywt

img = pywt.data.camera().astype(float)

# Fully separable transform
fswavedecn_result = pywt.fswavedecn(img, 'db2', 'periodization', levels=4)

# Standard DWT
coefs = pywt.wavedec2(img, 'db2', 'periodization', level=4)
# convert DWT coefficients to a 2D array
mallat_array, mallat_slices = pywt.coeffs_to_array(coefs)


fig, (ax1, ax2) = plt.subplots(1, 2)

ax1.imshow(np.abs(mallat_array)**0.25,
           cmap=plt.cm.gray,
           interpolation='nearest')
ax1.set_axis_off()
ax1.set_title('Mallat decomposition\n(wavedec2)')

ax2.imshow(np.abs(fswavedecn_result.coeffs)**0.25,
           cmap=plt.cm.gray,
           interpolation='nearest')
ax2.set_axis_off()
ax2.set_title('Fully separable decomposition\n(fswt)')

plt.show()
Example #17
0
import numpy as np
from matplotlib import pyplot as plt
import pywt

img = pywt.data.camera().astype(float)

# Fully separable transform
fswavedecn_result = pywt.fswavedecn(img, 'db2', 'periodization', levels=4)

# Standard DWT
coefs = pywt.wavedec2(img, 'db2', 'periodization', level=4)
# convert DWT coefficients to a 2D array
mallat_array, mallat_slices = pywt.coeffs_to_array(coefs)

fig, (ax1, ax2) = plt.subplots(1, 2)

ax1.imshow(np.abs(mallat_array)**0.25,
           cmap=plt.cm.gray,
           interpolation='nearest')
ax1.set_axis_off()
ax1.set_title('Mallat decomposition\n(wavedec2)')

ax2.imshow(np.abs(fswavedecn_result.coeffs)**0.25,
           cmap=plt.cm.gray,
           interpolation='nearest')
ax2.set_axis_off()
ax2.set_title('Fully separable decomposition\n(fswt)')

plt.show()