Пример #1
0
    def __init__(self, n_basis, family, n_aux=15):
        self.n_basis = n_basis

        ## Generate wavelet on fine grid
        wav = pywt.DiscreteContinuousWavelet(family)
        _, self.wavelet, self.x_grid = wav.wavefun(n_aux)
        self.N = max(self.x_grid)
Пример #2
0
def test_swt2_iswt2_integration():
    # This function performs a round-trip swt2/iswt2 transform test on
    # all available types of wavelets in PyWavelets - except the
    # 'dmey' wavelet. The latter has been excluded because it does not
    # produce very precise results. This is likely due to the fact
    # that the 'dmey' wavelet is a discrete approximation of a
    # continuous wavelet. All wavelets are tested up to 3 levels. The
    # test validates neither swt2 or iswt2 as such, but it does ensure
    # that they are each other's inverse.

    max_level = 3
    wavelets = pywt.wavelist()
    if 'dmey' in wavelets:
        # The 'dmey' wavelet seems to be a bit special - disregard it for now
        wavelets.remove('dmey')
    for current_wavelet_str in wavelets:
        current_wavelet = pywt.DiscreteContinuousWavelet(current_wavelet_str)
        if isinstance(current_wavelet, pywt.Wavelet):
            input_length_power = int(
                np.ceil(
                    np.log2(
                        max(current_wavelet.dec_len,
                            current_wavelet.rec_len))))
            input_length = 2**(input_length_power + max_level - 1)
            X = np.arange(input_length**2).reshape(input_length, input_length)

            with warnings.catch_warnings():
                warnings.simplefilter('ignore', FutureWarning)
                coeffs = pywt.swt2(X, current_wavelet, max_level)
                Y = pywt.iswt2(coeffs, current_wavelet)
            assert_allclose(Y, X, rtol=1e-5, atol=1e-5)
Пример #3
0
def test_error_on_continuous_wavelet():
    # A ValueError is raised if a Continuous wavelet is selected
    data = np.ones((32, ))
    for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]:
        assert_raises(ValueError, pywt.dwt, data, cwave)

        cA, cD = pywt.dwt(data, 'db1')
        assert_raises(ValueError, pywt.idwt, cA, cD, cwave)
Пример #4
0
def test_error_on_continuous_wavelet():
    # A ValueError is raised if a Continuous wavelet is selected
    data = np.ones((16, 16))
    for dec_fun, rec_fun in zip([pywt.wavedec, pywt.wavedec2, pywt.wavedecn],
                                [pywt.waverec, pywt.waverec2, pywt.waverecn]):
        for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]:
            assert_raises(ValueError, dec_fun, data, wavelet=cwave)

            c = dec_fun(data, 'db1')
            assert_raises(ValueError, rec_fun, c, wavelet=cwave)
Пример #5
0
def test_error_on_continuous_wavelet():
    # A ValueError is raised if a Continuous wavelet is selected
    data = np.ones((16, 16))
    for dec_func, rec_func in zip([pywt.swt, pywt.swt2, pywt.swtn],
                                  [pywt.iswt, pywt.iswt2, pywt.iswtn]):
        for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]:
            assert_raises(ValueError, dec_func, data, wavelet=cwave, level=3)

            c = dec_func(data, 'db1', level=3)
            assert_raises(ValueError, rec_func, c, wavelet=cwave)
Пример #6
0
def test_error_on_continuous_wavelet():
    # A ValueError is raised if a Continuous wavelet is selected
    data = np.ones((16, 16))
    with warnings.catch_warnings():  # avoid FutureWarning in swt2
        warnings.simplefilter('ignore', FutureWarning)
        for dec_func, rec_func in zip([pywt.swt, pywt.swt2, pywt.swtn],
                                      [pywt.iswt, pywt.iswt2, pywt.iswtn]):
            for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]:
                assert_raises(ValueError, dec_func, data, wavelet=cwave,
                              level=3)

                c = dec_func(data, 'db1', level=3)
                assert_raises(ValueError, rec_func, c, wavelet=cwave)
