Exemplo n.º 1
0
def test_ben():
    LB = -5
    UB = 5
    N = 1000
    Fc = 1.1
    [psi, x] = ref_ben(LB, UB, N,Fc)
    w = pywt.ContinuousWavelet("ben-{}".format(Fc))
    assert_almost_equal(w.center_frequency, Fc)
    w.upper_bound = UB
    w.lower_bound = LB
    PSI, X = w.wavefun(length=N)

    assert_allclose(np.real(PSI), np.real(psi))
    assert_allclose(np.imag(PSI), np.imag(psi))
    assert_allclose(X, x)

    LB = -5
    UB = 5
    N = 1001

    [psi, x] = ref_ben(LB, UB, N,Fc)
    w = pywt.ContinuousWavelet("ben-{}".format(Fc))
    assert_almost_equal(w.center_frequency, Fc)
    w.upper_bound = UB
    w.lower_bound = LB
    PSI, X = w.wavefun(length=N)

    assert_allclose(np.real(PSI), np.real(psi))
    assert_allclose(np.imag(PSI), np.imag(psi))
    assert_allclose(X, x)
Exemplo n.º 2
0
def test_mexh():
    LB = -5
    UB = 5
    N = 1000

    [psi, x] = ref_mexh(LB, UB, N)
    w = pywt.ContinuousWavelet("mexh")
    w.upper_bound = UB
    w.lower_bound = LB
    PSI, X = w.wavefun(length=N)

    assert_allclose(np.real(PSI), np.real(psi))
    assert_allclose(np.imag(PSI), np.imag(psi))
    assert_allclose(X, x)

    LB = -5
    UB = 5
    N = 1001

    [psi, x] = ref_mexh(LB, UB, N)
    w = pywt.ContinuousWavelet("mexh")
    w.upper_bound = UB
    w.lower_bound = LB
    PSI, X = w.wavefun(length=N)

    assert_allclose(np.real(PSI), np.real(psi))
    assert_allclose(np.imag(PSI), np.imag(psi))
    assert_allclose(X, x)
Exemplo n.º 3
0
def perform_wavelet_analysis(time_series, central_freq, sampling_rate,
                             peak_tresh):
    mean = sum(time_series) / len(time_series)
    time_series = time_series - mean
    ts = 1 / sampling_rate
    central_scale = sampling_rate / central_freq
    wav = pywt.ContinuousWavelet('cmor2-1.0')
    f_bound_high = central_scale / 2
    f_bound_low = central_scale / 2
    bands = 64
    widths = np.linspace(central_scale - f_bound_high,
                         central_scale + f_bound_low, bands)
    # (IMPORTANTE) devo trovare la formula che lega direttamente la frequenza rilevata dalla fft coi parametri da settare per le wavelets
    # in pratica ho capito che a bassissime frequenze non ho bisogno di un numero di bande superiore a 50
    # oltretutto a basse frequenze l'analisi wavelet è molto più lenta
    # un altro parametro molto importante è la larghezza della banda di analisi
    # il limite inferiore (in frequenza) deve essere aumentato
    # 6 Hz -> bands = 100, f_bound_high = central_scale / 20, f_bound_low = central_scale / 80
    # 0.15 Hz -> bands = 20, f_bound_high = central_scale / 3, f_bound_low = central_scale / 1
    cwtmatr, freqs = pywt.cwt(time_series, widths, wav, ts)
    cwt_freq_peaks = []
    times = 0
    for time_stamp in cwtmatr.T:  # [int(len(cwtmatr.T)/3):int(len(cwtmatr.T)*2/3)]:
        abs_ts = abs(time_stamp)
        max_value = max(abs_ts)
        indexes = peakutils.indexes(abs_ts, thres=peak_tresh, min_dist=20)
        for i in indexes:
            cwt_freq_peaks.append(freqs[i])
        times = times + 1
    #print("Peaks: " + str(cwt_freq_peaks))
    #print("Freqs: " + str(freqs))
    freq_det_cwt = np.mean(cwt_freq_peaks)
    return cwtmatr, freq_det_cwt
