예제 #1
0
def test_centrfreq():
    # db1 is Haar function, frequency=1
    w = pywt.Wavelet('db1')
    expected = 1
    result = pywt.central_frequency(w, precision=12)
    assert_almost_equal(result, expected, decimal=3)
    # db2, frequency=2/3
    w = pywt.Wavelet('db2')
    expected = 2/3.
    result = pywt.central_frequency(w, precision=12)
    assert_almost_equal(result, expected)
예제 #2
0
def compute_CWT_feature_L(data,scale=32,wavelet = 'mexh'):
    """
    Compute features based on continuous wavelet transform of EMG signal
    """
    n,t,c = data.shape
    cwt = np.zeros((n,4*c))
    #print(cwt.shape)
    fc = pywt.central_frequency(wavelet)
    cparam = 2 * fc * scale
    scales = cparam / np.arange(int(scale+1), 1, -1)
    #scales = np.arange(1,scale+1)
    for i in range(n):
        for j in range(c):
            cwtmatr,_ = pywt.cwt(data[i,:,j],scales,wavelet)
            mean_abs = np.mean(np.abs(cwtmatr),axis=1)
            mean_coe = np.mean(mean_abs)
            min_coe = np.min(mean_abs)
            mean_scale = mean_abs@scales/mean_abs.sum()
            total = (cumtrapz(mean_abs,scales,initial=0))
            #print(i,j,total[-1])
            w=np.where(total>=(total[-1]/2))[0][0]
            median_scale = scales[w]
            #print(i,j*4,(j+1)*4)
            cwt[i,j*4:(j+1)*4] = [mean_coe,min_coe,mean_scale,median_scale]
    return cwt
예제 #3
0
파일: dsp.py 프로젝트: HypoX64/candock
def signal2spectrum(data,stft_window_size,stft_stride,cwt_wavename,cwt_scale_num,n_downsample=1, log = True, log_alpha = 0.1, mod = 'stft'):
    # window : ('tukey',0.5) hann
    if n_downsample != 1:
        data = downsample(data,alpha=n_downsample)

    if mod == 'stft':
        zxx = scipy.signal.stft(data, window='hann', nperseg=stft_window_size,noverlap=stft_window_size-stft_stride)[2]
        spectrum = np.abs(zxx)

        if log:
            spectrum = np.log1p(spectrum)
            h = spectrum.shape[0]
            x = np.linspace(h*log_alpha, h-1,num=h+1,dtype=np.int64)
            index = (np.log1p(x)-np.log1p(h*log_alpha))/(np.log1p(h)-np.log1p(h*log_alpha))*h

            spectrum_new = np.zeros_like(spectrum)
            for i in range(h):
                spectrum_new[int(index[i]):int(index[i+1])] = spectrum[i]
            spectrum = spectrum_new

    if mod == 'cwt':

        fc = pywt.central_frequency(cwt_wavename)
        cparam = 2 * fc * cwt_scale_num
        scales = cparam / np.arange(cwt_scale_num, 1, -1)  
        cwtmatr, frequencies = pywt.cwt(data, scales, cwt_wavename,method='fft')
        spectrum = np.abs(cwtmatr)
        spectrum = cv2.resize(spectrum,(cwt_scale_num-1,cwt_scale_num-1),interpolation=cv2.INTER_AREA)

    return spectrum
예제 #4
0
    def plot_tf_cwt(self, TRAI, wavelet_name='morl', save_path=None):
        i = self.data_tra[int(TRAI - 1)]
        if self.device == 'vallen':
            sig = np.multiply(array.array('h', bytes(i[-2])), i[-3] * 1000)
            time = np.linspace(0,
                               pow(i[-5], -1) * (i[-4] - 1) * pow(10, 6),
                               i[-4])
        elif self.device == 'stream':
            sig = np.multiply(array.array('h', bytes(i[-1])), i[-2])
            time = np.linspace(0,
                               pow(i[3], -1) * (i[4] - 1) * pow(10, 6), i[4])

        scales = pywt.central_frequency(wavelet_name) * 1e3 / np.arange(
            1, 1e3, 1e0)
        [cwtmatr_new, frequencies_new] = pywt.cwt(sig, scales, wavelet_name,
                                                  1.0 / i[3])
        plt.figure(figsize=(5.12, 5.12))
        plt.contourf(time, frequencies_new / 1000, abs(cwtmatr_new))
        plt.ylim(20, 1000)
        plt.xlabel('Time (μs)')
        plt.ylabel('Frequency (kHz)')
        if save_path:
            plt.gca().xaxis.set_major_locator(plt.NullLocator())
            plt.gca().yaxis.set_major_locator(plt.NullLocator())
            plt.subplots_adjust(top=1,
                                bottom=0,
                                right=1,
                                left=0,
                                hspace=0,
                                wspace=0)
            plt.margins(0, 0)
            plt.savefig(os.path.join(save_path, '%i.jpg' % TRAI), pad_inches=0)
