예제 #1
0
def __axis_log(data,
               n_ticks,
               horiz,
               sr=22050,
               kwargs=None,
               label='Hz',
               secondary_axis='linear',
               minor=None,
               **_kwargs):
    '''Plot a log-scaled image'''

    axes_phantom = plt.gca()

    if kwargs is None:
        kwargs = dict()

    aspect = kwargs.pop('aspect', None)

    n, ticker, labeler = __get_shape_artists(data, horiz)
    t_log, t_inv = __log_scale(n)

    if horiz:
        if minor == 'log':
            ax2 = __log_scale(data.shape[0])[0]
        else:
            ax2 = np.linspace(0, data.shape[0], data.shape[0]).astype(int)
        ax1 = t_log
    else:
        if minor == 'log':
            ax1 = __log_scale(data.shape[1])[0]
        else:
            ax1 = np.linspace(0, data.shape[1], data.shape[1]).astype(int)

        ax2 = t_log

    args = (ax1, ax2, data)

    # NOTE:  2013-11-14 16:15:33 by Brian McFee <*****@*****.**>
    #  We draw the image twice here. This is a hack to get around
    #  NonUniformImage not properly setting hooks for color.
    #  Drawing twice enables things like colorbar() to work properly.

    im_phantom = img.NonUniformImage(axes_phantom,
                                     extent=(args[0].min(), args[0].max(),
                                             args[1].min(), args[1].max()),
                                     **kwargs)
    im_phantom.set_data(*args)

    kwargs['aspect'] = aspect

    axes_phantom.images[0] = im_phantom

    positions = np.linspace(0, n - 1, n_ticks, endpoint=True).astype(int)
    # One extra value here to catch nyquist
    values = np.linspace(0, 0.5 * sr, n, endpoint=True).astype(int)

    ticker(positions, values[t_inv[positions]])

    labeler(label)
예제 #2
0
 def surface_plot(self, x_range, y_range, data_matrix, plotAxis = None, interpolation_type = 'bilinear'):
     
     #Decide axis for the image to be plotted
     if plotAxis == None:
         plotAxis = self.Axis
     
     im = image.NonUniformImage(ax=plotAxis, interpolation=interpolation_type, cmap=cm.gist_earth)
     
     #Input data
     im.set_data(x_range, y_range, data_matrix)
     
     #Plot the image
     plotAxis.images.append(im)
     
     #Set the axis limit
     plotAxis.set_xlim(x_range[0],x_range[-1])
     plotAxis.set_ylim(y_range[0],y_range[-1])