def IC_FC_detection(data, scale=10, thres=0.65):
    """
    This function will do two continuous wavelet
    tranformations and will detect IC and FC
    respectively by the peak times detected.
    * Data: is the data we want to do the CWT over
    * Scale: is the scale that we want to use to
    extract a specific frequency
    * Thres: is the threshold used for detecting peaks
    """
    wavelet = pywt.ContinuousWavelet("gaus2")  # We use a Gaussian Wavelet

    # IC
    coefs, _ = pywt.cwt(data, scale, wavelet)
    final = coefs[0]
    IC = peakutils.indexes(
        -final, thres, min_dist=25)  # predefined interval from 0.25 to 2.25s

    # FC
    coefs_2, _ = pywt.cwt(final, scale, wavelet)
    final_2 = coefs_2[0]
    FC = peakutils.indexes(
        final_2, thres, min_dist=25)  # predefined interval from 0.25 to 2.25s

    return final, final_2, IC, FC
Exemplo n.º 5
0
def test_accuracy_pymatbridge_cwt():
    rstate = np.random.RandomState(1234)
    # max RMSE (was 1.0e-10, is reduced to 5.0e-5 due to different coefficents)
    epsilon = 1e-15
    epsilon_psi = 1e-15
    mlab.start()
    try:
        for wavelet in wavelets:
            with warnings.catch_warnings():
                warnings.simplefilter('ignore', FutureWarning)
                w = pywt.ContinuousWavelet(wavelet)
            if np.any((wavelet == np.array(['shan', 'cmor'])), axis=0):
                mlab.set_variable(
                    'wavelet', wavelet + str(w.bandwidth_frequency) + '-' +
                    str(w.center_frequency))
            elif wavelet == 'fbsp':
                mlab.set_variable(
                    'wavelet', wavelet + str(w.fbsp_order) + '-' +
                    str(w.bandwidth_frequency) + '-' + str(w.center_frequency))
            else:
                mlab.set_variable('wavelet', wavelet)
            mlab_code = ("psi = wavefun(wavelet,10)")
            res = mlab.run_code(mlab_code)
            psi = np.asarray(mlab.get_variable('psi'))
            yield _check_accuracy_psi, w, psi, wavelet, epsilon_psi
            for N in _get_data_sizes(w):
                data = rstate.randn(N)
                mlab.set_variable('data', data)
                for scales in _get_scales(w):
                    coefs = _compute_matlab_result(data, wavelet, scales)
                    yield _check_accuracy, data, w, scales, coefs, wavelet, epsilon

    finally:
        mlab.stop()
Exemplo n.º 6
0
def describe(signal):
    w = pywt.ContinuousWavelet('mexh')
    signal_with_noise = signal + np.random.uniform(-0.5, 0.5, N)

    amp, scales = pywt.cwt(signal_with_noise,
                           2**np.arange(7),
                           w,
                           sampling_period=0.25)
    to_show = 5

    def reconstruction_plot(yyy, color='r'):
        """Plot signal vector on x [0,1] independently of amount of values it contains."""
        length = len(yyy)
        mean = length // 2
        delta = length // to_show // 2
        plt.plot(
            np.linspace(0, 1, length)[mean - delta:mean + delta + 1],
            yyy[mean - delta:mean + delta + 1], color)
        # plt.plot(np.linspace(0, 1, len(yyy)), yyy, color)

    # plt.plot(np.linspace(0, 1, N)[:N//to_show + 1],
    #          signal_with_noise[:N//to_show + 1], 'b')
    reconstruction_plot(signal_with_noise, 'orange')
    reconstruction_plot(amp[0], 'r')
    reconstruction_plot(amp[2], 'g')
    plt.show()
def identify_scale(Vz, plot_this=False):
    """
    This function will identify the main
    wave scale that the data contains.
    It is optimized to identify walking
    bouts from accelerometer' measurements.
    """
    scale = list(np.arange(1, 150, 1))
    wavelet = pywt.ContinuousWavelet("gaus2")

    coefs, _ = pywt.cwt(Vz, scale, wavelet)

    averages = list()
    for i in coefs:
        averages.append(np.average(abs(i)))

    if plot_this:
        plt.plot(scale, averages)
        plt.title("Scale Optimization")
        plt.show()
    # We want to get the first peak as it should
    # symbolize the first main frequency.
    peaks, _ = find_peaks(averages)

    if len(peaks) == 0:
        return max(averages)

    else:
        return peaks[0]