예제 #5
0
def compute_CWT_feature(data,scale=32,wavelet = 'mexh'):
    """
    Compute features based on continuous wavelet transform of EMG signal
    """
    n,t,c = data.shape
    f=4
    cwt = np.zeros((n,f*c))
    #print(cwt.shape)
    fc = pywt.central_frequency(wavelet)
    cparam = 2 * fc * scale
    scales = cparam / np.arange(int(scale+1), 1, -1)
    #scales = np.arange(1,scale+1)
    batch = 5
    N = np.ceil(n/batch).astype(np.int32)
    
    for i in range(N):
        cwtmatr,_ = pywt.cwt(data[i*batch:(i+1)*batch,:,:],scales,wavelet,axis=1)
        cwtmatr = cwtmatr.transpose(1,0,2,3)
        mean_abs = np.mean(np.abs(cwtmatr),axis=2)
        mean_coe = np.mean(mean_abs,axis=1)
        min_coe = np.min(mean_abs,axis=1)
        mean_scale = scales@mean_abs/mean_abs.sum(axis=1)
        total = (cumtrapz(mean_abs,scales,axis=1,initial=0))
        w=np.greater_equal(total,total[:,-1:,:]/2)
        median_scale = np.zeros((cwtmatr.shape[0],c))
        for j in range(cwtmatr.shape[0]):
            for k in range(c):
                median_scale[j,k] = scales[w[j,:,k]][0]

        cwt[i*batch:(i+1)*batch,::f] = mean_coe
        cwt[i*batch:(i+1)*batch,1::f] = min_coe
        cwt[i*batch:(i+1)*batch,2::f] = mean_scale
        cwt[i*batch:(i+1)*batch,3::f] = median_scale
        
    return cwt
예제 #6
0
def get_cwt_scales(wavelet, lower_freq, upper_freq, dt, num):
    """
	Get expected range of frequencies for cwt.
	"""

    central_freq = pywt.central_frequency(wavelet, precision=15)
    scales = np.geomspace(central_freq / (upper_freq * dt),
                          central_freq / (lower_freq * dt),
                          num=num,
                          endpoint=True)

    return scales
예제 #7
0
def ft(t, data, sampling_rate):
    wavename = 'cgau8'
    totalscal = 512
    fc = pywt.central_frequency(wavename)
    cparam = 2 * fc * totalscal
    scales = cparam / np.arange(totalscal, 10, -10)
    [cwtmatr, frequencies] = pywt.cwt(data, scales, wavename,
                                      1.0 / sampling_rate)
    plt.contourf(t, frequencies, abs(cwtmatr))
    plt.ylabel(u"frequency(Hz)")
    plt.xlabel(u"time(s)")
    plt.subplots_adjust(hspace=0.4)
def main():
    sampling_rate = 360

    wavelet = "mexh"  # mexh, morl, gaus8, gaus4
    scales = pywt.central_frequency(wavelet) * sampling_rate / np.arange(
        1, 101, 1)

    (x1_train, x2_train, y_train,
     groups_train), (x1_test, x2_test, y_test,
                     groups_test) = load_data(wavelet=wavelet,
                                              scales=scales,
                                              sampling_rate=sampling_rate)
    print("Data loaded successfully!")

    log_dir = "./logs/{}".format(wavelet)
    shutil.rmtree(log_dir, ignore_errors=True)

    callbacks = [
        Initializer("[conv|fc]*.weight", fn=torch.nn.init.kaiming_normal_),
        Initializer("[conv|fc]*.bias",
                    fn=partial(torch.nn.init.constant_, val=0.0)),
        LRScheduler(policy=StepLR, step_size=5, gamma=0.1),
        EpochScoring(scoring=make_scorer(f1_score, average="macro"),
                     lower_is_better=False,
                     name="valid_f1"),
        TensorBoard(SummaryWriter(log_dir))
    ]
    net = NeuralNetClassifier(  # skorch is extensive package of pytorch for compatible with scikit-learn
        MyModule,
        criterion=torch.nn.CrossEntropyLoss,
        optimizer=torch.optim.Adam,
        lr=0.001,
        max_epochs=30,
        batch_size=1024,
        train_split=predefined_split(
            Dataset({
                "x1": x1_test,
                "x2": x2_test
            }, y_test)),
        verbose=1,
        device="cuda",
        callbacks=callbacks,
        iterator_train__shuffle=True,
        optimizer__weight_decay=0,
    )
    net.fit({"x1": x1_train, "x2": x2_train}, y_train)
    y_true, y_pred = y_test, net.predict({"x1": x1_test, "x2": x2_test})

    print(confusion_matrix(y_true, y_pred))
    print(classification_report(y_true, y_pred, digits=4))

    net.save_params(f_params="./models/model_{}.pkl".format(wavelet))
