def test_wignerVille(self):
     """
     Test for wigner_ville_spectrum. Test uses only a fraction of the
     whole spectrum due to space consumtions.
     """
     datafile = os.path.join(os.path.dirname(__file__), 'data', 'wv.npz')
     rec = np.load(datafile)
     wv = abs(wigner_ville_spectrum(signal_bursts(), 10, 3.5, smoothing_filter='gauss',
                                    verbose=False))
     # No NaNs are supposed to be in the output.
     self.assertEqual(np.isnan(wv).any(), False)
     rms1 = rms(rec['wv_250_500_25'], wv[250:500:25])
     rms2 = rms(rec['wv_750_1000_25'], wv[750:1000:25])
     self.assertEqual(True, rms1 < 1e-6)
     self.assertEqual(True, rms2 < 1e-6)
Exemple #2
0
 def test_wignerVille(self):
     """
     Test for wigner_ville_spectrum. Test uses only a fraction of the
     whole spectrum due to space consumtions.
     """
     datafile = os.path.join(os.path.dirname(__file__), 'data', 'wv.npz')
     rec = np.load(datafile)
     wv = abs(
         wigner_ville_spectrum(signal_bursts(),
                               10,
                               3.5,
                               smoothing_filter='gauss',
                               verbose=False))
     # No NaNs are supposed to be in the output.
     self.assertEqual(np.isnan(wv).any(), False)
     rms1 = rms(rec['wv_250_500_25'], wv[250:500:25])
     rms2 = rms(rec['wv_750_1000_25'], wv[750:1000:25])
     self.assertEqual(True, rms1 < 1e-6)
     self.assertEqual(True, rms2 < 1e-6)
def mtspec_wigner_ville(data,fs,filename):
    from mtspec import mtspec, wigner_ville_spectrum
    fig = plt.figure()
    
    t = np.arange(len(data)) / fs
    ax1 = fig.add_axes([0.2,0.75, 0.79, 0.23])
    ax1.plot(t,data, color="0.3")
    #ax1.set_xlim(0, len(data))
    ax2 = fig.add_axes([0.06,0.02,0.13,0.69])
    spec, freq = mtspec(data, 10, 3.5)
    print "freq is ", freq
    ax2.plot(spec, freq, color="0.3")
    ax2.set_xlim(0, spec.max())
    ax2.set_ylim(freq[0], freq[-1])
    ax2.set_xticks([])
    wv = wigner_ville_spectrum(data, 10, 3.5, smoothing_filter='gauss')
    ax3 = fig.add_axes([0.2, 0.02, 0.79, 0.69])
    ax3.set_yticks([])
    ax1.set_xticks([])
    ax3.imshow(np.sqrt(abs(wv)), interpolation='lanczos', aspect='auto')
    plt.savefig(filename+'.pdf')
