コード例 #1
0
ファイル: test_cwt_wavelets.py プロジェクト: PyWavelets/pywt
def test_cwt_complex():
    for dtype in [np.float32, np.float64]:
        time, sst = pywt.data.nino()
        sst = np.asarray(sst, dtype=dtype)
        dt = time[1] - time[0]
        wavelet = 'cmor1.5-1.0'
        scales = np.arange(1, 32)

        # real-valued tranfsorm
        [cfs, f] = pywt.cwt(sst, scales, wavelet, dt)

        # complex-valued tranfsorm equals sum of the transforms of the real and
        # imaginary components
        [cfs_complex, f] = pywt.cwt(sst + 1j*sst, scales, wavelet, dt)
        assert_almost_equal(cfs + 1j*cfs, cfs_complex)
コード例 #2
0
ファイル: do_wavelet.py プロジェクト: cppjocker/resonanse_dna
    def test_wavelet(self):
        t = np.arange(1, 1000)
        sig1 = np.sin(2 * math.pi * 1 / 150 * t)
        sig2 = np.sin(2 * math.pi * 1 / 300 * t)

        sig = np.concatenate([sig1, sig2])

        plt.plot(range(0, len(sig)), sig)

        plt.xlabel("Time", fontsize=3)
        plt.ylabel("Amplitude", fontsize=3)

        plt.title("Sin 150 period then 200 period ", fontsize=7)
        plt.savefig("Sin.png", dpi=1200)

        plt.close()

        scales = np.arange(1, 150)

        waveletname = 'morl'
        dt = 1

        [coefficients, frequencies] = pywt.cwt(sig, scales, waveletname, dt)

        idxs_del = np.where(frequencies > 0.5)[0]  # according to Nyquist
        frequencies = np.delete(frequencies, idxs_del)
        coefficients = np.delete(coefficients, idxs_del, 0)

        power = (abs(coefficients))**2
        period = [round(1 / x) for x in frequencies]

        heatmap_pd = pd.DataFrame(
            data=power,  # values
            index=period,
            columns=range(0, len(sig)))

        cs = plt.contourf(range(0, len(sig)), period, power)
        # sns.set(font_scale=0.5)

        # sns.heatmap(heatmap_pd, cbar_kws={'label': 'Energy'}, cmap='plasma')

        plt.xlabel("Time", fontsize=7)
        plt.ylabel("period (bp)", fontsize=7)

        plt.xticks(fontsize=7)
        plt.yticks(fontsize=7)

        plt.title("Sin example", fontsize=7)

        plt.colorbar()

        plt.savefig(self.alg_params.png_file, dpi=1200)

        plt.close()

        quit()
コード例 #3
0
def _check_accuracy(data, w, scales, coefs, wavelet, epsilon):
    # PyWavelets result
    coefs_pywt, freq = pywt.cwt(data, scales, w)

    # calculate error measures
    rms = np.real(np.sqrt(np.mean((coefs_pywt - coefs)**2)))

    msg = ('[RMS > EPSILON] for Scale: %s, Wavelet: %s, '
           'Length: %d, rms=%.3g' % (scales, wavelet, len(data), rms))
    assert_(rms < epsilon, msg=msg)
コード例 #4
0
def test_cwt_small_scales():
    data = np.zeros(32)

    # A scale of 0.1 was chosen specifically to give a filter of length 2 for
    # mexh.  This corner case should not raise an error.
    cfs, f = pywt.cwt(data, scales=0.1, wavelet='mexh')
    assert_allclose(cfs, np.zeros_like(cfs))

    # extremely short scale factors raise a ValueError
    assert_raises(ValueError, pywt.cwt, data, scales=0.01, wavelet='mexh')
コード例 #5
0
 def Wavelet_Specs(self):
     # This is an example. 
     import pywt
     import numpy as np
     import matplotlib.pyplot as plt
     x = np.arange(512)
     y = np.sin(2*np.pi*x/32)
     coef, freqs=pywt.cwt(y,np.arange(1,512),'cgau7')
     plt.matshow(coef) # doctest: +SKIP
     plt.show()