예제 #9
0
def get_dataset(data_length=1000, sample_rate=2e-6):
    # Load CSV Files
    # TODO: Use numpy instead of pandas
    I_sin_5k = pd.read_csv('data/raw/I(sin_5k_hiB).csv',
                           header=None).iloc[:, 1:data_length + 1]
    V_sin_5k = pd.read_csv('data/raw/V(sin_5k_hiB).csv',
                           header=None).iloc[:, 1:data_length + 1]

    I_tri_5k = pd.read_csv('data/raw/I(tri_5k_hiB).csv',
                           header=None).iloc[:, 1:data_length + 1]
    V_tri_5k = pd.read_csv('data/raw/V(tri_5k_hiB).csv',
                           header=None).iloc[:, 1:data_length + 1]

    I_trap_5k = pd.read_csv('data/raw/I(trap_5k_hiB).csv',
                            header=None).iloc[:, 1:data_length + 1]
    V_trap_5k = pd.read_csv('data/raw/V(trap_5k_hiB).csv',
                            header=None).iloc[:, 1:data_length + 1]

    I = pd.concat([I_sin_5k, I_tri_5k, I_trap_5k], ignore_index=True)
    V = pd.concat([V_sin_5k, V_tri_5k, V_trap_5k], ignore_index=True)

    # Compute scalograms
    wave_name = 'cgau8'
    total_scale = 30
    fc = pywt.central_frequency(wave_name)
    fmax = 10e3
    cparam = (1 / sample_rate) / fmax * fc * total_scale
    scales = cparam / np.arange(total_scale, 1, -1)

    data_size = I.shape[0]
    image_size = 24
    scalogram = np.zeros([data_size, image_size, image_size])
    for index, row in V.iterrows():
        cwtmatr, _ = pywt.cwt(row, scales, wave_name, sample_rate)
        scalogram[index] = resize(abs(cwtmatr), (image_size, image_size))
        if index % 100 == 0:
            print(f"Index {index} finished")

    # Compute labels
    P = V * I
    t = np.arange(0, (data_length - 0.5) * sample_rate, sample_rate)
    Loss_meas = np.trapz(P, t, axis=1) / (sample_rate * data_length)

    # Reshape data
    in_tensors = torch.from_numpy(scalogram).view(-1, 1, 24, 24)
    out_tensors = torch.from_numpy(Loss_meas).view(-1, 1)

    # Save data as CSV
    np.save("dataset.wavelet.in.npy", in_tensors.numpy())
    np.save("dataset.wavelet.out.npy", out_tensors.numpy())

    return torch.utils.data.TensorDataset(in_tensors, out_tensors)
예제 #10
0
파일: pycwt.py 프로젝트: abcdef1991/CCLSN
def cwt4series(data, wavename='cmor3-3', totalscal=46, sampling_rate=100):
    # data为一维时序数据

    # 需要确保data为(len,)格式
    data = data.reshape((-1, ))

    fc = pywt.central_frequency(wavename)
    cparam = 2 * fc * totalscal
    scales = cparam / np.arange(totalscal, 1, -1)

    [cwtmatr, frequencies] = pywt.cwt(data, scales, wavename,
                                      1.0 / sampling_rate)

    return [cwtmatr, frequencies]
예제 #11
0
def generate_CWT_feature(data,scale=32,wavelet = 'mexh'):
    """
    Compute continuous wavelet transform of EMG signal
    """
    n,t,c = data.shape
    fc = pywt.central_frequency(wavelet)
    cparam = 2 * fc * scale
    scales = cparam / np.arange(int(scale+1), 1, -1)
    cwtmatr = np.zeros((n,scale,t,c))
    for i in range(n):
        for j in range(c):
            temp,_ = pywt.cwt(data[i,:,j],scales,wavelet)
            cwtmatr[i,:,:,j] = abs(temp)
    return cwtmatr