def _create_scaleogram(signal: np.ndarray,
                       graph_wavelet_signal: bool) -> np.ndarray:
    """Creates scaleogram for signal.
    """
    # Length of the signal: 128
    n = len(signal)
    time_list = np.arange(n)
    # Scale 1 corresponds to a wavelet of width 17 (lower_bound=-8, upper_bound=8).
    # Scale n corresponds to a wavelet of width n*17.
    scale_list = np.arange(0, n) / 8 + 1
    wavelet = 'mexh'
    scaleogram = pywt.cwt(signal, scale_list, wavelet)[0]
    scaleogram = _normalize(scaleogram)

    if graph_wavelet_signal:
        signal = _normalize(signal)
        x = np.append([time_list], [time_list], axis=0)

        # Graph the narrowest wavelet together with the signal.
        [wav_narrowest,
         _] = pywt.ContinuousWavelet(wavelet).wavefun(length=n *
                                                      int(scale_list[0]))
        y = np.append([wav_narrowest], [signal], axis=0)
        utils_graph.graph_overlapping_lines(
            x, y, ['Mexican hat wavelet', 'Signal'], 'Time', 'Scale',
            'Example of a signal and narrowest wavelet', PLOTS_FOLDER,
            'sample_narrowest_wavelet.html')

        # Graph the widest wavelet together with the signal.
        # wavefun gives us the original wavelet, with a width of 17 (scale=1).
        # We want to stretch that signal by scale_list[n-1].
        # So we oversample the wavelet computation and take the n points in
        # the middle.
        [wav_widest,
         _] = pywt.ContinuousWavelet(wavelet).wavefun(length=n *
                                                      int(scale_list[n - 1]))
        middle = len(wav_widest) // 2
        lower_bound = middle - n // 2
        upper_bound = lower_bound + n
        wav_widest = wav_widest[lower_bound:upper_bound]
        y = np.append([wav_widest], [signal], axis=0)
        utils_graph.graph_overlapping_lines(
            x, y, ['Mexican hat wavelet', 'Signal'], 'Time', 'Scale',
            'Example of a signal and widest wavelet', PLOTS_FOLDER,
            'sample_widest_wavelet.html')

    return scaleogram
Exemplo n.º 9
0
def dominant_wavenumber(field, grid, n_scales=120, smoothing=(21, 7)):
    """Dominant zonal wavenumber at every gridpoint of field.

    Implements the procedure of Ghinassi et al. (2018) based on a wavelet
    analysis of the input field.

    - `n_scales` determines the number of scales used in the continuous wavelet
      transform.
    - `smoothing` determines the full width at half maximum of the Hann filter
      in zonal and meridional direction in degrees longitude/latitude.

    Returns the gridded dominant zonal wavenumber.

    Requires `pywt` (version >= 1.1.0) and `scipy`.
    """
    import pywt
    from scipy import signal
    # Truncate zonal fourier spectrum of meridional wind after wavenumber 20
    x = _restrict_fourier_zonal(field, 0, 20)
    # Triplicate field to avoid boundary issues (pywt.cwt does not support
    # periodic mode as of version 1.1)
    x = np.hstack([x, x, x])
    # Use the complex Morlet wavelet
    morlet = pywt.ContinuousWavelet("cmor1.0-1.0")
    # ...
    scales = 3 * 2**np.linspace(0, 6, n_scales)
    # Apply the continuous wavelet transform
    coef, freqs = pywt.cwt(x, scales=scales, wavelet=morlet, axis=_ZONAL)
    # Extract the middle domain, throw away the periodic padding
    ii = coef.shape[-1] // 3
    coef = coef[:, :, ii:-ii]
    # Obtain the power spectrum
    power = np.abs(coef)**2
    # Determine wavenumbers from scales
    wavenum = pywt.scale2frequency(morlet, scales) * grid.shape[_ZONAL]
    # Dominant wavenumber is that of maximum power in the spectrum
    dom_wavenum = wavenum[np.argmax(power, axis=0)]
    # Smooth dominant wavenumber with Hann windows. Window width is given as
    # full width at half maximum, which is half of the full width. Choose the
    # nearest odd number of gridpoints available to the desired value.
    smooth_lon, smooth_lat = smoothing
    hann_lon = signal.windows.hann(
        int(smooth_lon / 360 * grid.shape[_ZONAL]) * 2 + 1)
    hann_lon = hann_lon / np.sum(hann_lon)
    hann_lat = signal.windows.hann(
        int(smooth_lat / 180 * grid.shape[_MERIDIONAL]) * 2 + 1)
    hann_lat = hann_lat / np.sum(hann_lat)
    # Apply zonal filter first with periodic boundary
    dom_wavenum = signal.convolve2d(dom_wavenum,
                                    hann_lon[None, :],
                                    mode="same",
                                    boundary="wrap")
    # Then apply meridional filter with symmetrical boundary
    dom_wavenum = signal.convolve2d(dom_wavenum,
                                    hann_lat[:, None],
                                    mode="same",
                                    boundary="symm")
    return dom_wavenum