コード例 #6
0
def signal_wnrmse_cwt(s1,
                      s2,
                      waveletname='cmor1.5-1.0',
                      level=None,
                      eps=10e-8):
    scales = np.arange(1, 64)
    dt = 1,
    [s1_coeffs, frequencies] = pywt.cwt(s1, scales, waveletname, dt)
    [s2_coeffs, frequencies] = pywt.cwt(s2, scales, waveletname, dt)

    #sum over time
    s1_coeffs = np.sum((abs(s1_coeffs)), axis=1)
    s2_coeffs = np.sum((abs(s2_coeffs)), axis=1)

    numerator = np.linalg.norm(s1_coeffs - s2_coeffs)
    denominator = np.sqrt(
        np.linalg.norm(s1_coeffs)**2 + np.linalg.norm(s2_coeffs)**2 + eps)
    wnrmse = numerator / denominator
    return wnrmse.sum()
コード例 #7
0
ファイル: test_cwt_wavelets.py プロジェクト: PyWavelets/pywt
def test_cwt_small_scales():
    data = np.zeros(32)

    # A scale of 0.1 was chosen specifically to give a filter of length 2 for
    # mexh.  This corner case should not raise an error.
    cfs, f = pywt.cwt(data, scales=0.1, wavelet='mexh')
    assert_allclose(cfs, np.zeros_like(cfs))

    # extremely short scale factors raise a ValueError
    assert_raises(ValueError, pywt.cwt, data, scales=0.01, wavelet='mexh')
コード例 #8
0
def _check_accuracy(data, w, scales, coefs, wavelet, epsilon):
    # PyWavelets result
    coefs_pywt, freq = pywt.cwt(data, scales, w)

    # calculate error measures
    rms = np.real(np.sqrt(np.mean((coefs_pywt - coefs) ** 2)))

    msg = ('[RMS > EPSILON] for Scale: %s, Wavelet: %s, '
           'Length: %d, rms=%.3g' % (scales, wavelet, len(data), rms))
    assert_(rms < epsilon, msg=msg)
コード例 #9
0
def sig2scalo(wave_path,
              scales=np.arange(1, 128),
              wavelet='morl',
              norm=True,
              save=False):
    audio, sr = librosa.load(wave_path, sr=22500)
    coeff, freq = pywt.cwt(audio, scales, wavelet)
    #scalogram = cv2.resize(coeff, dsize=(224, 224), interpolation = cv2.INTER_CUBIC)
    if save:
        save_image('scalogram', scalo)
    return coeff
コード例 #10
0
ファイル: util.py プロジェクト: shouldsee/music_io
    def old_cwt(self, t1, t2):
#         tmin = int(self.bitrate * t1)
#         tmax = int(self.bitrate * t2)
#         x = self.t0[tmin:tmax]
#         y = self.x0[tmin:tmax]
        x, y = self.trimto(t1,t2)
        scale = np.arange(1,129)
        # scale = np.linspace(1,1000,100)
        coef, freqs=pywt.cwt( y, scale, self.motherwave)
        self.coef = coef
        return coef
コード例 #11
0
def get_cwt(field, sampling_interval=11):
    cumulative_differences, interpolated_data = get_interpolated_data(field)

    coefs, freq = pywt.cwt(
        data=interpolated_data,
        scales=np.arange(1, 128),
        wavelet='morl',
        sampling_period=sampling_interval
    )

    return coefs, freq, cumulative_differences, interpolated_data
コード例 #12
0
def WT_MEXH(y, frequency_bound=32, prominence=1):
    coef, freqs = pywt.cwt(y, np.arange(1, frequency_bound + 1), "mexh")
    z = 0
    h = np.zeros(len(y))
    while z < frequency_bound:
        h += np.power(coef[z], 2)
        z += 1
    total_energy = h / frequency_bound
    peak_wt = find_peaks(total_energy,
                         prominence=prominence)[0]  # use prominence or width
    return peak_wt, total_energy
コード例 #13
0
def data__draw_choose(data):

    def data_batch(data,range):
        basic = np.random.randint(0,120000-range) #这里120000为数据长度
        return np.squeeze(data[basic:basic+range]),basic

    data_,_rand = data_batch(data,4800)   #随机获取长度得数据
    cwtmatr, frequencies = pywt.cwt(data_, np.arange(1,30), 'cgau8',1/SAMPLE_TIME)
    t  = [i for i in range(0,len(data_))]
    plt.contourf(t,frequencies, abs(cwtmatr))
    return _rand
コード例 #14
0
def wavelet_expansion(x, n=25, maxscale=50):

    import pywt

    scales = np.geomspace(1, maxscale, num=n, endpoint=True)

    x = (x - np.nanmean(x, axis=0)) / np.nanstd(x, axis=0)
    x, _ = pywt.cwt(x, scales=scales, wavelet='morl', axis=0)
    x = np.moveaxis(x, [0, 1, 2], [2, 0, 1])
    x = np.reshape(x, (x.shape[0], x.shape[1] * x.shape[2]))

    return x