Пример #7
0
def wavelet_basis(responses, n_basis, family='db4'):
    """Evaluates Daubechies basis.

    Arguments
    ----------
    responses : array
        An array of responses in [0, 1].
    n_basis : integer
        The number of basis functions to evaluate.
    family : string
        The wavelet family to evaluate.

    Returns
    -------
    numpy matrix
        A matrix of Fourier basis functions evaluated at `responses`. Each row
        corresponds to a value of `responses`, each column corresponds to a
        basis function.

    """
    responses = responses.flatten()

    n_aux = 15
    rez = pywt.DiscreteContinuousWavelet(family).wavefun(n_aux)
    if len(rez) == 2:
        wavelet, x_grid = rez
    else:
        _, wavelet, x_grid = rez
    wavelet *= np.sqrt(max(x_grid) - min(x_grid))
    x_grid = (x_grid - min(x_grid)) / (max(x_grid) - min(x_grid))

    def _wave_fun(val):
        if val < 0 or val > 1:
            return 0.0
        return wavelet[np.argmin(abs(val - x_grid))]

    n_obs = responses.shape[0]
    basis = np.empty((n_obs, n_basis))
    basis[:, 0] = 1.0

    loc = 0
    level = 0
    for col in range(1, n_basis):
        basis[:, col] = [
            2**(level / 2) * _wave_fun(a * 2**level - loc) for a in responses
        ]
        loc += 1
        if loc == 2**level:
            loc = 0
            level += 1
    return basis
Пример #8
0
def cwt_tf(data, scales, wavelet, batch_size, sampling_period=1.):

    # accept array_like input; make a copy to ensure a contiguous array
    dt = tf.float32
    dt_cplx = tf.complex64
    if not isinstance(wavelet, (pywt.ContinuousWavelet, pywt.Wavelet)):
        wavelet = pywt.DiscreteContinuousWavelet(wavelet)
    if np.isscalar(scales):
        scales = np.array([scales])

    dt_out = dt_cplx if wavelet.complex_cwt else dt
    out = []
    precision = 10
    int_psi, x = pywt.integrate_wavelet(wavelet, precision=precision)
    int_psi = np.conj(int_psi) if wavelet.complex_cwt else int_psi

    # convert int_psi, x to the same precision as the data
    dt_psi = np.complex64 if int_psi.dtype.kind == 'c' else np.float32
    int_psi = np.asarray(int_psi, dtype=dt_psi)
    x = np.asarray(x, dtype=np.float32)

    for i, scale in enumerate(scales):
        step = x[1] - x[0]
        j = np.arange(scale * (x[-1] - x[0]) + 1) / (scale * step)
        j = j.astype(int)  # floor
        if j[-1] >= int_psi.size:
            j = np.extract(j < int_psi.size, j)
        int_psi_scale = int_psi[j][::-1]
        int_psi_scale_n = np.zeros(
            (len(int_psi_scale), data.shape[-1], data.shape[-1]),
            dtype=int_psi_scale.dtype)
        for c in range(data.shape[-1]):
            int_psi_scale_n[:, c, c] = int_psi_scale

        conv = tf.nn.convolution(data, int_psi_scale_n, 1, 'SAME')

        coef = -tf.math.sqrt(float(scale)) * tf.experimental.numpy.diff(
            conv, axis=-2)

        if dt_out != dt_cplx:
            coef = tf.math.real(coef)

        out += [tf.cast(tf.abs(coef), dt_out)]

#     frequencies = pywt.scale2frequency(wavelet, scales, precision)
#     if np.isscalar(frequencies):
#         frequencies = np.array([frequencies])
#     frequencies /= sampling_period
    return tf.transpose(tf.convert_to_tensor(out, dtype=dt_out),
                        (1, 0, 2, 3))  #, frequencies
Пример #9
0
def test_compare_downcoef_coeffs():
    rstate = np.random.RandomState(1234)
    r = rstate.randn(16)
    # compare downcoef against wavedec outputs
    for nlevels in [1, 2, 3]:
        for wavelet in pywt.wavelist():
            wavelet = pywt.DiscreteContinuousWavelet(wavelet)
            if isinstance(wavelet, pywt.Wavelet):
                max_level = pywt.dwt_max_level(r.size, wavelet.dec_len)
                if nlevels <= max_level:
                    a = pywt.downcoef('a', r, wavelet, level=nlevels)
                    d = pywt.downcoef('d', r, wavelet, level=nlevels)
                    coeffs = pywt.wavedec(r, wavelet, level=nlevels)
                    assert_allclose(a, coeffs[0])
                    assert_allclose(d, coeffs[1])