예제 #12
0
    def wavelet(self,
                show_results=False,
                save=False,
                w='cgau8',
                sampling_rate=24e3,
                figsize=(36, 25),
                points=None):
        """

        :param figsize:
        :param sampling_rate: 采样频率
        :param show_results:
        :param save:
        :param w: 小波函数种类
        :return:
        """
        wavelet_results = []
        totalscal = len(self.signals[0][0])
        points = points or totalscal
        t = np.arange(0, points) * 24000 / points
        fc = pywt.central_frequency(w)  # 中心频率
        cparam = 2 * fc * totalscal
        scales = cparam / np.arange(totalscal, 1, -1)
        i = 0
        for temp in self.signals:
            shape = (3, len(temp) // 3)
            # fig, axs = plt.subplots(shape[0], shape[1], figsize=figsize)
            wavelet_temp = []
            for j in range(len(temp)):
                [cwtmatr,
                 frequencies] = pywt.cwt(temp[j], scales, w,
                                         1.0 / sampling_rate)  # 连续小波变换
                plt.subplot(shape[0], shape[1], j + 1)
                plt.contourf(t, frequencies, abs(cwtmatr))
                plt.ylabel(u"freq(Hz)")
                plt.xlabel(u"time(s)")
                plt.title('S{} Wavelet Magnitude'.format(j))
                wavelet_temp.append([cwtmatr, frequencies])
            wavelet_results.append(wavelet_temp)

            if save:
                plt.savefig(os.path.join(
                    RESULT_ROOT,
                    str(i) + "_class_wavelet_spectrum.png"),
                            dpi=600,
                            bbox_inches='tight')
            i += 1
            if show_results:
                plt.show()
        return wavelet_results
예제 #13
0
def Continuous_Wavelet_Transform(X,
                                 scales,
                                 sample_rate=500,
                                 wavelet=None,
                                 use_scipy_signal=True,
                                 *a,
                                 **k):
    '''
    Unforturnately it's a very misleading terminology here to name it by
    Continuous Wavelet Transform. Actually, in engineering, both cwt and
    dwt are digital, point-by-point transform algorithums that can easily
    implemented on a computer. If two mathematicians talk about CWT, it
    really mean Continuous-WT. But here, CWT just misleading people.

    A cwt is a discret operation as well as dwt. The difference is how they
    convolve signal with wavelet. CWT will convolve signal with wavelet
    moveing foreward point-by-point while DWT moves window-by-window. When
    decomposition level grows, wavelet need to be expanded in length. CWT
    wavelet length will be 2, 3, 4, 5, ... and DWT will be 2, 4, 8, ...
    '''
    # check params
    if np.isscalar(scales):
        scales = np.arange(1, scales + 1)
    scales = np.array(scales)
    assert 0 not in scales
    if not use_scipy_signal and wavelet not in pywt.wavelist():
        wavelet = 'morl'

    # prepare wavelets
    if use_scipy_signal:
        wavelets = [
            wavelet(min(10 * scale, X.shape[1]), scale) for scale in scales
        ]
    else:
        int_psi, x = pywt.integrate_wavelet(wavelet, precision=10)
        wavelets = []
        for scale in scales:
            j = np.arange(scale * (x[-1] - x[0]) + 1)
            j = np.floor(j / scale / (x[1] - x[0]))
            wavelets.append(int_psi[np.int32(j[j < len(int_psi)])][::-1])

    # convolve
    coef = np.array([[np.convolve(ch, w, mode='same') for w in wavelets]
                     for ch in X])
    if use_scipy_signal:
        freq = None
    else:
        coef = -np.sqrt(scales).reshape(len(scales), 1) * np.diff(coef)
        freq = (pywt.central_frequency(wavelet, 10) / scales * sample_rate)
    return coef, freq
예제 #14
0
    def calculatecorr(self, filepath):

        interval = 5
        dt = 0.0000001 * interval
        fs = 10000000 / interval
        start = 250000
        end = 350000

        with open(filepath, "rb") as fb:
            data = fb.read()

        ch1ch2 = struct.unpack("<" + str(int(len(data) / 2)) + "H", data)
        ch1ch2 = np.array(ch1ch2)
        ch1ch2 = (ch1ch2 - 8192) * 2.5 / 8192

        datay1 = ch1ch2[::2]
        datay2 = ch1ch2[1::2]

        data1 = datay1[start:end:interval]
        data2 = datay2[start:end:interval]

        wavelet = 'morl'
        c = pywt.central_frequency(wavelet)
        fa = np.arange(20000, 400000 + 1, 10000)
        scales = np.array(float(c)) * fs / np.array(fa)

        [cfs1, frequencies1] = pywt.cwt(data1, scales, wavelet, dt)
        [cfs2, frequencies2] = pywt.cwt(data2, scales, wavelet, dt)
        power1 = (abs(cfs1))**2
        power2 = (abs(cfs2))**2

        for i, f in enumerate(fa):
            mean1 = power1[i].mean()
            power1[i] = power1[i] / mean1
            mean2 = power2[i].mean()
            power2[i] = power2[i] / mean2
            temp = signal.correlate(power1[i],
                                    power2[i],
                                    mode='same',
                                    method='fft')
            corr = (np.where(temp == max(temp))[0][0] -
                    len(temp) / 2) * dt * 1000
            self.dict_fitting[self.source_loc].append([f, corr])

        showdict = ""
        for item in sorted(self.dict_fitting[self.source_loc]):
            showdict += "freq:%dHz corr:%.4fms\r\n" % (item[0], item[1])
        self.textEdit_time_difference.setText(showdict)
예제 #15
0
def plot_wav_freq(wav=None,
                  figsize=None,
                  ax=None,
                  yscale='linear',
                  annotate=True,
                  clearx=False):
    """Plot wavelet representation in **frequency domain**
    see ``plot_wav()`` for parameters.
    """

    if wav is None:
        wav = get_default_wavelet()
    wav = _wavelet_instance(wav)
    fun_wav, time = wav.wavefun()

    if ax is None:
        fig, ax = plt.subplots(1, 1, figsize=figsize)

    # frequency domain plot
    df = 1 / (time[-1] - time[0])
    freq = np.arange(len(time)) * df
    fft = np.abs(np.fft.fft(fun_wav) / np.sqrt(len(fun_wav)))
    ax.plot(freq, fft)
    #ax2.set_yscale('log')
    ax.set_xlim(0, df * len(freq) / 2)
    ax.set_title("Frequency support")
    if clearx:
        ax.set_xticks([])
    else:
        ax.set_xlabel("Frequency [Hz]")

    ax.set_yscale(yscale)
    ax.set_ylim(-0.1, 1.1)

    central_frequency = wav.center_frequency
    if not central_frequency:
        central_frequency = pywt.central_frequency(wav)
    bandwidth_frequency = wav.bandwidth_frequency if wav.bandwidth_frequency else 0
    ax.plot(central_frequency * np.ones(2), ax.get_ylim())

    if annotate:
        ax.annotate("central_freq=%0.1fHz\nbandwidth_param=%0.1f" %
                    (central_frequency, bandwidth_frequency),
                    xy=(central_frequency, 0.5),
                    xytext=(central_frequency + 2, 0.6),
                    arrowprops=dict(facecolor='black', shrink=0.01))

    return ax
예제 #16
0
def ft_diff(t, data_real, data_pre, sampling_rate):
    wavename = 'cgau8'
    totalscal = 512
    fc = pywt.central_frequency(wavename)
    cparam = 2 * fc * totalscal
    scales = cparam / np.arange(totalscal, 10, -10)
    [cwtmatr_real, frequencies] = pywt.cwt(data_real, scales, wavename,
                                           1.0 / sampling_rate)
    [cwtmatr_pre, frequencies] = pywt.cwt(data_pre, scales, wavename,
                                          1.0 / sampling_rate)
    cwtmatr_plot = (np.exp(abs(cwtmatr_real)) -
                    np.exp(abs(cwtmatr_pre))) / (np.exp(abs(cwtmatr_pre)))
    plt.contourf(t, frequencies, abs(cwtmatr_plot))
    plt.ylabel(u"frequency(Hz)")
    plt.xlabel(u"time(s)")
    plt.subplots_adjust(hspace=0.4)
    plt.colorbar()
예제 #17
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)
예제 #18
0
 def calc_k0(self):
     fig_size = 20
     interval = 5
     dt = 0.0000001 * interval
     fs = 10000000 / interval
     start = 250000
     end = 350000
     path = "samples"
     filelisttemp = os.listdir(path)
     for filename in filelisttemp:
         filepath = path + "/" + filename
         with open(filepath, "rb") as fb:
             data = fb.read()
         ch1ch2 = struct.unpack("<"+str(int(len(data)/2))+"H", data)
         ch1ch2 = np.array(ch1ch2)
         ch1ch2 = (ch1ch2-8192)*2.5/8192
         datay1 = ch1ch2[::2]
         datay2 = ch1ch2[1::2]
         data1 = datay1[start:end:interval]
         data2 = datay2[start:end:interval]
         wavelet = 'morl'
         c = pywt.central_frequency(wavelet)
         fa = np.arange(400000, 20000 - 1, -20000)
         scales = np.array(float(c)) * fs / np.array(fa)
         [cfs1,frequencies1] = pywt.cwt(data1,scales,wavelet,dt)
         [cfs2,frequencies2] = pywt.cwt(data2,scales,wavelet,dt)
         power1 = (abs(cfs1)) ** 2
         power2 = (abs(cfs2)) ** 2
         length_now = len(power1[0])
         power1 = np.reshape(power1,(len(power1),fig_size,int(length_now/fig_size)))
         power2 = np.reshape(power2,(len(power2),fig_size,int(length_now/fig_size)))
         power1 = np.log10(np.mean(power1,axis=2))
         power2 = np.log10(np.mean(power2,axis=2))
         mx = power1.max()
         mn = power1.min()
         power1 = (power1-mn) / (mx-mn) * 255.0
         power1 = np.floor(power1)
         mx = power2.max()
         mn = power2.min()
         power2 = (power2-mn) / (mx-mn) * 255.0
         power2 = np.floor(power2)
         self.k0.append(power1)
         self.k0_norm.append(sqrt((power1 ** 2).sum()))
         self.k0.append(power2)
         self.k0_norm.append(sqrt((power2 ** 2).sum()))
