Пример #1
0
 def plotCWT(self, order=6):
     from mlpy.wavelet import cwt, autoscales, fourier_from_scales
     import matplotlib.pyplot as plt
     omega0 = order
     #compute scales 
     scales = autoscales(N=self.getNumberOfSamples(), dt=self.getSamplingStep(), dj=0.05, wf='morlet', p=omega0)        
     
     spec = cwt(self.getSeries(), dt=self.getSamplingStep(), scales=scales, wf='morlet', p=omega0)
     
     freq = fourier_from_scales(scales, 'morlet', omega0)
     
     # approximate scales through frequencies
     #freq = (omega0 + np.sqrt(2.0 + omega0**2))/(4*np.pi * scale[1:])
     #get as fourier freqs
     
     
     plt.figure()
     ax1 = plt.subplot(211)
     ax2 = plt.subplot(212, sharex=ax1)
     
     t = np.arange( self.getNumberOfSamples() ) * self.x_step_ + self.x_start_
     
     ax1.plot(self.getPositionVector(), self.y_, 'k')
     extent=[t[0], t[-1], freq[0], freq[-1]]
     img = ax2.imshow(np.abs(spec), extent=extent, aspect='auto') 
     
     #plt.colorbar(img)
     plt.show()
     return extent,spec
def mlpy_cwt(x, fs, filename, wv='morlet' ):
    from matplotlib import pyplot as plt
    import mlpy.wavelet as wave
    omega0 = 0
    #fs=1e6
    fact=2048
    t = np.arange(len(x)) / fs
    #scales = wave.autoscales(N=x.shape[0], dt=1/fs, dj=0.4875, wf=wv, p=omega0)
    #X = wave.cwt(x=x, dt=1/fs, scales=scales, wf=wv, p=omega0)

    scales = wave.autoscales(N=x.shape[0], dt=1.0/fs, dj=.025, wf=wv, p=omega0)
    X = wave.cwt(x=x, dt=1/fs, scales=scales, wf=wv, p=omega0)
    
    fig = plt.figure(1)
    ax1 = plt.subplot(2,1,1)
    p1 = ax1.plot(t,x)
    ax1.autoscale_view(tight=True)
    ax2 = plt.subplot(2,1,2)
    freq = (omega0 + np.sqrt(2.0 + omega0 ** 2)) / (4 * np.pi * scales[1:])
        #print "frequencies are ", freq
    freqs=[math.pow(i,-1) for i in wave.fourier_from_scales(scales, wv, omega0)]
            #print "api freqs are ", freqs
    p2 = ax2.imshow(np.abs(X), interpolation='nearest',aspect='auto', extent=[t[0], t[-1], freq[-1], freq[0]], vmax=abs(X).max(), vmin=-abs(X).max()  )
    twin_ax = ax2.twinx()
    twin_ax.set_xlim(t[0], t[-1])
    twin_ax.set_ylim(freq[-1], freq[0])
    twin_ax.set_yscale('log')
    ax2.tick_params(which='both', labelleft=False, left=False)
    twin_ax.tick_params(which='both', labelleft=True, left=True, labelright=False)
    
    #fig.colorbar(p2)
    fig.savefig(filename+'_'+wv+'.pdf')
    fig.clf()
Пример #3
0
def scaleogram(data, samp_rate = 100.0,wavelet = 'morlet' ,bb=6,what = 'Amp',axis = None):
    """
    Computes and plots logarithmic spectrogram of the input trace.

    :param data: Input data
    :param sample_rate: Samplerate in Hz
    :param log: True logarithmic frequency axis, False linear frequency axis
    :param per_lap: Percent of overlap
    :param nwin: Approximate number of windows.
    :param outfile: String for the filename of output file, if None
        interactive plotting is activated.
    :param format: Format of image to save
    :param axis: Plot into given axis, this deactivates the format and
        outfile option
    """
    # enforce float for samp_rate
    samp_rate = float(samp_rate)

    # nfft needs to be an integer, otherwise a deprecation will be raised


    dscale = 0.1
    dtime = 1./samp_rate
    npts = data.shape[0]
    tt = np.arange(0,npts/samp_rate,1/samp_rate)
    xx = ml.autoscales(N=data.shape[0], dt=dtime, dj=dscale, wf=wavelet, p=bb)
    X = ml.cwt(x=data, dt=dtime, scales=xx, wf=wavelet, p=bb)
    freq = ml.fourier_from_scales(xx, wavelet, bb)
    freq = 1./freq

#    amp = X
    amp = np.abs(X)
    phase = np.angle(X)

    if not axis:
        fig = plt.figure()
        ax = fig.add_subplot(111)

    else:
        ax = axis

    ax.set_yscale('log')
    if what == 'Amp':
        im=ax.pcolormesh(tt,freq,amp)
    else:
        im=ax.pcolormesh(tt,freq,phase)

    # set correct way of axis, whitespace before and after with window
    # length

    ax.axis('tight')
    # ax.set_xlim(0, end)
    ax.grid(False)
    ax.set_xlabel('Time [s]')
    ax.set_ylabel('Frequency [Hz]')

    if axis:
        return ax, im