Пример #10
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 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)
Пример #11
0
    ]
except AttributeError:
    pass

# determine which wavelets to test
wavelist = pywt.wavelist()
if 'dmey' in wavelist:
    # accuracy is very low for dmey, so omit it
    wavelist.remove('dmey')

# removing wavelets with dwt_possible == False
del_list = []
for wavelet in wavelist:
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', FutureWarning)
        if not isinstance(pywt.DiscreteContinuousWavelet(wavelet),
                          pywt.Wavelet):
            del_list.append(wavelet)
for del_ind in del_list:
    wavelist.remove(del_ind)

####
# 1d multilevel dwt tests
####


def test_wavedec():
    x = [3, 7, 1, 1, -2, 5, 4, 6]
    db1 = pywt.Wavelet('db1')
    cA3, cD3, cD2, cD1 = pywt.wavedec(x, db1)
    assert_almost_equal(cA3, [8.83883476])
Пример #12
0
from scipy.signal import stft
import numpy as np
import pywt

scale = ['C', 'C♯', 'D', 'E♭', 'E', 'F', 'F♯', 'G', 'G♯', 'A', 'B♭', 'B']
# Stereo audio; take only the first channel.
rate, data = read("marySongOrig.wav")
data0 = data  #[:, 0]

# For wavelet transform, let the input data stream be even.
# Get rid of the first element if the amount of data is odd.
if len(data0) % 2 == 1:
    data0 = data0[1:]

# Obtain wavelet.
db1 = pywt.DiscreteContinuousWavelet('db1')

# Denoise the wave using the SureShrink method, where SURE
# is Stein's Unbiased Risk Estimate. Use stationary wavelet
# transform.
# Take the inner product of the original audio with the
# Daubechies wavelet db1. In the time-freq-domain, use soft-
# thresholding to reduce frequencies below a threshold,
# then apply Inverse Stationary Wavelet Transform to get the
# denoised signal. Assume noise is white Gaussian.
output = pywt.swt(data0, db1)


# Measure the threshold.
# Here we use Donoho and Johnstone's method to estimate the
# noise level σ. This is based on the last level of the
Пример #13
0
import pywt

wavelet = pywt.DiscreteContinuousWavelet('db1')
print(wavelet)