예제 #19
0
def signal_pywt(signals):
    #幅值数据
    data_amp = signals
    #小波名称
    wavename = 'cgau8'
    #采样频率
    sampling_rate = 100
    #    小波计算scale,决定变换后频率下限
    totalscal = 128
    fc = pywt.central_frequency(wavename)
    cparam = 2 * fc * totalscal
    scales = cparam / np.arange(totalscal, 1, -1)
    #    小波变换,得到小波系数与频率
    [cwtmatr, frequencies] = pywt.cwt(data_amp, scales, wavename,
                                      1.0 / sampling_rate)
    Abs_cwtmatr = abs(cwtmatr)

    return frequencies, Abs_cwtmatr
예제 #20
0
def wvread_video(file_path):
    audio = AudioSegment.from_file(file_path, 'mp4')
    waveData = np.fromstring(
        audio.raw_data,
        dtype=np.int16)  # np.fromstring(strData, dtype=np.int16)  # 将字符串转化为int
    nchannels = audio.channels
    framerate = audio.frame_rate
    nframes = waveData.shape[0] // nchannels
    pltframe = 2048
    time = np.arange(0, pltframe) * (1.0 / framerate)
    waveData = waveData * 1.0 / (max(abs(waveData)))  # wave幅值归一化
    waveData = np.reshape(waveData, [nframes, nchannels])
    np_audio = waveData[:, 0]  # first channel
    np_audio = np_audio[88200:88200 + pltframe]

    # 傅里叶变换
    # transformed = np.fft.fft(np_audio)  # 傅里叶变换
    # shifted = np.fft.fftshift(transformed)  # 移频
    # plt.figure()
    # plt.subplot(2,1,1)
    # plt.plot(time, np_audio)
    # plt.subplot(2,1,2)
    # plt.plot(transformed)  # 绘制变换后的信号
    # plt.show()

    # 每1ms有44.1frame 每960ms有42336frame
    wavename = 'cgau8'
    totalscal = 4096
    fc = pywt.central_frequency(wavename)
    cparam = 2 * fc * totalscal
    scales = cparam / np.arange(totalscal, 1, -1)
    [cwtmatr, frequencies] = pywt.cwt(np_audio, scales, wavename,
                                      1.0 / framerate)
    plt.figure(figsize=(8, 4))
    plt.subplot(211)
    plt.plot(time, np_audio)
    plt.xlabel(u"time(s)")
    plt.title(u"300Hz 200Hz 100Hz Time spectrum")
    plt.subplot(212)
    plt.contourf(time, frequencies, abs(cwtmatr))
    plt.ylabel(u"freq(Hz)")
    plt.xlabel(u"time(s)")
    plt.subplots_adjust(hspace=0.4)
    plt.show()