def all_in_one(x, fs, filename, wv='morlet',  nfft=2048 ):
    from matplotlib import pyplot as plt
    import mlpy.wavelet as wave
    omega0 = 0
    #fs=1e6
    t = np.arange(len(x)) / fs
    #scales = wave.autoscales(N=x.shape[0], dt=1/fs, dj=0.4875, wf=wv, p=omega0)
    #X = wave.cwt(x=x, dt=1/fs, scales=scales, wf=wv, p=omega0)
                                
    scales = wave.autoscales(N=x.shape[0], dt=1.0/fs, dj=.025, wf=wv, p=omega0)
    X = wave.cwt(x=x, dt=1/fs, scales=scales, wf=wv, p=omega0)
    
    fig = plt.figure(1)
    
    ax1 = plt.subplot(3,1,1)
    p1 = ax1.plot(t,x)
    ax1.autoscale_view(tight=True)
    ax2 = plt.subplot(3,1,2)
    freq = (omega0 + np.sqrt(2.0 + omega0 ** 2)) / (4 * np.pi * scales[1:])
    #print "frequencies are ", freq
    freqs=[math.pow(i,-1) for i in wave.fourier_from_scales(scales, wv, omega0)]
    #print "api freqs are ", freqs
    p2 = ax2.imshow(np.abs(X), interpolation='nearest',aspect='auto', extent=[t[0], t[-1], freq[-1], freq[0]], vmax=abs(X).max(), vmin=-abs(X).max()  )
    twin_ax = ax2.twinx()
    twin_ax.set_xlim(t[0], t[-1])
    twin_ax.set_ylim(freq[-1], freq[0])
    twin_ax.set_yscale('log')
    ax2.tick_params(which='both', labelleft=False, left=False)
    twin_ax.tick_params(which='both', labelleft=True, left=True, labelright=False)
    #fig.colorbar(p2, ax=ax2).set_label("Amplitude (dB)") #fig.colorbar(p2)
    
    ax3 = plt.subplot(3,1,3)
    wrapper = lambda fn : np.blackman(fn)
    #wrapper = lambda n : np.hamming(n)
    #wrapper = lambda n : np.hanning(n)
    Pxx, freqs, time, im = ax3.specgram(x, NFFT=nfft,  Fs=fs, detrend=pylab.detrend_none, window=wrapper(nfft), noverlap=nfft/2)
    #Pxx, freqs, time, im = ax3.specgram(x, Fs=fs, NFFT=nfft)
    #fig.colorbar(im, ax=ax3).set_label("Amplitude (dB)")
    ax3.set_xlim(t[0], t[-1])
    fig.savefig(filename+'_all'+'.pdf')
    fig.clf()
def aren_wavelet(x,filename,fs):
    '''
    Does the same continuous wavelet transmform as the mlpy_cwt
    '''
    from wavelets import WaveletAnalysis
    dt=1/fs
    wa = WaveletAnalysis(x, dt=dt)
    # wavelet power spectrum
    power = wa.wavelet_power
    # scales
    scales = wa.scales
    import mlpy.wavelet as wave
    freqs=[math.pow(i,-1) for i in wave.fourier_from_scales(scales, 'morlet',2)]
    # associated time vector
    t = wa.time
    # reconstruction of the original data
    rx = wa.reconstruction()

    fig, ax = plt.subplots()
    T, S = np.meshgrid(t, scales)
    ax.contourf(T, S, power)
    #ax.set_ylim(freqs[-1],freqs[0])
    #ax.set_yscale('log')
    fig.savefig(filename+'.pdf')
Пример #6
0
def scaleogram(data,
               samp_rate=100.0,
               wavelet='morlet',
               bb=6,
               what='Amp',
               axis=None):
    """
    Computes and plots logarithmic spectrogram of the input trace.

    :param data: Input data
    :param sample_rate: Samplerate in Hz
    :param log: True logarithmic frequency axis, False linear frequency axis
    :param per_lap: Percent of overlap
    :param nwin: Approximate number of windows.
    :param outfile: String for the filename of output file, if None
        interactive plotting is activated.
    :param format: Format of image to save
    :param axis: Plot into given axis, this deactivates the format and
        outfile option
    """
    # enforce float for samp_rate
    samp_rate = float(samp_rate)

    # nfft needs to be an integer, otherwise a deprecation will be raised

    dscale = 0.1
    dtime = 1. / samp_rate
    npts = data.shape[0]
    tt = np.arange(0, npts / samp_rate, 1 / samp_rate)
    xx = ml.autoscales(N=data.shape[0], dt=dtime, dj=dscale, wf=wavelet, p=bb)
    X = ml.cwt(x=data, dt=dtime, scales=xx, wf=wavelet, p=bb)
    freq = ml.fourier_from_scales(xx, wavelet, bb)
    freq = 1. / freq

    #    amp = X
    amp = np.abs(X)
    phase = np.angle(X)

    if not axis:
        fig = plt.figure()
        ax = fig.add_subplot(111)

    else:
        ax = axis

    ax.set_yscale('log')
    if what == 'Amp':
        im = ax.pcolormesh(tt, freq, amp)
    else:
        im = ax.pcolormesh(tt, freq, phase)

    # set correct way of axis, whitespace before and after with window
    # length

    ax.axis('tight')
    # ax.set_xlim(0, end)
    ax.grid(False)
    ax.set_xlabel('Time [s]')
    ax.set_ylabel('Frequency [Hz]')

    if axis:
        return ax, im