コード例 #15
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 cwt(data, fs, f_cutoff):
    dt = 1 / fs
    wavelet = 'cmor1.5-1.0'
    scales = np.arange(1, 255)
    [cfs, frequencies] = pywt.cwt(data, scales, wavelet, 1 / fs)
    power = (abs(cfs))**2 * 10
    freqs = pywt.scale2frequency(wavelet, scales) / dt
    mask = frequencies <= f_cutoff
    index = np.where(mask)
    time = np.linspace(0, len(data) / fs, num=len(data), endpoint=False)
    t, f = np.meshgrid(time, frequencies)
    return t[index], f[index], power[index]
コード例 #17
0
def example_1():  #vavelet
    filename = 'data.txt'  #txt文件和当前脚本在同一目录下,所以不用写具体路径
    data = []
    with open(filename, 'r') as file_to_read:
        while True:
            lines = file_to_read.readline()  # 整行读取数据
            if not lines:
                break
                pass
            # 将整行数据分割处理,如果分割符是空格,括号里就不用传入参数,如果是逗号, 则传入‘,'字符。
            p_tmp = lines.split()
            data.append(p_tmp[0])  # 添加新读取的数据
            pass

    x = np.arange(len(data))
    y = data
    # 连续小波变换
    coef, freqs = pywt.cwt(y, np.arange(1, 128), 'gaus1')
    # 时频(尺度)图
    #plt.matshow( coef )
    # 频率
    #plt.plot(freqs)

    # learns to repeat simple sequence from random inputs
    # 从随机输入重复简单的序列学习
    np.random.seed(0)

    # parameters for input data dimension and lstm cell count
    # 输入数据维度和lstm单元数量的参数
    mem_cell_ct = 100  # mem_cell_ct是lstm的神经元数目
    x_dim = 50  # x_dim是输入数据的维度
    lstm_param = LstmParam(mem_cell_ct, x_dim)
    lstm_net = LstmNetwork(lstm_param)
    #y_list = [-0.5, 0.2, 0.1, -0.5]     #此 代码 其是通过自己实现 lstm 网络来逼近一个序列,y_list = [-0.5, 0.2, 0.1, -0.5]                        #
    y_list = [-0.5, 0, -0.5]
    input_val_arr = [np.random.random(x_dim) for _ in y_list]  # 输入

    #print(input_val_arr)
    for cur_iter in range(1000):
        print("iter", "%2s" % str(cur_iter), end=": ")
        for ind in range(len(y_list)):
            lstm_net.x_list_add(input_val_arr[ind])

        print("y_pred = [" + ", ".join([
            "% 2.5f" % lstm_net.lstm_node_list[ind].state.h[0]
            for ind in range(len(y_list))
        ]) + "]",
              end=", ")

        loss = lstm_net.y_list_is(y_list, ToyLossLayer)
        print("loss:", "%.3e" % loss)
        lstm_param.apply_diff(lr=0.1)
        lstm_net.x_list_clear()
コード例 #18
0
def wavelet_transform(signal, p):

    #Assumes that the down-sampled signal at 1kHz is analyzed
    sampling_period = 1 / 1000

    #Use built in pywt function to determine physical frequencies
    scales = pywt.scale2frequency('morl', np.arange(1, 120)) / sampling_period

    #Complete wavelet anlaysis
    coef, freq = pywt.cwt(signal, scales, 'morl', sampling_period)

    return coef, freq
コード例 #19
0
def test_cwt_complex(dtype, tol, method):
    time, sst = pywt.data.nino()
    sst = np.asarray(sst, dtype=dtype)
    dt = time[1] - time[0]
    wavelet = 'cmor1.5-1.0'
    scales = np.arange(1, 32)

    # real-valued tranfsorm as a reference
    [cfs, f] = pywt.cwt(sst, scales, wavelet, dt, method=method)

    # verify same precision
    assert_equal(cfs.real.dtype, sst.dtype)

    # complex-valued transform equals sum of the transforms of the real
    # and imaginary components
    sst_complex = sst + 1j*sst
    [cfs_complex, f] = pywt.cwt(sst_complex, scales, wavelet, dt,
                                method=method)
    assert_allclose(cfs + 1j*cfs, cfs_complex, atol=tol, rtol=tol)
    # verify dtype is preserved
    assert_equal(cfs_complex.dtype, sst_complex.dtype)