Exemple #4
0
def wv_spect(values, times, fig=None, figsize=(8,10), trace_ylab=None, 
             ylab='Frequency (kHz)', sampling_rate=5e6, max_freq=None, 
                min_freq=.0, dbscale=False, vmin=.0, vmax=1., taper=False, 
                number_of_plots=2, **kwargs):
    '''
    Function to plot a multi-taper Wigner-Ville spectrogram of time series
    data.
    
    Arguments: 
        --values: A 1-D array containing 
        --times: An array of times against which the values are plotted
        --fig: The figure to plot the wiglle plot on
        --figsize: The figure size of the plot
        --trace_ylab: The y-axis label for the time series data
        --ylab: The y label for the plot
        --sampling_rate: The sampling rate of the time series data
        --max_freq: The maximum frequency to calculate the spectrogram for.
        --min_freq: The minimum frequency to calculate the spectrogram for.
        --dbscale: Either False (linear colour map), 'min' (decibel scale using
                   the minimum value as a reference), or 'median' (decibel scale
                   using the median power as the reference)
        --vmin: The minimum of the colour map dynamic range (fraction between 0 and 1)
        --vmax: The maximum of the colour map dynamic range (fraction between 0 and 1)
        --taper: The length of seconds at the start of the trace to taper with a
                 Hanning window.
        --number_of_plots: The number of plots to be contained on the figure.
                 Usually 2.
        --**kwargs: Keyqord arguments for figure formatting/saving (see format_fig)
                 
    Returns:
        --None (by default)
        --WV spectrum (if wv_only=True)search_win=[10.0,15.5]
    '''
    
    if taper:
        mute_ind = np.where(times <= taper)[0][-1]
        window = np.hanning(mute_ind*2)[:mute_ind]
        values[:mute_ind] = np.multiply(values[:mute_ind],window)
    
    if not max_freq:
        max_freq = sampling_rate / 2.
    
    wv = wigner_ville_spectrum(values, 1/sampling_rate, 5.5, smoothing_filter='gauss')
        
    frequency_divider = sampling_rate / 2. / max_freq
    if frequency_divider > 1.1:
        wv = wv[-int((wv.shape[0]-1.0)//frequency_divider):,:]
    if min_freq:
        wv = wv[:-int(min_freq*(wv.shape[0]-1.0)//max_freq),:] 
    
    if dbscale == 'median':
        wv = 10 * np.log10(np.abs(wv)/np.median(np.abs(wv)))
    elif dbscale == 'min':
        wv = 10 * np.log10(np.abs(wv)/np.amin(np.abs(wv)))
    else:
        wv = np.where(wv > 0., wv, 0.) #OR: np.sqrt(np.abs(wv))
    
    if not fig:
        fig = plt.figure(figsize=figsize) 
        
    if number_of_plots > 2:
        gs = gridspec.GridSpec(number_of_plots, 2, height_ratios=[2,3]+[2]*(number_of_plots-2),
                               width_ratios=[30,1])
    else:
        gs = gridspec.GridSpec(2, 2, height_ratios=[2,3], width_ratios=[30,1])

    ax1 = fig.add_subplot(gs[0])     
    ax2 = fig.add_subplot(gs[2], sharex=ax1)
    if number_of_plots > 2:
        [fig.add_subplot(gs[i], sharex=ax1) for i in range(4, number_of_plots*2-1,2)]
    
    ax1.plot(times, values, 'k')          #Plot the waveform
    ax1.xaxis.set_tick_params(direction='in') 
    
    extent = (times[0], times[-1], min_freq/1e3, max_freq/1e3)
    im = ax2.imshow(wv, interpolation='nearest', aspect='auto', extent=extent,
                    cmap="nipy_spectral", vmin=vmin)#, vmax=vmax) 
    
    cbar_axes = fig.add_subplot(gs[3])
    units_list = ['','(dB)']
    cb = plt.colorbar(im, cax = cbar_axes)
    cbar_axes.set_ylabel('Power {}'.format(units_list[dbscale!=False]),fontsize=16.0)
    cbar_axes.yaxis.set_label_position('right')
    cbar_axes.tick_params(labelsize=12.0)
    cb.formatter.set_powerlimits((-3,3)), cb.update_ticks()
    
    xlab = 'Time ($\mu$s)' if number_of_plots < 3 else ''
    format_kwargs = {key:val for key ,val in kwargs.items() if key not in ['show','save_dir']}
    fig, ax1 = format_fig(fig, ax1, ylab=trace_ylab, show=False, save_dir=False,
                         xlim=(times[0], times[-1]), **format_kwargs)
    
    kwargs.update({'title':None})
    fig, ax2 = format_fig(fig, ax2, xlab=xlab, ylab=ylab,
                         xlim=(times[0], times[-1]), **kwargs)

    return fig, wv
from mtspec import mtspec, wigner_ville_spectrum
from mtspec.util import signal_bursts

fig = plt.figure()
data = signal_bursts()

# Plot the data
ax1 = fig.add_axes([0.2,0.75, 0.79, 0.24])
ax1.plot(data, color="k")
ax1.set_xlim(0, len(data))

# Plot multitaper spectrum
ax2 = fig.add_axes([0.06,0.02,0.13,0.69])
spec, freq = mtspec(data, 10, 3.5)
ax2.plot(spec, freq, color="k")
ax2.set_xlim(0, spec.max())
ax2.set_ylim(freq[0], freq[-1])
ax2.set_xticks([])

# Create the wigner ville spectrum
wv = wigner_ville_spectrum(data, 10, 3.5, smoothing_filter='gauss')

# Plot the WV
ax3 = fig.add_axes([0.2, 0.02, 0.79, 0.69])
ax3.set_yticks([])
ax3.set_xticks([])
ax3.imshow(abs(wv), interpolation='nearest', aspect='auto',
           cmap="magma")

plt.show()
Exemple #6
0
import matplotlib.pylab as plt
from mtspec import wigner_ville_spectrum
from mtspec.util import linear_chirp, exponential_chirp
import numpy as np

fig = plt.figure()
data = linear_chirp() + exponential_chirp()

# Plot the data
ax1 = fig.add_axes([0.05,0.75, 0.90, 0.24])
ax1.plot(data)
ax1.set_xlim(0, len(data))
ax1.set_yticks([])

# Get the smoothed WV spectrum.
wv = wigner_ville_spectrum(data, 10, 5.0, smoothing_filter='gauss',
                           filter_width=25)

# Plot the WV
ax2 = fig.add_axes([0.01, 0.025, 0.48, 0.64])
ax2.set_yticks([])
ax2.set_xticks([])
ax2.imshow(abs(wv), interpolation='nearest', aspect='auto')
ax2.set_title('With smoothing')

# Get the WV spectrum.
wv = wigner_ville_spectrum(data, 10, 5.0, smoothing_filter=None)

# Plot the WV
ax3 = fig.add_axes([0.51, 0.025, 0.48, 0.64])
ax3.set_yticks([])
ax3.set_xticks([])
Exemple #7
0
 def spectrum(self, signal):
     return np.log(abs(wigner_ville_spectrum(signal, delta=self.sampling_freq,
                                             time_bandwidth=self.time_bandwidth,
                                             smoothing_filter=self.smoothing_filter))) + 1
Exemple #8
0
from mtspec.util import linear_chirp, exponential_chirp
import numpy as np

fig = plt.figure()
data = linear_chirp() + exponential_chirp()

# Plot the data
ax1 = fig.add_axes([0.05, 0.75, 0.90, 0.24])
ax1.plot(data)
ax1.set_xlim(0, len(data))
ax1.set_yticks([])

# Get the smoothed WV spectrum.
wv = wigner_ville_spectrum(data,
                           10,
                           5.0,
                           smoothing_filter='gauss',
                           filter_width=25)

# Plot the WV
ax2 = fig.add_axes([0.01, 0.025, 0.48, 0.64])
ax2.set_yticks([])
ax2.set_xticks([])
ax2.imshow(abs(wv), interpolation='nearest', aspect='auto')
ax2.set_title('With smoothing')

# Get the WV spectrum.
wv = wigner_ville_spectrum(data, 10, 5.0, smoothing_filter=None)

# Plot the WV
ax3 = fig.add_axes([0.51, 0.025, 0.48, 0.64])
s9, f, jackknife, _, _ = mtspec(data=st9,
                                delta=0.02,
                                time_bandwidth=3.5,
                                number_of_tapers=5,
                                statistics=True)
s10, f, jackknife, _, _ = mtspec(data=st10,
                                 delta=0.02,
                                 time_bandwidth=3.5,
                                 number_of_tapers=5,
                                 statistics=True)

#Spectrograms
#smoothing_filter='gauss',filter_width=10
wv1 = wigner_ville_spectrum(st1,
                            delta=0.02,
                            time_bandwidth=3.5,
                            smoothing_filter='gauss',
                            filter_width=50)
wv10 = wigner_ville_spectrum(st10,
                             delta=0.02,
                             time_bandwidth=3.5,
                             smoothing_filter='gauss',
                             filter_width=50)
wv1 = abs(wv1)
wv10 = abs(wv10)
twv = arange(0, len(st1) * 0.02 - 0.01, 0.02) - 500 * 0.02
T, F = meshgrid(twv, f[::-1])

# Plot the source time functions
# Using contourf to provide my colorbar info, then clearing the figure
Z = [[0, 0], [0, 0]]
from mtspec import mtspec, wigner_ville_spectrum
from mtspec.util import signal_bursts

fig = plt.figure()
data = signal_bursts()

# Plot the data
ax1 = fig.add_axes([0.2, 0.75, 0.79, 0.24])
ax1.plot(data, color="k")
ax1.set_xlim(0, len(data))

# Plot multitaper spectrum
ax2 = fig.add_axes([0.06, 0.02, 0.13, 0.69])
spec, freq = mtspec(data, 10, 3.5)
ax2.plot(spec, freq, color="k")
ax2.set_xlim(0, spec.max())
ax2.set_ylim(freq[0], freq[-1])
ax2.set_xticks([])

# Create the wigner ville spectrum
wv = wigner_ville_spectrum(data, 10, 3.5, smoothing_filter="gauss")

# Plot the WV
ax3 = fig.add_axes([0.2, 0.02, 0.79, 0.69])
ax3.set_yticks([])
ax3.set_xticks([])
ax3.imshow(abs(wv), interpolation="nearest", aspect="auto", cmap="magma")

plt.show()