예제 #3
0
def specshow(data,
             sr=22050,
             hop_length=512,
             x_axis=None,
             y_axis=None,
             n_xticks=5,
             n_yticks=5,
             fmin=None,
             fmax=None,
             **kwargs):
    '''Display a spectrogram/chromagram/cqt/etc.

    Functions as a drop-in replacement for ``matplotlib.pyplot.imshow``, but with useful defaults.

    :usage:
        >>> # Visualize an STFT with linear frequency scaling
        >>> D = np.abs(librosa.stft(y))
        >>> librosa.display.specshow(D, sr=sr, y_axis='linear')

        >>> # Or with logarithmic frequency scaling
        >>> librosa.display.specshow(D, sr=sr, y_axis='log')

        >>> # Visualize a CQT with note markers
        >>> CQT = librosa.cqt(y, sr, fmin=55, fmax=880)
        >>> librosa.display.specshow(CQT, sr=sr, y_axis='cqt_note', fmin=55, fmax=880)

        >>> # Draw time markers automatically
        >>> librosa.display.specshow(D, sr=sr, hop_length=hop_length, x_axis='time')

        >>> # Draw a chromagram with pitch classes
        >>> C = librosa.feature.chromagram(y, sr)
        >>> librosa.display.specshow(C, y_axis='chroma')

        >>> # Force a grayscale colormap (white -> black)
        >>> librosa.display.specshow(librosa.logamplitude(D), cmap='gray_r')

    :parameters:
      - data : np.ndarray
          Matrix to display (eg, spectrogram)

      - sr : int > 0
          Sample rate. Used to determine time scale in x-axis

      - hop_length : int > 0
          Hop length. Also used to determine time scale in x-axis

      - x_axis : None or {'time', 'frames', 'off'}
          If None or 'off', no x axis is displayed.
          If 'time', markers are shown as milliseconds, seconds, minutes, or hours.
          (See ``time_ticks()`` for details.)
          If 'frames', markers are shown as frame counts.

      - y_axis : None or {'linear', 'mel', 'cqt_hz', 'cqt_note', 'chroma', 'off'}
          - None or 'off': no y axis is displayed.
          - 'linear': frequency range is determined by the FFT window and sampling rate.
          - 'log': the image is displayed on a vertical log scale.
          - 'mel': frequencies are determined by the mel scale.
          - 'cqt_hz': frequencies are determined by the fmin and fmax values.
          - 'cqt_note': pitches are determined by the fmin and fmax values.
          - 'chroma': pitches are determined by the chroma filters.

      - n_xticks : int > 0
          If x_axis is drawn, the number of ticks to show

      - n_yticks : int > 0
          If y_axis is drawn, the number of ticks to show

      - fmin : float > 0 or None

      - fmax : float > 0 or None
          Used for setting the Mel or constantq frequency scales

      - kwargs
          Additional keyword arguments passed through to ``matplotlib.pyplot.imshow``.

    :returns:
      - image : ``matplotlib.image.AxesImage``
          As returned from ``matplotlib.pyplot.imshow``.

    :raises:
      - ValueError
          If y_axis is 'cqt_hz' or 'cqt_note' and fmin and fmax are not supplied.
    '''

    kwargs.setdefault('aspect', 'auto')
    kwargs.setdefault('origin', 'lower')
    kwargs.setdefault('interpolation', 'nearest')

    if np.issubdtype(data.dtype, np.complex):
        warnings.warn(
            'Trying to display complex-valued input. Showing magnitude instead.'
        )
        data = np.abs(data)

    kwargs.setdefault('cmap', cmap(data))

    # NOTE:  2013-11-14 16:15:33 by Brian McFee <*****@*****.**>pitch
    #  We draw the image twice here. This is a hack to get around NonUniformImage
    #  not properly setting hooks for color: drawing twice enables things like
    #  colorbar() to work properly.

    axes = plt.imshow(data, **kwargs)

    if y_axis is 'log':
        axes_phantom = plt.gca()

        # Non-uniform imshow doesn't like aspect
        del kwargs['aspect']
        im_phantom = img.NonUniformImage(axes_phantom, **kwargs)

        y_log, y_inv = __log_scale(data.shape[0])

        im_phantom.set_data(np.arange(0, data.shape[1]), y_log, data)
        axes_phantom.images.append(im_phantom)
        axes_phantom.set_ylim(0, data.shape[0])
        axes_phantom.set_xlim(0, data.shape[1])

    # Set up the y ticks
    positions = np.asarray(np.linspace(0, data.shape[0], n_yticks), dtype=int)

    if y_axis is 'linear':
        values = np.asarray(np.linspace(0, 0.5 * sr, data.shape[0] + 1),
                            dtype=int)

        plt.yticks(positions, values[positions])
        plt.ylabel('Hz')

    elif y_axis is 'log':

        values = np.asarray(np.linspace(0, 0.5 * sr, data.shape[0] + 1),
                            dtype=int)
        plt.yticks(positions, values[y_inv[positions]])

        plt.ylabel('Hz')

    elif y_axis is 'mel':
        m_args = {}
        if fmin is not None:
            m_args['fmin'] = fmin
        if fmax is not None:
            m_args['fmax'] = fmax

        # only two star-args here, defined immediately above
        values = librosa.core.mel_frequencies(
            n_mels=data.shape[0],  # pylint: disable=star-args
            extra=True,
            **m_args)[positions].astype(np.int)
        plt.yticks(positions, values)
        plt.ylabel('Hz')

    elif y_axis is 'cqt_hz':
        if fmax is None and fmin is None:
            raise ValueError(
                'fmin and fmax must be supplied for CQT axis display')

        positions = np.arange(0,
                              data.shape[0],
                              np.ceil(data.shape[0] / float(n_yticks)),
                              dtype=int)

        # Get frequencies
        values = librosa.core.cqt_frequencies(
            data.shape[0],
            fmin=fmin,
            bins_per_octave=int(data.shape[0] /
                                np.ceil(np.log2(fmax) - np.log2(fmin))))
        plt.yticks(positions, values[positions].astype(int))
        plt.ylabel('Hz')

    elif y_axis is 'cqt_note':
        if fmax is None and fmin is None:
            raise ValueError(
                'fmin and fmax must be supplied for CQT axis display')

        positions = np.arange(0,
                              data.shape[0],
                              np.ceil(data.shape[0] / float(n_yticks)),
                              dtype=int)

        # Get frequencies
        values = librosa.core.cqt_frequencies(
            data.shape[0],
            fmin=fmin,
            bins_per_octave=int(data.shape[0] /
                                np.ceil(np.log2(fmax) - np.log2(fmin))))
        values = librosa.core.midi_to_note(
            librosa.core.hz_to_midi(values[positions]))
        plt.yticks(positions, values)
        plt.ylabel('Note')

    elif y_axis is 'chroma':
        positions = np.arange(0, data.shape[0], max(1, data.shape[0] / 12))
        # Labels start at 9 here because chroma starts at A.
        values = librosa.core.midi_to_note(range(9, 9 + 12), octave=False)
        plt.yticks(positions, values)
        plt.ylabel('Pitch class')

    elif y_axis is None or y_axis is 'off':
        plt.yticks([])
        plt.ylabel('')

    else:
        raise ValueError('Unknown y_axis parameter: %s' % y_axis)

    # Set up the x ticks
    positions = np.asarray(np.linspace(0, data.shape[1], n_xticks), dtype=int)

    if x_axis is 'time':
        time_ticks(positions,
                   librosa.core.frames_to_time(positions,
                                               sr=sr,
                                               hop_length=hop_length),
                   n_ticks=None,
                   axis='x')

        plt.xlabel('Time')

    elif x_axis is 'frames':
        # Nothing to do here, plot is in frames
        plt.xticks(positions, positions)
        plt.xlabel('Frames')

    elif x_axis is None or x_axis is 'off':
        plt.xticks([])
        plt.xlabel('')

    else:
        raise ValueError('Unknown x_axis parameter: %s' % x_axis)

    return axes