コード例 #20
0
def getcwt(fullfilepath):

    data = pd.read_csv(fullfilepath)

    widths = np.arange(1, 101)
    sig = data.values[:, 0]

    cwtmatr, freqs = pywt.cwt(sig, widths, 'mexh', 1 / 20000)

    cwtmags = abs(cwtmatr)

    return cwtmags
コード例 #21
0
def get_cwt(window,
            mask=(0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0),
            wdname='db6',
            wcname='morl',
            scale=40):
    window = wavedec_filtration(window, mask, wdname)
    decomposition, _ = pywt.cwt(window, np.arange(1, scale), wcname)

    tmp = np.abs(decomposition)
    phi = np.cos(np.angle(decomposition))

    return tmp * phi
コード例 #22
0
def get_multi_features(args, train_data, valid_data):
    print(f"Train data shape: {train_data[0].shape}")
    print(f"Valid data shape: {valid_data[0].shape}")
    train_data_cwt = list(train_data)
    valid_data_cwt = list(valid_data)
    # widths = (
    #     np.arange(1, args.signal_window_size + 1)
    #     if args.signal_window_size <= 64
    #     else np.arange(2, args.signal_window_size + 1, 2)
    # )
    max_scale = 1024
    num = int(np.log2(max_scale)) + 1
    widths = np.round(np.geomspace(1, max_scale, num=num,
                                   endpoint=True)).astype(int)
    train_data_cwt[0], _ = pywt.cwt(train_data_cwt[0],
                                    scales=widths,
                                    wavelet="morl",
                                    axis=0)
    train_data_cwt[0] = np.transpose(train_data_cwt[0], (1, 0, 2, 3))
    valid_data_cwt[0], _ = pywt.cwt(valid_data_cwt[0],
                                    scales=widths,
                                    wavelet="morl",
                                    axis=0)
    valid_data_cwt[0] = np.transpose(valid_data_cwt[0], (1, 0, 2, 3))
    train_data_cwt = tuple(train_data_cwt)
    valid_data_cwt = tuple(valid_data_cwt)
    print(f"CWT Train data shape: {train_data_cwt[0].shape}")
    print(f"CWT Valid data shape: {valid_data_cwt[0].shape}")

    print(f"CWT Train data label shape: {train_data_cwt[1].shape}")
    print(f"CWT Valid data label shape: {valid_data_cwt[1].shape}")

    assert (
        train_data[0].shape[0] == train_data_cwt[0].shape[0]
    ), "CWT train data leading dimension does not match with the raw data!"
    assert (
        valid_data[0].shape[0] == valid_data_cwt[0].shape[0]
    ), "CWT valid data leading dimension does not match with the raw data!"

    return train_data_cwt, valid_data_cwt
コード例 #23
0
def get_scalograms(signals, path, data, frequency, time, wavelet_func = "cmor3-60"):

    if (empty_folder(path) == False):
        if(delete_contents_in_folder(path) == False):
            return
    
    T = time #sec
    Fs=frequency #Hz
    dt=1/Fs #sec
    time = np.arange(0, T, dt)
    wavelet =  wavelet_func # "morl"# "cmor" "gaus1"
    scales = np.arange(1,512,2)

    i = 0
    for val in signals:

        i += 1
        ppg = val['ppg']
        patientid = val['patientid']
        sbp = val['sbp']
        dbp=val['dbp']
        
        signal_detrend = signal.detrend(ppg, type='constant')
        #ax = plt.axes()
        fig = plt.figure()
        ax = fig.add_subplot()
        dt = time[1] - time[0]
        [coefficients, frequencies] = pywt.cwt(signal_detrend, scales, wavelet, dt)
        power = (abs(coefficients)) ** 2
        lev_exp = np.arange(-5, np.ceil(np.log10(power.max())+1))
        levs = np.power(10, lev_exp)
        ##for cardioveg
        try: 
            if data == 'cardioveg':
                ##for cardioveg
                im = ax.contourf(time, np.log2(frequencies[:]), power[:,1:], levs, norm=mpl.colors.LogNorm(), extend='both',cmap="RdBu_r")
            else:
                im = ax.contourf(time, np.log2(frequencies[1:]), power[:][1:], levs, norm=mpl.colors.LogNorm(), extend='both',cmap="RdBu_r")
        except TypeError:
            print("length of the ppg signals are not similar for index {}".format(i-1))
            pass

        yticks = 2**np.arange(-2, np.floor(np.log2(frequencies.max()))) ##-2 forcardioveg
        ax.set_yticks(np.log2(yticks))
        ax.set_yticklabels(yticks)
        ax.invert_yaxis()
        ax.get_xaxis().set_visible(False)
        ax.get_yaxis().set_visible(False)
        ylim = ax.get_ylim()
        ax.set_ylim(ylim[0], 1) ##can set the last parameter to -2 for cardioveg
        fig.savefig(os.path.join(path, '{}_{}_{}_{}_scalogram.jpg'.format(i, patientid, sbp, dbp)), dpi=fig.dpi, bbox_inches='tight', pad_inches=0)
        plt.close(fig)