예제 #21
0
def cal_wave(data, sampling_rate, total_scale=32, wave_name='cgau8'):
    time = np.arange(0, len(data)) / sampling_rate
    fc = pywt.central_frequency(wave_name)
    c_param = 2 * fc * total_scale
    scales = c_param / np.arange(total_scale, 1, -1)
    [cwt_mat, frequencies] = pywt.cwt(data, scales, wave_name,
                                      1.0 / sampling_rate)
    # plt.figure(figsize=(8, 4))
    # plt.subplot(211)
    # plt.plot(time, data)
    # plt.xlabel(u"Time(s)")
    # plt.title(u"300HzAnd200HzAnd100Hz")
    # plt.subplot(212)
    # plt.contourf(time, frequencies, abs(cwt_mat))
    # plt.ylabel(u"Frequency(Hz)")
    # plt.xlabel(u"Time(s)")
    # plt.subplots_adjust(hspace=0.4)
    # plt.show()
    return cwt_mat, frequencies
예제 #22
0
def spec_wavlet(t, x, nfft=1024, wavename='cgau8', vmax=0.1):
    dt = (t[22] - t[2]) / 20
    ts = dt
    fs = 1 / ts
    fc = pywt.central_frequency(wavename)
    cparam = 2 * fc * nfft
    scales = cparam / np.arange(nfft, 1, -1)
    [cwtmatr, f] = pywt.cwt(x, scales, wavename, 1 / fs)
    Zxx = np.abs(cwtmatr)
    tf = t
    f = f / 1000.

    vmin = 0
    if vmax == -1:
        Zxx = np.log10(Zxx) - np.log10(np.max(Zxx))
        vmax = np.max(Zxx)
        vmin = np.min(Zxx)

    return tf, f, Zxx, vmin, vmax