Exemplo n.º 10
0
def scalo2sig(scalo, name, scales=np.arange(1, 128), wavelet='morl'):
    mwf = pywt.ContinuousWavelet(wavelet).wavefun()
    y_0 = mwf[0][np.argmin(np.abs(mwf[1]))]
    r_sum = np.transpose(np.sum(np.transpose(scalo) / scales**0.5, axis=-1))
    audio = r_sum * (1 / y_0)
    newDir = './Audio_Results/audio_from_scalo'
    if not os.path.exists(newDir):
        os.makedirs(newDir)
    sf.write(f"{newDir}/{name}.wav", audio, 22500)
Exemplo n.º 11
0
def _wavelet_instance(wavelet):
    """Function responsible for returning the correct pywt.ContinuousWavelet
    """
    if isinstance(wavelet, pywt.ContinuousWavelet):
        return wavelet
    if isinstance(wavelet, six.string_types):
        return pywt.ContinuousWavelet(wavelet)
    else:
        raise ValueError("Expecting a string name for the wavelet," +
                         " or pywt.ContinuousWavelet. Got: " + str(wavelet))
Exemplo n.º 12
0
def get_list_of_continuous_wavelets():
    l = []
    for name in pywt.wavelist(kind='continuous'):
        # supress warnings when the wavelet name is missing parameters
        completion = {
            'cmor': 'cmor1.5-1.0',
            'fbsp': 'fbsp1-1.5-1.0',
            'shan': 'shan1.5-1.0' }
        if name in completion:
            name =  completion[name]# supress warning
        l.append( name+" :\t"+pywt.ContinuousWavelet(name).family_name )
    return l
Exemplo n.º 13
0
def test_cgau():
    LB = -5
    UB = 5
    N = 1000
    for num in np.arange(1, 9):
        [psi, x] = ref_cgau(LB, UB, N, num)
        w = pywt.ContinuousWavelet("cgau" + str(num))
        PSI, X = w.wavefun(length=N)

        assert_allclose(np.real(PSI), np.real(psi))
        assert_allclose(np.imag(PSI), np.imag(psi))
        assert_allclose(X, x)
def test_accuracy_precomputed_cwt():
    # Keep this specific random seed to match the precomputed Matlab result.
    rstate = np.random.RandomState(1234)
    # has to be improved
    epsilon = 1e-15
    epsilon32 = 1e-5
    epsilon_psi = 1e-15
    for wavelet in wavelets:
        w = pywt.ContinuousWavelet(wavelet)
        w32 = pywt.ContinuousWavelet(wavelet, dtype=np.float32)
        psi = _load_matlab_result_psi(wavelet)
        yield _check_accuracy_psi, w, psi, wavelet, epsilon_psi

        for N in _get_data_sizes(w):
            data = rstate.randn(N)
            data32 = data.astype(np.float32)
            scales_count = 0
            for scales in _get_scales(w):
                scales_count += 1
                coefs = _load_matlab_result(data, wavelet, scales_count)
                yield _check_accuracy, data, w, scales, coefs, wavelet, epsilon
                yield _check_accuracy, data32, w32, scales, coefs, wavelet, epsilon32
Exemplo n.º 15
0
    def __init__(self, id=0):
        with open("config/wavelets/default_wavelet.json") as f:
            data = json.load(f)

        config = load_config(id, data)

        self.B = float(config["wavelet"]["B"])
        self.C = float(config["wavelet"]["C"])
        self.name = config["wavelet"]["name"]
        self.min_scales = int(config["wavelet"]["min_scales"])
        self.max_scales = int(config["wavelet"]["max_scales"])
        self.scales = np.arange(self.min_scales, self.max_scales)
        self.wavelet = pywt.ContinuousWavelet('%s%s-%s' % (self.name, self.B, self.C))