コード例 #24
0
def _peaks_delineator(ecg, rpeaks, cleaning=False, sampling_rate=1000):
    # Try loading pywt
    try:
        import pywt
    except ImportError:
        raise ImportError(
            "NeuroKit error: ecg_delineator(): the 'PyWavelets' module is required for this method to run. ",
            "Please install it first (`pip install PyWavelets`).",
        )
    # first derivative of the Gaissian signal
    scales = np.array([1, 2, 4, 8, 16])
    cwtmatr, freqs = pywt.cwt(ecg,
                              scales,
                              "gaus1",
                              sampling_period=1.0 / sampling_rate)

    qrs_duration = 0.1

    search_boundary = int(0.9 * qrs_duration * sampling_rate / 2)
    significant_peaks_groups = []
    tppeaks_pairs = []
    tppeaks = []
    for i in range(len(rpeaks) - 1):
        # search for T peaks and P peaks from R peaks
        start = rpeaks[i] + search_boundary
        end = rpeaks[i + 1] - search_boundary
        search_window = cwtmatr[4, start:end]
        height = 0.25 * np.sqrt(np.mean(np.square(search_window)))
        peaks_tp, heights_tp = scipy.signal.find_peaks(np.abs(search_window),
                                                       height=height)
        peaks_tp = peaks_tp + rpeaks[i] + search_boundary
        # set threshold for heights of peaks to find significant peaks in wavelet
        threshold = 0.125 * max(search_window)
        significant_index = []
        significant_index = [
            j for j in range(len(peaks_tp))
            if heights_tp["peak_heights"][j] > threshold
        ]

        significant_peaks_tp = []
        for index in significant_index:
            significant_peaks_tp.append(peaks_tp[index])
        significant_peaks_groups.append(
            _find_tppeaks(ecg,
                          significant_peaks_tp,
                          sampling_rate=sampling_rate))

    tpeaks, ppeaks = zip(*[(g[0], g[-1]) for g in significant_peaks_groups])

    tpeaks = np.array(tpeaks, dtype="int")
    ppeaks = np.array(ppeaks, dtype="int")
    return tpeaks, ppeaks
コード例 #25
0
    def get_cwt(self,
                side,
                sensor,
                index,
                scales=shared.SCALES,
                wavelet=shared.WAVELET,
                samp_period=1 / shared.SAMPLING_FREQUENCY,
                mode="coeff"):
        """
        Returns Continuous Wavelet Transform. Wrapper for pywt function

        Parameters
        ----------

        side: str = {"N","S"}
            Side of the train
        sensor: int = {0,1,2,3}
            Index for the sensor
        index: int
            Index for number of cluster
        scales:
            Number of scales for the pywt.cwt
        wavelet:
            Wavelet selected for the pywt.cwt
        samp_period:
            Sampling Period for the pywt.cwt
        mode: str = {"coeff", "wsd", "sawp"}
            Output format.

        Returns
        -------

        wavelet_coeff: np.array
            2-dim array containing the complex values of the wavelet function calculated for the signal.
        wave_freq: np.array
            1-dim array containing the frequency corresponding to scales.

        """
        wavelet_coeff, wave_freq = pywt.cwt(data=np.nan_to_num(
            self(side=side, sensor=sensor, cluster=index)),
                                            scales=scales,
                                            wavelet=wavelet,
                                            sampling_period=samp_period)
        if mode == "coeff":
            return wavelet_coeff
        if mode == "wsd":
            return np.abs(wavelet_coeff**2)
        if mode == "sawp":
            weights = np.array(shared.SCALES).reshape((len(shared.SCALES), 1))
            return np.sum(shared.SCALE_JUMP * np.abs(wavelet_coeff**2) /
                          (shared.SAMPLING_FREQUENCY * weights),
                          axis=0)