Пример #7
0
def ratio_scaleogram(data1,data2, samp_rate = 100.0,wavelet = 'morlet' ,bb=6,what = 'Amp',axis = None):
    """
    Computes and plots logarithmic spectrogram of the input trace.

    :param data: Input data
    :param sample_rate: Samplerate in Hz
    :param log: True logarithmic frequency axis, False linear frequency axis
    :param per_lap: Percent of overlap
    :param nwin: Approximate number of windows.
    :param outfile: String for the filename of output file, if None
        interactive plotting is activated.
    :param format: Format of image to save
    :param axis: Plot into given axis, this deactivates the format and
        outfile option
    """
    # enforce float for samp_rate
    samp_rate = float(samp_rate)

    # nfft needs to be an integer, otherwise a deprecation will be raised


    dscale = 0.05
    dtime = 1./samp_rate
    npts = data1.shape[0]
    tt = np.arange(0,npts/samp_rate,1/samp_rate)
    xx = ml.autoscales(N=data1.shape[0], dt=dtime, dj=dscale, wf=wavelet, p=bb)
    X = ml.cwt(x=data1, dt=dtime, scales=xx, wf=wavelet, p=bb)
    Y = ml.cwt(x=data2, dt=dtime, scales=xx, wf=wavelet, p=bb)
    freq = ml.fourier_from_scales(xx, wavelet, bb)
    freq = 1./freq

    XY = np.abs(X*Y.conjugate())
    YY = np.abs(Y*Y.conjugate())
    XX = np.abs(X*X.conjugate())
    ss,st = XY.shape

    s = np.arange(dscale,0.6,dscale)

    i= 0
    Tl = bb
    while i < ss:
        bt = np.kaiser(Tl*(i+1),0)
        XY[i,:] = np.convolve(XY[i,:],bt,'same')
        XX[i,:] = np.convolve(XX[i,:],bt,'same')
        YY[i,:] = np.convolve(YY[i,:],bt,'same')
        i += 1

    Tf = bb
    i = 0
    while i < st:
        s = np.kaiser(Tf,0)
        XY[:,i] = np.convolve(XY[:,i],s,'same')
        XX[:,i] = np.convolve(XX[:,i],s,'same')
        YY[:,i] = np.convolve(YY[:,i],s,'same')
        i += 1

    Coh = (np.abs(XY)**2)/(np.abs(XX) * np.abs(YY))


    if not axis:
        fig = plt.figure()
        ax = fig.add_subplot(111)

    else:
        ax = axis

    ax.set_yscale('log')
    im=ax.pcolormesh(tt,freq,Coh)

    # set correct way of axis, whitespace before and after with window
    # length

    ax.axis('tight')
    # ax.set_xlim(0, end)
    ax.grid(False)
    ax.set_xlabel('Time [s]')
    ax.set_ylabel('Frequency [Hz]')

    if axis:
        return ax, im
fftave = np.convolve(fft_power, np.ones(5) / 5)

# write output of fourier transform
outfile = open("fft.pow", 'w')
for i in range(0, len(fft_power)):
    print >> open('fft.pow', 'a'), fft_freq[i], fft_power[i], fftave[i]

outfile = open("fft.inv", 'w')
for i in range(0, len(fkinv.real)):
    print >> open('fft.inv', 'a'), fkinv.real[i]

# calculate wavelet scales
scales = wave.autoscales(N=x_pad.shape[0], dt=dt, dj=dj, wf=wf, p=p)

# convert scales to fourier periods and output
period = wave.fourier_from_scales(scales, wf=wf, p=p)
outfile = open("scales.periods", 'w')
scale_len = len(scales)
for i in range(0, scale_len):
    print >> open("scales.periods",
                  'a'), i, scales[i], period[i], 1. / period[i]

# perform continuous wavelet transform and output
X = wave.cwt(x=x_pad, dt=dt, scales=scales, wf=wf, p=p)
power = (np.abs(X))**2.
sumpow = power.mean(axis=1)
outfile = open("sumpower.fp", 'w')
for i in range(0, scale_len):
    print >> open('sumpower.fp', 'a'), sumpow[i] / xlen, period[
        i], 1. / period[i], scales[i], sumpow[i] / (scales[i] * xlen)