예제 #4
0
 x = scipy.ndimage.zoom(x, 3)
 y = scipy.ndimage.zoom(y, 3)
 data_fitted = scipy.ndimage.zoom(data_fitted.reshape(H.shape), 3)
 plt.contour(x, y, data_fitted, 8, colors='w')
 plt.ylim(yedges[0], yedges[-2])
 plt.xlim(xedges[0], xedges[-2])
 plt.savefig("measured_elec_pho_corr_%d.png" % (run_num))
 plt.show()
 raw_input()
 plt.close()
 fig2 = plt.figure()
 ax2 = fig2.add_subplot(121, title='')
 X, Y = np.meshgrid(xedges, yedges)
 ax2.pcolormesh(X, Y, H)
 ax2 = fig2.add_subplot(122, title='')
 im2 = image.NonUniformImage(ax2, interpolation='bilinear')
 xcenters = xedges[:-1]  # + xedges[1:]) / 2
 ycenters = yedges[:-1]  # + yedges[1:]) / 2
 im2.set_data(xcenters, ycenters, H)
 ax2.images.append(im2)
 #      im2 = ax2.imshow(data_fitted, cmap=plt.cm.jet, origin='bottom',extent=(x.min(), x.max(),y.min(), y.max()))
 ax2.contour(x, y, data_fitted, 8, colors='w')
 plt.plot(
     x_vals,
     y_vals,
     'w-',
     label=
     "rotation angle:%.1f$^{\circ}\pm$%.1f$^{\circ}$\npeak photon number:%d$\pm$%d\n peak electron number:%d$\pm$%d\n photon intercept:%d$\pm$%d\n electron intercept:%d$\pm$%d"
     % (-np.rad2deg(np.arctan(slope)),
        -np.rad2deg(np.arctan(slope) * rotation_err), max_pho,
        max_pho * centerx_err, max_ele, max_ele * centery_err,