コード例 #26
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)
コード例 #27
0
def wavelet(t, x, periods):
    """Wavelet Power Spectrum using Morlet wavelets.

    Parameters
    ----------
    t: array-like
        Time array.
    x: array-like
        Signal array.
    periods: array-like
        Periods to consider, in the same units as `t`.

    Returns
    -------
    power: ndarray[len(periods), len(t)]
        Wavelet Power Spectrum.
    coi: tuple of ndarray
        Time and scale samples for plotting the Cone of Influence boundaries.
    mask_coi: ndarray[len(periods), len(t)]
        Boolean mask with the same shape as `power`; it is True inside the COI.
    """
    family = 'cmor2.0-1.0'
    dt = float(np.median(np.diff(t)))
    scales = pywt.scale2frequency(family, 1) * np.asarray(periods) / dt
    conv_complex = len(scales) * len(x)
    fft_complex = (len(scales) + len(x) -
                   1) * np.log2(len(scales) + len(x) - 1)
    if fft_complex < conv_complex:
        method = 'fft'
    else:
        method = 'conv'
    coefs, freqs = pywt.cwt(x - x.mean(), scales, family, dt, method=method)
    power = np.square(np.abs(coefs))
    wps = (power.T / scales).T
    # Cone of Influence (COI)
    t_max = np.max(t)
    t_min = np.min(t)
    p_max = np.max(periods)
    p_min = np.min(periods)
    t_mesh, p_mesh = np.meshgrid(t, periods)
    mask_coi = (2**.5 * p_mesh < np.minimum(t_mesh - t_min, t_max - t_mesh))
    p_samples = np.logspace(np.log10(p_min), np.log10(p_max), 100)
    p_samples = p_samples[2**.5 * p_samples < (t_max - t_min) / 2]
    t1 = t_min + 2**.5 * p_samples
    t2 = t_max - 2**.5 * p_samples
    t_samples = np.hstack((t1, t2))
    p_samples = np.hstack((p_samples, p_samples))
    sorted_ids = t_samples.argsort()
    sorted_t_samples = t_samples[sorted_ids]
    sorted_p_samples = p_samples[sorted_ids]
    coi = (sorted_t_samples, sorted_p_samples)
    return wps, coi, mask_coi
コード例 #28
0
def generate_wavelet(signal, fs, scale_length=25):
    '''Generate CWT signals of 22Hz - 75Hz.
    Args:
        signal: np.array of shape [n_samples]
        fs: sampling rate
    Outputs:
        CWT_coef: np.array of shape [25, n_samples]
    '''

    scale = np.arange(scale_length) * (fs / 1000) + (fs / 1000) * 8
    coef, freqs = pywt.cwt(signal, scale, 'cgau5', sampling_period=1 / fs)

    return np.abs(coef)
コード例 #29
0
ファイル: processCourbes.py プロジェクト: renared/papertube
def find_peaks(v,thres=0.05,graphCWT=False,graphPeaks=False):
    cwtmatr, freqs = pywt.cwt(v,np.arange(1,10),'mexh')
    peaks = signal.find_peaks(cwtmatr[3],height=0)[0]
    peaks = [p for p in peaks if cwtmatr[-1][int(p)]>0 and cwtmatr[3][int(p)]>abs(cwtmatr).max()*thres]

    if graphCWT:
        plt.figure(figsize=(18,4))
        plt.imshow(cwtmatr, extent=[0, 1, 1, 10], cmap='PRGn', aspect='auto',vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max())
        if graphPeaks:
            for p in peaks:
                plt.axvline(x=p/len(cwtmatr[3]),alpha=0.2)
        plt.title("thres="+str(thres))
    return peaks
コード例 #30
0
def plot_spectrogram(ax, time, signal, waveletname = 'morl', cmap = plt.cm.seismic):
    dt = time[1] - time[0]
    scales = np.arange(1, 128)
    [coefficients, frequencies] = pywt.cwt(signal, scales, waveletname, dt)
    power = (abs(coefficients)) ** 2
    period = 1. / frequencies
    levels = [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8]
    contourlevels = np.log2(levels)    
    ax.contourf(time, np.log2(period), np.log2(power), contourlevels, extend='both',cmap=cmap)
    ax.invert_yaxis()
    ylim = ax.get_ylim()
    ax.set_ylim(ylim[0], -1)
    plt.axis('off')
コード例 #31
0
    def transform(self):
        """
		Wavelet transform each variable separately.
		"""

        scales = get_cwt_scales(self.wavelet, self.min_freq, self.max_freq,
                                self.dt, self.num_freqs)
        for iV in range(self.num_vars):
            coefs, freqs = pywt.cwt(self.Xx[:, iV], scales, self.wavelet,
                                    self.dt)
            self.cwt_matrix[:, :, iV] = abs(coefs)**2.0

        save_cwt_matrix(self.cwt_matrix, self.exp_dir, self.exp_name)