Exemplo n.º 16
0
    def do_pywt_transform(data,
                          quality=44100,
                          scalogram_quality=2000,
                          base_freq=30000,
                          num_octaves=2,
                          voices_per_octave=50):
        """Actually perform the wavelet transform, using the PyWavelet module."""
        CORRECTION_FACTOR = 10000
        try:
            import pywt
        except ImportError:
            print(
                "Sorry, you need the PyWavelets (\"pywt\") module to create scalograms.",
                file=sys.stderr)
            sys.exit(1)

        # workaround--the pywt has accuracy bugs when we get to high freqs, so slow everything down
        base_freq /= CORRECTION_FACTOR
        quality /= CORRECTION_FACTOR
        scalogram_quality /= CORRECTION_FACTOR

        # construct the wavelet we want
        wavelet = pywt.ContinuousWavelet('cmor')
        wavelet.bandwidth_frequency = Scalogram.BANDWIDTH_FREQ
        wavelet.center_frequency = base_freq * 2  # put the center freq in the middle of the expected range

        base_scale = quality * wavelet.center_frequency / base_freq
        far_scale = base_scale / 2**num_octaves
        scales = np.geomspace(base_scale,
                              far_scale,
                              num=num_octaves * voices_per_octave + 1,
                              endpoint=True)

        #mags = np.empty((len(scales), int(len(data) * scalogram_quality / quality)))
        mags = np.empty(
            (int(len(data) * scalogram_quality / quality), len(scales)))
        freqs = np.empty(len(scales))

        # do actual calculation 1 scale at a time, resampling the magnitudes (saves memory)
        factor = int(quality / scalogram_quality)
        for f in range(len(scales)):
            coeffs, freq = pywt.cwt(data, scales[f], wavelet, 1 / quality)

            freqs[f] = freq[0] * CORRECTION_FACTOR
            for t in range(len(mags)):
                mags[t][f] = (abs(coeffs[0][t * factor:(t + 1) *
                                            factor])).mean()

        return (freqs, mags)
Exemplo n.º 17
0
def test_cmor():
    LB = -20
    UB = 20
    N = 1000
    Fb = 1
    Fc = 1.5

    [psi, x] = ref_cmor(LB, UB, N, Fb, Fc)
    w = pywt.ContinuousWavelet("cmor{}-{}".format(Fb, Fc))
    assert_almost_equal(w.center_frequency, Fc)
    assert_almost_equal(w.bandwidth_frequency, Fb)
    w.upper_bound = UB
    w.lower_bound = LB
    PSI, X = w.wavefun(length=N)

    assert_allclose(np.real(PSI), np.real(psi), atol=1e-15)
    assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15)
    assert_allclose(X, x, atol=1e-15)

    LB = -20
    UB = 20
    N = 1000
    Fb = 1.5
    Fc = 1

    [psi, x] = ref_cmor(LB, UB, N, Fb, Fc)
    w = pywt.ContinuousWavelet("cmor{}-{}".format(Fb, Fc))
    assert_almost_equal(w.center_frequency, Fc)
    assert_almost_equal(w.bandwidth_frequency, Fb)
    w.upper_bound = UB
    w.lower_bound = LB
    PSI, X = w.wavefun(length=N)

    assert_allclose(np.real(PSI), np.real(psi), atol=1e-15)
    assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15)
    assert_allclose(X, x, atol=1e-15)
Exemplo n.º 18
0
	def plot_signal_decomp2(data,w,scale,title):
		w = pywt.ContinuousWavelet(w)#选取小波函数
		a = data
		coefs=[]
		freqs=[]
		coefs, freqs=pywt.cwt(a,scale,w)
		#X,Y=coefs.shape#增加等高线表示
		im=plt.matshow(coefs,interpolation='nearest',cmap='jet')
		plt.colorbar(im)
		#plt.title('RH CWT')
		plt.xlabel('time(day)')
		plt.ylabel('scale')
		plt.title(title,verticalalignment='bottom')
		plt.show()
		return coefs
Exemplo n.º 19
0
def gen_spike_track(dat_3D, frames, fps=50):
    # fps is the desired framerate of the output video
    output = np.array([], dtype='float32')
    w_length = 100
    bitrate = 44100
    length = 1. / fps  # length of a frame in seconds
    num_samps_per_frame = int(bitrate * length)
    spikeshape = pywt.ContinuousWavelet('mexh').wavefun(length=w_length)[0]
    for ii, frame in enumerate(frames):
        frame_sound = np.zeros(num_samps_per_frame, dtype='float32')
        num_spikes = spikes_in_frame(dat_3D, frame)
        if num_spikes > 0:
            frame_sound[:w_length * num_spikes] = np.tile(
                spikeshape, num_spikes).ravel()
        output = np.concatenate([output, frame_sound])
    return output