예제 #23
0
def wavelet2image(signal,
                  sampling_rate,
                  freq_dim_scale=256,
                  wavelet_name='morl'):
    """
    :param signal: 1D temporal sequence
    :param sampling_rate: sampling rate for the sequence
    :param freq_dim_scale: frequency resolution
    :param wavelet_name: wavelet name for CWT, here we have 'morl', 'gaus', 'cmor',...
    :return: time-freq image and its reciprocal frequencies
    """

    freq_centre = pywt.central_frequency(wavelet_name)  # 所选小波的中心频率
    cparam = 2 * freq_centre * freq_dim_scale
    scales = cparam / np.arange(1, freq_dim_scale + 1, 1)  # 获取小波基函数的尺度参数 a 的倒数
    [cwt_matrix, frequencies] = pywt.cwt(signal, scales, wavelet_name,
                                         1.0 / sampling_rate)

    return abs(cwt_matrix), frequencies
def MyPywtCWT(data):
    pass
    ''' --原始数据信息初始化--'''

    # Fs = 500000 #采样频率:500 000 Hz ; 采样周期:2 us
    ''' --尺度计算-- '''
    wavename = 'gaus1'
    totalscal = 256  #尺度序列的长度

    #Fc = 2000;             #小波中心频率(Hz)(“主波峰之间的差值”=2000Hz)
    #Fc = pywt.central_frequency(wavename, precision=8)
    Fc = pywt.central_frequency(wavename)

    C = 2 * Fc * totalscal  # C为常数,用于计算尺度序列. C = 2*Fc/totalscal
    scal = C / np.arange(1, totalscal + 1)  #尺度序列,范围(2*Fc,inf)

    #--连续小波变换--
    coef, freqs = pywt.cwt(data, scal, wavename)
    coef = np.abs(coef)
    return coef, freqs
def MyCWT(data):
    pass
    #--原始数据初始化--
    #x = np.arange(len(data))
    y = data

    # Fs = 500000 #采样频率:500 000 Hz
    #             #采样周期:2 us
    #--尺度计算--
    wavename = 'gaus1'
    totalscal = 64  #尺度序列的长度

    #Fc = 2000;          #小波中心频率(Hz)(“主波峰之间的差值”=2000Hz)
    #Fc = pywt.central_frequency(wavename, precision=8)
    Fc = pywt.central_frequency(wavename)

    C = 2 * Fc * totalscal  # C 为常数,C = 2*Fc/totalscal
    scal = C / np.arange(1, totalscal + 1)  #尺度序列,范围(2*Fc,inf)

    #--连续小波变换--
    coef, freqs = pywt.cwt(y, scal, wavename)
    return coef, freqs