コード例 #32
0
def swt_show(record_ID='1269'):

    y = loadChanggeng(record_ID)
    raw_sig = y[:]
    original_ecg = raw_sig[:]
    annots = loadChanggengAnnots(record_ID)
    y = removeQRS(y, annots)

    coef, freqs = pywt.cwt(y, np.arange(1, 32), 'mexh')

    coef_shape = coef.shape
    # Get P magnify ranges
    P_point_list = list()
    thres = 0.2
    for ind in xrange(0, len(y)):
        if coef[-1, ind] > thres:
            P_point_list.append(ind)

    x_range = (1000, 1640)
    # y = y[x_range[0]:x_range[1]]
    # coef = coef[x_range[0]:x_range[1]]

    # fig, ax = plt.subplots(2,1)

    # amplist = [y[x] for x in P_point_list]
    # ax[0].plot(y)
    # ax[0].plot(P_point_list, amplist, 'ro')

    # amplify(coef, y, ax, level = 20, color = (0.1, 0.2,0.3))
    # amplify(coef, y, ax, level = 10, color = (0.9, 0.3,0.8))
    # # amplify
    # for pos in P_point_list:
    # y[pos] *= 10.0
    # raw_sig[pos] *= 5.0
    # ax[0].plot(y, 'y', lw = 4, alpha = 0.3)

    # ax[0].set_xlim(x_range)
    # ax[1].matshow(coef, cmap = plt.gray())
    # # ax[1].set_clip_box(((0,0),(9,19)))
    # ax[1].set_xlim(x_range)
    # plt.legend(numpoints = 1)

    plt.figure(2)
    # plt.plot(raw_sig, 'k', lw = 2, alpha = 1)
    poslist, wave_ranges = getWaveRange(coef, y)
    amplist = [original_ecg[x] for x in poslist]
    plt.plot(original_ecg, 'b', lw=2, alpha=1)
    plt.plot(poslist, amplist, 'ro', markersize=12, alpha=0.5)

    plt.title(record_ID)
    plt.show()
コード例 #33
0
def wavelet_transform(train_signals_ucihar, test_signals_ucihar,
                      train_labels_ucihar, test_labels_ucihar):
    scales = range(1, 64)
    waveletname = 'morl'

    train_size = len(train_signals_ucihar)
    test_size = len(test_signals_ucihar)

    train_data_cwt = np.ndarray(shape=(train_size, 63, 63, 6))

    for ii in range(0, train_size):
        if ii % 100 == 0:
            print(ii)
        for jj in range(0, 6):
            signal = train_signals_ucihar[ii, :, jj]
            coeff, freq = pywt.cwt(signal, scales, waveletname, 1)
            coeff_ = coeff[:, :63]
            train_data_cwt[ii, :, :, jj] = coeff_

    test_data_cwt = np.ndarray(shape=(test_size, 63, 63, 6))
    for ii in range(0, test_size):
        if ii % 100 == 0:
            print(ii)
        for jj in range(0, 6):
            signal = test_signals_ucihar[ii, :, jj]
            coeff, freq = pywt.cwt(signal, scales, waveletname, 1)
            coeff_ = coeff[:, :63]
            test_data_cwt[ii, :, :, jj] = coeff_

    # train_labels_ucihar = list(map(lambda x: int(x) - 1, train_labels_ucihar))
    # test_labels_ucihar = list(map(lambda x: int(x) - 1, test_labels_ucihar))

    x_train = train_data_cwt
    y_train = list(train_labels_ucihar[:train_size])
    x_test = test_data_cwt
    y_test = list(test_labels_ucihar[:test_size])

    return x_train, y_train, x_test, y_test