Exemplo n.º 20
0
def get_wavlist():
    """Returns the list of continuous wavelet functions available in the
    PyWavelets library.
    """
    l = []
    for name in pywt.wavelist(kind='continuous'):
        # supress warnings when the wavelet name is missing parameters
        completion = {
            'cmor': 'cmor1.5-1.0',
            'fbsp': 'fbsp1-1.5-1.0',
            'shan': 'shan1.5-1.0'
        }
        if name in completion:
            name = completion[name]  # supress warning
        l.append(name + " :\t" + pywt.ContinuousWavelet(name).family_name)
    return l
def _save_wavelets() -> None:
    """Saves three different kinds of mother wavelets to be used in the 
    theoretical part of the report.
    """
    n = 100
    wavelet_names = ['gaus1', 'mexh', 'morl']
    titles = ['Gaussian wavelet', 'Mexican hat wavelet', 'Morlet wavelet']
    file_names = ['gaussian.html', 'mexican_hat.html', 'morlet.html']
    for i in range(len(wavelet_names)):
        file_name = file_names[i]
        path = Path(PLOTS_FOLDER, file_name)
        if not path.exists():
            wavelet_name = wavelet_names[i]
            wavelet = pywt.ContinuousWavelet(wavelet_name)
            [wavelet_fun, x] = wavelet.wavefun(length=n)
            utils_graph.graph_2d_line(x, wavelet_fun, 'Time', 'Amplitude',
                                      titles[i], PLOTS_FOLDER, file_name)
Exemplo n.º 22
0
def periods2scales(periods, wavelet=None, dt=1.0):
    """Helper function to convert periods values (in the pseudo period
    wavelet sense) to scales values

    Arguments
    ---------
    - periods : np.ndarray() of positive strictly increasing values
        The ``periods`` array should be consistent with the ``time`` array passed
        to ``cws()``. If no ``time`` values are provided the period on the
        scaleogram will be in sample units.

        Note: you should check that periods minimum value is larger than the
        duration of two data sample because the sectrum has no physical
        meaning bellow these values.

    - wavelet : pywt.ContinuousWavelet instance or string name

    dt=[1.0] : specify the time interval between two samples of data
        When no ``time`` array is passed to ``cws()``, there is no need to
        set this parameter and the default value of 1 is used.

    Note: for a scale value of ``s`` and a wavelet Central frequency ``C``,
    the period ``p`` is::

        p = s / C

    Example : Build a spectrum  with constant period bins in log space
    -------
    import numpy as np
    import scaleogram as scg

    periods = np.logspace(np.log10(2), np.log10(100), 100)
    wavelet = 'cgau5'
    scales  = periods2scales(periods, wavelet)
    data    = np.random.randn(512)  # gaussian noise
    scg.cws( data, scales=scales, wavelet=wavelet, yscale='log',
            title="CWT of gaussian noise with constant binning in Y logscale")
    """
    if wavelet is None:
        wavelet = get_default_wavelet()
    if isinstance(wavelet, six.string_types):
        wavelet = pywt.ContinuousWavelet(wavelet)
    else:
        assert (isinstance(wavelet, pywt.ContinuousWavelet))

    return (periods / dt) * pywt.central_frequency(wavelet)