wavelet = pywt.DiscreteContinuousWavelet('gaus1')
print(wavelet)
Пример #14
0
def fastcwt(data, scales, wavelet, sampling_period=1.0, method='auto'):
    """
    Compute the continuous wavelet transform (CWT) and has the same signature
    as ``pywt.cwt()`` but is faster for large signals length and scales.

    Parameters
    ----------
    signal : array to compute the CWT on
    
    scales: dilatation factors for the CWT
    
    wavelet: wavelet name or pywt.ContinuousWavelet

    method=['auto'] | 'conv' | 'fft' for selecting the convolution method
        the `'auto'` keyword switch automatically to the best complexity at each
        scales. While the `'fft'` and `'conv'` uses `numpy.fft` and `numpy.conv`
        respectively.

    In practice the `'fft'` method is implemented by using the convolution 
    theorem which states::
        convolve(wav,sig) == ifft(fft(wav)*fft(sig))

    Zero padding is adjusted to keep at bay circular convolution side effects.


    Example::

        %time (coef1, freq1) = fastcwt(np.arange(140000), np.arange(2,200), 'cmorl1-1')
        => CPU times: user 12.6 s, sys: 2.2 s, total: 14.8 s
        => Wall time: 14.9 s

        %time (coef1, freq1) = pywt.cwt(np.arange(140000), np.arange(2,200), 'cmorl1-1')
        => CPU times: user 1min 50s, sys: 401 ms, total: 1min 51s
        => Wall time: 1min 51s
    """

    # accept array_like input; make a copy to ensure a contiguous array
    data = np.array(data)
    if not isinstance(wavelet, (pywt.ContinuousWavelet, pywt.Wavelet)):
        wavelet = pywt.DiscreteContinuousWavelet(wavelet)
    if np.isscalar(scales):
        scales = np.array([scales])
    dt_out = None  # currently keep the 1.0.2 behaviour: TODO fix in/out dtype consistency
    if data.ndim == 1:
        if wavelet.complex_cwt:
            dt_out = complex
        out = np.zeros((np.size(scales), data.size), dtype=dt_out)
        precision = 10
        int_psi, x = pywt.integrate_wavelet(wavelet, precision=precision)

        if method in ('auto', 'fft'):
            # - to be as large as the sum of data length and and maximum wavelet
            #   support to avoid circular convolution effects
            # - additional padding to reach a power of 2 for CPU-optimal FFT
            size_pad = lambda s: 2**np.int(np.ceil(np.log2(s[0] + s[1])))
            size_scale0 = size_pad(
                (len(data), np.take(scales, 0) * ((x[-1] - x[0]) + 1)))
            fft_data = None
        elif not method == 'conv':
            raise ValueError("method must be in: 'conv', 'fft' or 'auto'")

        for i in np.arange(np.size(scales)):
            step = x[1] - x[0]
            j = np.floor(
                np.arange(scales[i] * (x[-1] - x[0]) + 1) / (scales[i] * step))
            if np.max(j) >= np.size(int_psi):
                j = np.delete(j, np.where((j >= np.size(int_psi)))[0])
            int_psi_scale = int_psi[j.astype(np.int)][::-1]

            if method == 'conv':
                conv = np.convolve(data, int_psi_scale)
            else:
                size_scale = size_pad((len(data), len(int_psi_scale)))
                if size_scale != size_scale0:
                    # the fft of data changes when padding size changes thus
                    # it has to be recomputed
                    fft_data = None
                size_scale0 = size_scale
                nops_conv = len(data) * len(int_psi_scale)
                nops_fft = (
                    2 + (fft_data is None)) * size_scale * np.log2(size_scale)
                if (method == 'fft') or ((method == 'auto') and
                                         (nops_fft < nops_conv)):
                    if fft_data is None:
                        fft_data = np.fft.fft(data, size_scale)
                    fft_wav = np.fft.fft(int_psi_scale, size_scale)
                    conv = np.fft.ifft(fft_wav * fft_data)
                    conv = conv[0:len(data) + len(int_psi_scale) - 1]
                else:
                    conv = np.convolve(data, int_psi_scale)

            coef = -np.sqrt(scales[i]) * np.diff(conv)
            if not np.iscomplexobj(out):
                coef = np.real(coef)
            d = (coef.size - data.size) / 2.
            if d > 0:
                out[i, :] = coef[int(np.floor(d)):int(-np.ceil(d))]
            elif d == 0.:
                out[i, :] = coef
            else:
                raise ValueError("Selected scale of {} too small.".format(
                    scales[i]))
        frequencies = pywt.scale2frequency(wavelet, scales, precision)
        if np.isscalar(frequencies):
            frequencies = np.array([frequencies])
        for i in np.arange(len(frequencies)):
            frequencies[i] /= sampling_period
        return out, frequencies
    else:
        raise ValueError("Only dim == 1 supported")
Пример #15
0
    res = 1 / np.log(2) * (k + np.log(2000 / 30) + gamma(k) + (k + 1) * sum_s)
    plt.plot(k, res)
    plt.grid()
    plt.xlabel('k')
    plt.ylabel('H(k)')
    plt.show()


#H()
import pywt
from pylab import *
from numpy import *
discrete_wavelets = ['db5', 'sym4', 'coif5', 'haar']
print('discrete_wavelets-%s' % discrete_wavelets)
st = 'db4'
wavelet = pywt.DiscreteContinuousWavelet(st)
print(wavelet)
i = 10
phi, psi, x = wavelet.wavefun(level=i)

#title("График самой вейвлет - функции -%s"%st)
'''plot(x,psi,linewidth=2, label='level=%s'%i)
grid()'''
#legend(loc='best')

title(st)
plt.plot(x, phi, linewidth=2, label='level=%s' % i)
#legend(loc='best')
grid()
show()