예제 #26
0
def frequency2scale(frequency, wavelet, sr):
    """determine appropriate wavelet scale for desired center frequency

    Args:
        frequency: desired center frequency of wavelet in Hz (1/seconds)
        wavelet: (str) name of pywt wavelet, eg 'morl' for Morlet
        sr: sample rate in Hz (1/seconds)

    Returns:
        scale: (float) scale parameter for pywt.ctw() to extract desired frequency

    Note: this function is not exactly an inverse of pywt.scale2frequency(),
    because that function returns frequency in sample-units (cycles/sample)
    rather than frequency in Hz (cycles/second). In other words,
    freuquency_hz = pywt.scale2frequency(w,scale)*sr.
    """
    from pywt import central_frequency

    # get center frequency of this wavelet
    cf = central_frequency(wavelet)

    # calculate scale
    return cf * sr / frequency
예제 #27
0
import matplotlib.pyplot as plt
import pywt
import os
import numpy as np
import scipy.io as scio
from TheRealEDA import FrequencyAnalysis, get_damage

"""
小波变换样例!后续就用这个
"""
sampling_rate = 24e3  # 采样频率
t = np.arange(0, 1e4/sampling_rate, 1.0/sampling_rate)

w = "cgau8"
totalscal = 3500 - 700
fc = pywt.central_frequency(w)  # 中心频率
cparam = 2 * fc * totalscal
scales = cparam/np.arange(totalscal, 1, -1)

damage = get_damage()
fa = FrequencyAnalysis(damage)
signals = fa.signals

figsize = (11, 8)

shape = (3, 2)

s17 = signals[17]
s25 = signals[25]

s17_temp = []
예제 #28
0
def Continuous_Wavelt_Transform(data, wavename, totalscal, sampling_rate):
    fc = pywt.central_frequency(wavename)  # central frequency
    cparam = 2 * fc * totalscal
    scales = cparam / np.arange(1, totalscal + 1)
    [coef, freqs] = pywt.cwt(data, scales, wavename, 1.0 / sampling_rate)
    return coef, freqs
예제 #29
0
        ch2 = (float(ch2) - 8192) / 8192 * 2.5
        ch1 = float(ch1)
        ch2 = float(ch2)
        data1.append(ch1)
        data2.append(ch2)
        t.append(x * 0.0000001)
    x = x + 1

fb.close()

data1 = data1[int(start / interval):int(end / interval)]
data2 = data2[int(start / interval):int(end / interval)]
t = t[int(start / interval):int(end / interval)]

wavelet = 'morl'
c = pywt.central_frequency(wavelet)
fa = np.arange(400000, 20000 - 1, -100)
scales = np.array(float(c)) * fs / np.array(fa)

[cfs1, frequencies1] = pywt.cwt(data1, scales, wavelet, dt)
[cfs2, frequencies2] = pywt.cwt(data2, scales, wavelet, dt)
power1 = (abs(cfs1))
power2 = (abs(cfs2))

plt.subplot(2, 1, 1)
plt.imshow(power1, cmap=cmap)
plt.axis('off')

plt.subplot(2, 1, 2)
plt.imshow(power2, cmap=cmap)
plt.axis('off')
예제 #30
0
import matplotlib.pyplot as plt
import numpy as np
import pywt
import librosa

#filepath='output/07_05/generated_5.wav'
filepath = 'C_major.wav'
y, fs = librosa.load(filepath)

t = np.arange(0, len(y) / float(fs), 1.0 / fs)

wavename = 'cgau8'
totalscal = 256
fc = pywt.central_frequency(wavename)
cparam = 2 * fc * totalscal
scales = cparam / np.arange(totalscal, 1, -1)
[cwtmatr, frequencies] = pywt.cwt(y, scales, wavename, 1.0 / fs)
plt.figure(figsize=(8, 4))
plt.subplot(211)
plt.plot(t, y)
plt.xlabel("time (sec)")
plt.title("Spectrogram")
plt.subplot(212)
plt.contourf(t, frequencies, abs(cwtmatr))
plt.ylabel("frequency (Hz)")
plt.ylim(0, 1000)
plt.xlabel("time (sec)")
plt.subplots_adjust(hspace=0.4)

plt.show()