Exemplo n.º 23
0
def get_wavelet(latency, frequency, times, mwt="mexh"):
    signal_frequency = 1 / (times[1] - times[0])
    mother = pywt.ContinuousWavelet(mwt)
    scale = signal_frequency / frequency
    mex, _ = mother.wavefun(length=int(scale * 4))

    center_index = int((latency - times[0]) * signal_frequency)
    left_index = center_index - len(mex) // 2
    res = np.zeros_like(times)
    if left_index < 0:
        mex = mex[-left_index:]
        start = 0
    else:
        start = left_index

    mex = mex[:len(res) - start]
    res[start:start + len(mex)] = mex
    return res
    def drawWavalet(self, type):

        font_title = {'family': 'SimHei', 'weight': 'bold', 'size': 14}

        font = {'family': 'DejaVu Sans', 'weight': 'bold', 'size': 13}

        if type == 'haar' or type == 'db8':
            wavelet = pywt.Wavelet(type)
            phi, psi, x = wavelet.wavefun(level=3)
            plt.figure(figsize=(8, 7))
            ax1 = plt.subplot(2, 1, 1)
            ax1.plot(x, psi, color='black')
            ax1.grid()
            ax1.set_title(type + "母小波", font_title)
            # ax1.set_ylabel('(a)')
            ax2 = plt.subplot(2, 1, 2)
            ax2.set_title(type + "父小波", font_title)
            ax2.plot(x, phi, color='black')
            ax2.grid()
            # ax2.set_ylabel('(b)')
            plt.savefig(self.path + type + '.png',
                        dpi=400,
                        bbox_inches='tight')
            plt.show()
        elif type == 'mexh' or type == 'gaus1':
            wavelet = pywt.ContinuousWavelet(type)
            psi, x = wavelet.wavefun(level=10)
            plt.figure(figsize=(7, 4))
            plt.plot(x, psi, color='black')
            plt.grid()
            #plt.title("Mexh 小波基函数", font_title)
            plt.xlabel("X", font)
            plt.ylabel("${ψ_{a,b}'(x)}$", font)
            plt.savefig(self.path + type + '.png',
                        dpi=400,
                        bbox_inches='tight')
            plt.show()
Exemplo n.º 25
0
def test_fbsp():
    LB = -20
    UB = 20
    N = 1000
    M = 2
    Fb = 1
    Fc = 1.5

    [psi, x] = ref_fbsp(LB, UB, N, M, Fb, Fc)

    w = pywt.ContinuousWavelet("fbsp{}-{}-{}".format(M, Fb, Fc))
    assert_almost_equal(w.center_frequency, Fc)
    assert_almost_equal(w.bandwidth_frequency, Fb)
    w.fbsp_order = M
    w.upper_bound = UB
    w.lower_bound = LB
    PSI, X = w.wavefun(length=N)

    assert_allclose(np.real(PSI), np.real(psi), atol=1e-15)
    assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15)
    assert_allclose(X, x, atol=1e-15)

    LB = -20
    UB = 20
    N = 1000
    M = 2
    Fb = 1.5
    Fc = 1

    [psi, x] = ref_fbsp(LB, UB, N, M, Fb, Fc)
    w = pywt.ContinuousWavelet("fbsp{}-{}-{}".format(M, Fb, Fc))
    assert_almost_equal(w.center_frequency, Fc)
    assert_almost_equal(w.bandwidth_frequency, Fb)
    w.fbsp_order = M
    w.upper_bound = UB
    w.lower_bound = LB
    PSI, X = w.wavefun(length=N)

    assert_allclose(np.real(PSI), np.real(psi), atol=1e-15)
    assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15)
    assert_allclose(X, x, atol=1e-15)

    LB = -20
    UB = 20
    N = 1000
    M = 3
    Fb = 1.5
    Fc = 1.2

    [psi, x] = ref_fbsp(LB, UB, N, M, Fb, Fc)
    w = pywt.ContinuousWavelet("fbsp{}-{}-{}".format(M, Fb, Fc))
    assert_almost_equal(w.center_frequency, Fc)
    assert_almost_equal(w.bandwidth_frequency, Fb)
    w.fbsp_order = M
    w.upper_bound = UB
    w.lower_bound = LB
    PSI, X = w.wavefun(length=N)
    # TODO: investigate why atol = 1e-5 is necessary
    assert_allclose(np.real(PSI), np.real(psi), atol=1e-5)
    assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-5)
    assert_allclose(X, x, atol=1e-15)
Exemplo n.º 26
0
import numpy as np
import pywt
import matplotlib.pyplot as plt

wav = pywt.ContinuousWavelet('cmor1.5-1.0')

# print the range over which the wavelet will be evaluated
print("Continuous wavelet will be evaluated over the range [{}, {}]".format(
    wav.lower_bound, wav.upper_bound))

width = wav.upper_bound - wav.lower_bound

scales = [1, 2, 3, 4, 10, 15]

max_len = int(np.max(scales) * width + 1)
t = np.arange(max_len)
fig, axes = plt.subplots(len(scales), 2, figsize=(12, 6))
for n, scale in enumerate(scales):

    # The following code is adapted from the internals of cwt
    int_psi, x = pywt.integrate_wavelet(wav, precision=10)
    step = x[1] - x[0]
    j = np.floor(np.arange(scale * width + 1) / (scale * step))
    if np.max(j) >= np.size(int_psi):
        j = np.delete(j, np.where((j >= np.size(int_psi)))[0])
    j = j.astype(np.int_)

    # normalize int_psi for easier plotting
    int_psi /= np.abs(int_psi).max()

    # discrete samples of the integrated wavelet