コード例 #34
0
ファイル: TLCINTF.py プロジェクト: arrovvx/TLC
def handleMsg(self, message, callback):
	global shiftEnd,bufferData,bufferTarget, fillNum, curser, buffer, transformWindow, targetWindow, runNum
	
	parsed_json = json.loads(message)
	bufferData[curser] = parsed_json['input']
	bufferTarget[curser] = parsed_json['output']
	
	curser += 1
	if(curser == shiftSpeed):
		curser = 0
		transformWindow[shiftSpeed:] = transformWindow[:shiftEnd]
		transformWindow[:shiftSpeed] = bufferData[:shiftSpeed]
		
		targetWindow[shiftSpeed:] = targetWindow[:shiftEnd]
		targetWindow[:shiftSpeed] = bufferTarget[:shiftSpeed]
		
		if (runNum > fillNum):
			Data = np.array(transformWindow)
			Target = np.array(targetWindow)
			
			aa, ff = pywt.cwt(Data[:,0], np.arange(1, 129), 'morl')
			DataArr = np.array([aa[:,300:700]])
			
			for i in range(Data.shape[1] - 1):
				aa, ff = pywt.cwt(Data[:,i + 1], np.arange(1, 129), 'morl')
				DataArr = np.vstack([DataArr,[aa[:,300:700]]])
			
			output = callback(DataArr, Target[300:700])
			if output >= 0:
				self.write_message('{"name" : "TLCOutput", "output": "%s"}' % str(output))
			
			#plt.matshow(aa) 
			#plt.show()
			#thr = threading.Thread(target=runNN, args=(self))#, kwargs={}
			#thr.start() # will run "foo"
		else:
			runNum += 1
コード例 #35
0
ファイル: benchmark.py プロジェクト: nickgeoca/cwt-tensorflow
signal = np.sin(np.arange(sampleSize) / 20.)

start = time.time()
a = pywt.dwt(signal, 'haar')
end = time.time()
print('pywt dwt haar: ' + str(end - start))

start = time.time()
a = pywt.dwt(signal, 'db2')
end = time.time()
print('pywt dwt db2: ' + str(end - start))

start = time.time()
a = pywt.dwt(signal, 'db8')
end = time.time()
print('pywt dwt db8: ' + str(end - start))

start = time.time()
coef, freqs=pywt.cwt(signal,np.arange(1,1+cwtWidth),'morl')
end = time.time()
print('pywt cwt mortlet: ' + str(end - start))

cwtOp = cwtMortlet(tf.float32, signal, cwtWidth)
sess = tf.Session()
start = time.time()
cwt = sess.run(cwtOp)
end = time.time()
sess.close()
print('tf cwt mortlet: ' + str(end - start))

コード例 #36
0
ファイル: cwt_benchmarks.py プロジェクト: HenryZhou1002/pywt
 def time_cwt(self, n, wavelet, max_scale):
     pywt.cwt(self.data, self.scales, wavelet)
コード例 #37
0
ファイル: cwt_1.py プロジェクト: BossKwei/temp
import pywt
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(512)
y = np.sin(2 * np.pi * x / 32)
scales = np.linspace(1, 64, 64)
plt.plot(x, y)
coef, freqs = pywt.cwt(y, scales, 'gaus1')
plt.matshow(coef)

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

t = np.linspace(-1, 1, 200, endpoint=False)
sig = np.cos(2 * np.pi * 7 * t) + np.real(np.exp(-7 * (t - 0.4) ** 2) * np.exp(1j * 2 * np.pi * 2 * (t - 0.4)))
plt.plot(t, sig)
plt.show()
widths = np.arange(1, 31)
cwtmatr, freqs = pywt.cwt(sig, widths, 'mexh')
plt.imshow(cwtmatr, extent=[-1, 1, 1, 31], cmap='PRGn', aspect='auto',
           vmax=abs(cwtmatr).max(), vmin=-abs(cwtmatr).max())
plt.show()
コード例 #38
0
ファイル: cwt_analysis.py プロジェクト: PyWavelets/pywt
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt

import pywt

time, sst = pywt.data.nino()
dt = time[1] - time[0]

# Taken from http://nicolasfauchereau.github.io/climatecode/posts/wavelet-analysis-in-python/
wavelet = 'cmor1.5-1.0'
scales = np.arange(1, 128)

[cfs, frequencies] = pywt.cwt(sst, scales, wavelet, dt)
power = (abs(cfs)) ** 2

period = 1. / frequencies
levels = [0.0625, 0.125, 0.25, 0.5, 1, 2, 4, 8]
f, ax = plt.subplots(figsize=(15, 10))
ax.contourf(time, np.log2(period), np.log2(power), np.log2(levels),
            extend='both')

ax.set_title('%s Wavelet Power Spectrum (%s)' % ('Nino1+2', wavelet))
ax.set_ylabel('Period (years)')
Yticks = 2 ** np.arange(np.ceil(np.log2(period.min())),
                        np.ceil(np.log2(period.max())))
ax.set_yticks(np.log2(Yticks))
ax.set_yticklabels(Yticks)
ax.invert_yaxis()