Exemplo n.º 27
0
# JUST ME PLAYING AROUND

import pywt
import numpy as np
import matplotlib.pyplot as plt
import sys

TAU = 2 * np.pi
SAMPLING_RATE = 300 * 1000
SAMPLING_PERIOD = 1 / SAMPLING_RATE
SIGNAL_FREQ = 80 * 1000
AMPLITUDE = 1
VOICES_PER_OCTAVE = 64
BASE_SCALE = 133.125  # WHY?

wavelet = pywt.ContinuousWavelet('cmor5-60000')

# make data of a 2-kHz signal over 1 second, sampling rate of 100 kHz

np.set_printoptions(threshold=sys.maxsize)

# create 1 s of data at the given frequency sampling rate
x = np.arange(SAMPLING_RATE)
signal = AMPLITUDE * np.sin(TAU * x / (SAMPLING_RATE / SIGNAL_FREQ))
print(signal.shape)
print(signal[0:128])
# plot the signal
#fig,ax = plt.subplots(figsize=(50,10))
#ax.plot(x,signal)

scales = np.geomspace(BASE_SCALE * 2, BASE_SCALE / 2,
Exemplo n.º 28
0
size_set = 'reduced'

# list of mode names in pywt and matlab
modes = [('zero', 'zpd'), ('constant', 'sp0'), ('symmetric', 'sym'),
         ('periodic', 'ppd'), ('smooth', 'sp1'), ('periodization', 'per')]

families = ('gaus', 'mexh', 'morl', 'cgau', 'shan', 'fbsp', 'cmor')
wavelets = sum([pywt.wavelist(name) for name in families], [])

rstate = np.random.RandomState(1234)
mlab.start()
try:
    all_matlab_results = {}
    for wavelet in wavelets:
        w = pywt.ContinuousWavelet(wavelet)
        if np.any((wavelet == np.array(['shan', 'cmor'])), axis=0):
            mlab.set_variable(
                'wavelet', wavelet + str(w.bandwidth_frequency) + '-' +
                str(w.center_frequency))
        elif wavelet == 'fbsp':
            mlab.set_variable(
                'wavelet', wavelet + str(w.fbsp_order) + '-' +
                str(w.bandwidth_frequency) + '-' + str(w.center_frequency))
        else:
            mlab.set_variable('wavelet', wavelet)
        if size_set == 'full':
            data_sizes = list(range(100, 101)) + \
                [100, 200, 500, 1000, 50000]
            Scales = (1, np.arange(1, 3), np.arange(1, 4), np.arange(1, 5))
        else:
Exemplo n.º 29
0
import matplotlib.pyplot as plt
import numpy as np
import pywt

plt.rc('font', family='serif')
plt.rc('xtick', labelsize='10')
plt.rc('ytick', labelsize='10')
plt.rc('axes', titlesize=12)
plt.rc('text', usetex=True)

discrete_wavelets = ['db5', 'sym5', 'coif5', 'bior2.4']
continuous_wavelets = ['mexh', 'morl', 'shan', 'gaus5']

fig, axes = plt.subplots(1, 4, figsize=(6, 1.8))

for continuous_wavelet in enumerate(continuous_wavelets):
    wavelet = pywt.ContinuousWavelet(continuous_wavelet[1])
    w, x = wavelet.wavefun()
    #Some wavelets names have 'wavelets' instead of 'wavelet' and it leaves an 'S'
    title = wavelet.family_name.replace('wavelets', '')
    title = title.replace('wavelet', '')
    axes[continuous_wavelet[0]].plot(x, w, c='k', lw=1)
    axes[continuous_wavelet[0]].set_title(title)

for axis in axes.ravel():
    axis.set_xticks([])
    axis.set_yticks([])
fig.tight_layout()
fig.savefig('D:/Thesis\Document/figures/plots/wavelets.pdf')
Exemplo n.º 30
0
def test_continuous_wavelet_invalid_dtype():
    with pytest.raises(ValueError):
        pywt.ContinuousWavelet('gaus5', np.complex64)
    with pytest.raises(ValueError):
        pywt.ContinuousWavelet('gaus5', np.int_)