def specshow(data, x_coords=None, y_coords=None,<EOL>x_axis=None, y_axis=None,<EOL>sr=<NUM_LIT>, hop_length=<NUM_LIT>,<EOL>fmin=None, fmax=None,<EOL>bins_per_octave=<NUM_LIT:12>,<EOL>ax=None,<EOL>**kwargs):

if np.issubdtype(data.dtype, np.complexfloating):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>data = np.abs(data)<EOL><DEDENT>kwargs.setdefault('<STR_LIT>', cmap(data))<EOL>kwargs.setdefault('<STR_LIT>', True)<EOL>kwargs.setdefault('<STR_LIT>', '<STR_LIT:None>')<EOL>kwargs.setdefault('<STR_LIT>', '<STR_LIT>')<EOL>all_params = dict(kwargs=kwargs,<EOL>sr=sr,<EOL>fmin=fmin,<EOL>fmax=fmax,<EOL>bins_per_octave=bins_per_octave,<EOL>hop_length=hop_length)<EOL>y_coords = __mesh_coords(y_axis, y_coords, data.shape[<NUM_LIT:0>], **all_params)<EOL>x_coords = __mesh_coords(x_axis, x_coords, data.shape[<NUM_LIT:1>], **all_params)<EOL>axes = __check_axes(ax)<EOL>out = axes.pcolormesh(x_coords, y_coords, data, **kwargs)<EOL>__set_current_image(ax, out)<EOL>axes.set_xlim(x_coords.min(), x_coords.max())<EOL>axes.set_ylim(y_coords.min(), y_coords.max())<EOL>__scale_axes(axes, x_axis, '<STR_LIT:x>')<EOL>__scale_axes(axes, y_axis, '<STR_LIT:y>')<EOL>__decorate_axis(axes.xaxis, x_axis)<EOL>__decorate_axis(axes.yaxis, y_axis)<EOL>return axes<EOL>

Display a spectrogram/chromagram/cqt/etc.

    Parameters
    ----------
    data : np.ndarray [shape=(d, n)]
        Matrix to display (e.g., spectrogram)

    sr : number > 0 [scalar]
        Sample rate used to determine time scale in x-axis.

    hop_length : int > 0 [scalar]
        Hop length, also used to determine time scale in x-axis

    x_axis : None or str

    y_axis : None or str
        Range for the x- and y-axes.

        Valid types are:

        - None, 'none', or 'off' : no axis decoration is displayed.

        Frequency types:

        - 'linear', 'fft', 'hz' : frequency range is determined by
          the FFT window and sampling rate.
        - 'log' : the spectrum is displayed on a log scale.
        - 'mel' : frequencies are determined by the mel scale.
        - 'cqt_hz' : frequencies are determined by the CQT scale.
        - 'cqt_note' : pitches are determined by the CQT scale.

        All frequency types are plotted in units of Hz.

        Categorical types:

        - 'chroma' : pitches are determined by the chroma filters.
          Pitch classes are arranged at integer locations (0-11).

        - 'tonnetz' : axes are labeled by Tonnetz dimensions (0-5)
        - 'frames' : markers are shown as frame counts.

        Time types:

        - 'time' : markers are shown as milliseconds, seconds,
          minutes, or hours.
          Values are plotted in units of seconds.
        - 's' : markers are shown as seconds.
        - 'ms' : markers are shown as milliseconds.

        - 'lag' : like time, but past the halfway point counts
          as negative values.
        - 'lag_s' : same as lag, but in seconds.
        - 'lag_ms' : same as lag, but in milliseconds.

        Other:

        - 'tempo' : markers are shown as beats-per-minute (BPM)
            using a logarithmic scale.

    x_coords : np.ndarray [shape=data.shape[1]+1]
    y_coords : np.ndarray [shape=data.shape[0]+1]

        Optional positioning coordinates of the input data.
        These can be use to explicitly set the location of each
        element `data[i, j]`, e.g., for displaying beat-synchronous
        features in natural time coordinates.

        If not provided, they are inferred from `x_axis` and `y_axis`.

    fmin : float > 0 [scalar] or None
        Frequency of the lowest spectrogram bin.  Used for Mel and CQT
        scales.

        If `y_axis` is `cqt_hz` or `cqt_note` and `fmin` is not given,
        it is set by default to `note_to_hz('C1')`.

    fmax : float > 0 [scalar] or None
        Used for setting the Mel frequency scales

    bins_per_octave : int > 0 [scalar]
        Number of bins per octave.  Used for CQT frequency scale.

    ax : matplotlib.axes.Axes or None
        Axes to plot on instead of the default `plt.gca()`.

    kwargs : additional keyword arguments
        Arguments passed through to `matplotlib.pyplot.pcolormesh`.

        By default, the following options are set:

            - `rasterized=True`
            - `shading='flat'`
            - `edgecolors='None'`

    Returns
    -------
    axes
        The axis handle for the figure.

    See Also
    --------
    cmap : Automatic colormap detection

    matplotlib.pyplot.pcolormesh

    Examples
    --------
    Visualize an STFT power spectrum

    >>> import matplotlib.pyplot as plt
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> plt.figure(figsize=(12, 8))

    >>> D = librosa.amplitude_to_db(np.abs(librosa.stft(y)), ref=np.max)
    >>> plt.subplot(4, 2, 1)
    >>> librosa.display.specshow(D, y_axis='linear')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Linear-frequency power spectrogram')

    Or on a logarithmic scale

    >>> plt.subplot(4, 2, 2)
    >>> librosa.display.specshow(D, y_axis='log')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Log-frequency power spectrogram')

    Or use a CQT scale

    >>> CQT = librosa.amplitude_to_db(np.abs(librosa.cqt(y, sr=sr)), ref=np.max)
    >>> plt.subplot(4, 2, 3)
    >>> librosa.display.specshow(CQT, y_axis='cqt_note')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Constant-Q power spectrogram (note)')

    >>> plt.subplot(4, 2, 4)
    >>> librosa.display.specshow(CQT, y_axis='cqt_hz')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Constant-Q power spectrogram (Hz)')

    Draw a chromagram with pitch classes

    >>> C = librosa.feature.chroma_cqt(y=y, sr=sr)
    >>> plt.subplot(4, 2, 5)
    >>> librosa.display.specshow(C, y_axis='chroma')
    >>> plt.colorbar()
    >>> plt.title('Chromagram')

    Force a grayscale colormap (white -> black)

    >>> plt.subplot(4, 2, 6)
    >>> librosa.display.specshow(D, cmap='gray_r', y_axis='linear')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Linear power spectrogram (grayscale)')

    Draw time markers automatically

    >>> plt.subplot(4, 2, 7)
    >>> librosa.display.specshow(D, x_axis='time', y_axis='log')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Log power spectrogram')

    Draw a tempogram with BPM markers

    >>> plt.subplot(4, 2, 8)
    >>> Tgram = librosa.feature.tempogram(y=y, sr=sr)
    >>> librosa.display.specshow(Tgram, x_axis='time', y_axis='tempo')
    >>> plt.colorbar()
    >>> plt.title('Tempogram')
    >>> plt.tight_layout()

    Draw beat-synchronous chroma in natural time

    >>> plt.figure()
    >>> tempo, beat_f = librosa.beat.beat_track(y=y, sr=sr, trim=False)
    >>> beat_f = librosa.util.fix_frames(beat_f, x_max=C.shape[1])
    >>> Csync = librosa.util.sync(C, beat_f, aggregate=np.median)
    >>> beat_t = librosa.frames_to_time(beat_f, sr=sr)
    >>> ax1 = plt.subplot(2,1,1)
    >>> librosa.display.specshow(C, y_axis='chroma', x_axis='time')
    >>> plt.title('Chroma (linear time)')
    >>> ax2 = plt.subplot(2,1,2, sharex=ax1)
    >>> librosa.display.specshow(Csync, y_axis='chroma', x_axis='time',
    ...                          x_coords=beat_t)
    >>> plt.title('Chroma (beat time)')
    >>> plt.tight_layout()


if ax is None:<EOL><INDENT>import matplotlib.pyplot as plt<EOL>plt.sci(img)<EOL><DEDENT>

Helper to set the current image in pyplot mode.

    If the provided `ax` is not `None`, then we assume that the user is using the object API.
    In this case, the pyplot current image is not set.


def __mesh_coords(ax_type, coords, n, **kwargs):

if coords is not None:<EOL><INDENT>if len(coords) < n:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(len(coords), n))<EOL><DEDENT>return coords<EOL><DEDENT>coord_map = {'<STR_LIT>': __coord_fft_hz,<EOL>'<STR_LIT>': __coord_fft_hz,<EOL>'<STR_LIT>': __coord_fft_hz,<EOL>'<STR_LIT>': __coord_mel_hz,<EOL>'<STR_LIT>': __coord_cqt_hz,<EOL>'<STR_LIT>': __coord_cqt_hz,<EOL>'<STR_LIT>': __coord_cqt_hz,<EOL>'<STR_LIT>': __coord_chroma,<EOL>'<STR_LIT:time>': __coord_time,<EOL>'<STR_LIT:s>': __coord_time,<EOL>'<STR_LIT>': __coord_time,<EOL>'<STR_LIT>': __coord_time,<EOL>'<STR_LIT>': __coord_time,<EOL>'<STR_LIT>': __coord_time,<EOL>'<STR_LIT>': __coord_n,<EOL>'<STR_LIT>': __coord_n,<EOL>'<STR_LIT>': __coord_tempo,<EOL>'<STR_LIT>': __coord_n,<EOL>None: __coord_n}<EOL>if ax_type not in coord_map:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(ax_type))<EOL><DEDENT>return coord_map[ax_type](n, **kwargs)<EOL>


if axes is None:<EOL><INDENT>import matplotlib.pyplot as plt<EOL>axes = plt.gca()<EOL><DEDENT>elif not isinstance(axes, Axes):<EOL><INDENT>raise ValueError("<STR_LIT>"<EOL>"<STR_LIT>".format(type(axes)))<EOL><DEDENT>return axes<EOL>

Check if "axes" is an instance of an axis object. If not, use `gca`.


kwargs = dict()<EOL>if which == '<STR_LIT:x>':<EOL><INDENT>thresh = '<STR_LIT>'<EOL>base = '<STR_LIT>'<EOL>scale = '<STR_LIT>'<EOL>scaler = axes.set_xscale<EOL>limit = axes.set_xlim<EOL><DEDENT>else:<EOL><INDENT>thresh = '<STR_LIT>'<EOL>base = '<STR_LIT>'<EOL>scale = '<STR_LIT>'<EOL>scaler = axes.set_yscale<EOL>limit = axes.set_ylim<EOL><DEDENT>if ax_type == '<STR_LIT>':<EOL><INDENT>mode = '<STR_LIT>'<EOL>kwargs[thresh] = <NUM_LIT><EOL>kwargs[base] = <NUM_LIT:2><EOL><DEDENT>elif ax_type == '<STR_LIT>':<EOL><INDENT>mode = '<STR_LIT>'<EOL>kwargs[base] = <NUM_LIT:2><EOL>kwargs[thresh] = core.note_to_hz('<STR_LIT>')<EOL>kwargs[scale] = <NUM_LIT:0.5><EOL><DEDENT>elif ax_type in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>mode = '<STR_LIT>'<EOL>kwargs[base] = <NUM_LIT:2><EOL><DEDENT>elif ax_type == '<STR_LIT>':<EOL><INDENT>mode = '<STR_LIT>'<EOL>kwargs[base] = <NUM_LIT:2><EOL>limit(<NUM_LIT:16>, <NUM_LIT>)<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>scaler(mode, **kwargs)<EOL>


if ax_type == '<STR_LIT>':<EOL><INDENT>axis.set_major_formatter(TonnetzFormatter())<EOL>axis.set_major_locator(FixedLocator(<NUM_LIT:0.5> + np.arange(<NUM_LIT:6>)))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type == '<STR_LIT>':<EOL><INDENT>axis.set_major_formatter(ChromaFormatter())<EOL>axis.set_major_locator(FixedLocator(<NUM_LIT:0.5> +<EOL>np.add.outer(<NUM_LIT:12> * np.arange(<NUM_LIT:10>),<EOL>[<NUM_LIT:0>, <NUM_LIT:2>, <NUM_LIT:4>, <NUM_LIT:5>, <NUM_LIT:7>, <NUM_LIT:9>, <NUM_LIT:11>]).ravel()))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type == '<STR_LIT>':<EOL><INDENT>axis.set_major_formatter(ScalarFormatter())<EOL>axis.set_major_locator(LogLocator(base=<NUM_LIT>))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type == '<STR_LIT:time>':<EOL><INDENT>axis.set_major_formatter(TimeFormatter(unit=None, lag=False))<EOL>axis.set_major_locator(MaxNLocator(prune=None,<EOL>steps=[<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT:5>, <NUM_LIT:6>, <NUM_LIT:10>]))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type == '<STR_LIT:s>':<EOL><INDENT>axis.set_major_formatter(TimeFormatter(unit='<STR_LIT:s>', lag=False))<EOL>axis.set_major_locator(MaxNLocator(prune=None,<EOL>steps=[<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT:5>, <NUM_LIT:6>, <NUM_LIT:10>]))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type == '<STR_LIT>':<EOL><INDENT>axis.set_major_formatter(TimeFormatter(unit='<STR_LIT>', lag=False))<EOL>axis.set_major_locator(MaxNLocator(prune=None,<EOL>steps=[<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT:5>, <NUM_LIT:6>, <NUM_LIT:10>]))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type == '<STR_LIT>':<EOL><INDENT>axis.set_major_formatter(TimeFormatter(unit=None, lag=True))<EOL>axis.set_major_locator(MaxNLocator(prune=None,<EOL>steps=[<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT:5>, <NUM_LIT:6>, <NUM_LIT:10>]))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type == '<STR_LIT>':<EOL><INDENT>axis.set_major_formatter(TimeFormatter(unit='<STR_LIT:s>', lag=True))<EOL>axis.set_major_locator(MaxNLocator(prune=None,<EOL>steps=[<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT:5>, <NUM_LIT:6>, <NUM_LIT:10>]))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type == '<STR_LIT>':<EOL><INDENT>axis.set_major_formatter(TimeFormatter(unit='<STR_LIT>', lag=True))<EOL>axis.set_major_locator(MaxNLocator(prune=None,<EOL>steps=[<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT:5>, <NUM_LIT:6>, <NUM_LIT:10>]))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type == '<STR_LIT>':<EOL><INDENT>axis.set_major_formatter(NoteFormatter())<EOL>axis.set_major_locator(LogLocator(base=<NUM_LIT>))<EOL>axis.set_minor_formatter(NoteFormatter(major=False))<EOL>axis.set_minor_locator(LogLocator(base=<NUM_LIT>,<EOL>subs=<NUM_LIT>**(np.arange(<NUM_LIT:1>, <NUM_LIT:12>)/<NUM_LIT>)))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type in ['<STR_LIT>']:<EOL><INDENT>axis.set_major_formatter(LogHzFormatter())<EOL>axis.set_major_locator(LogLocator(base=<NUM_LIT>))<EOL>axis.set_minor_formatter(LogHzFormatter(major=False))<EOL>axis.set_minor_locator(LogLocator(base=<NUM_LIT>,<EOL>subs=<NUM_LIT>**(np.arange(<NUM_LIT:1>, <NUM_LIT:12>)/<NUM_LIT>)))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>axis.set_major_formatter(ScalarFormatter())<EOL>axis.set_major_locator(SymmetricalLogLocator(axis.get_transform()))<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>axis.set_major_formatter(ScalarFormatter())<EOL>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type in ['<STR_LIT>']:<EOL><INDENT>axis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif ax_type in ['<STR_LIT>', '<STR_LIT:none>', None]:<EOL><INDENT>axis.set_label_text('<STR_LIT>')<EOL>axis.set_ticks([])<EOL><DEDENT>

Configure axis tickers, locators, and labels


def __coord_fft_hz(n, sr=<NUM_LIT>, **_kwargs):

n_fft = <NUM_LIT:2> * (n - <NUM_LIT:1>)<EOL>basis = core.fft_frequencies(sr=sr, n_fft=n_fft)<EOL>fmax = basis[-<NUM_LIT:1>]<EOL>basis -= <NUM_LIT:0.5> * (basis[<NUM_LIT:1>] - basis[<NUM_LIT:0>])<EOL>basis = np.append(np.maximum(<NUM_LIT:0>, basis), [fmax])<EOL>return basis<EOL>


def __coord_mel_hz(n, fmin=<NUM_LIT:0>, fmax=<NUM_LIT>, **_kwargs):

if fmin is None:<EOL><INDENT>fmin = <NUM_LIT:0><EOL><DEDENT>if fmax is None:<EOL><INDENT>fmax = <NUM_LIT><EOL><DEDENT>basis = core.mel_frequencies(n, fmin=fmin, fmax=fmax)<EOL>basis[<NUM_LIT:1>:] -= <NUM_LIT:0.5> * np.diff(basis)<EOL>basis = np.append(np.maximum(<NUM_LIT:0>, basis), [fmax])<EOL>return basis<EOL>


def __coord_cqt_hz(n, fmin=None, bins_per_octave=<NUM_LIT:12>, **_kwargs):

if fmin is None:<EOL><INDENT>fmin = core.note_to_hz('<STR_LIT>')<EOL><DEDENT>return core.cqt_frequencies(n+<NUM_LIT:1>,<EOL>fmin=fmin / <NUM_LIT>**(<NUM_LIT:0.5>/bins_per_octave),<EOL>bins_per_octave=bins_per_octave)<EOL>


def __coord_chroma(n, bins_per_octave=<NUM_LIT:12>, **_kwargs):

return np.linspace(<NUM_LIT:0>, (<NUM_LIT> * n) / bins_per_octave, num=n+<NUM_LIT:1>, endpoint=True)<EOL>


def __coord_tempo(n, sr=<NUM_LIT>, hop_length=<NUM_LIT>, **_kwargs):

basis = core.tempo_frequencies(n+<NUM_LIT:2>, sr=sr, hop_length=hop_length)[<NUM_LIT:1>:]<EOL>edges = np.arange(<NUM_LIT:1>, n+<NUM_LIT:2>)<EOL>return basis * (edges + <NUM_LIT:0.5>) / edges<EOL>


return np.arange(n+<NUM_LIT:1>)<EOL>


def __coord_time(n, sr=<NUM_LIT>, hop_length=<NUM_LIT>, **_kwargs):

return core.frames_to_time(np.arange(n+<NUM_LIT:1>), sr=sr, hop_length=hop_length)<EOL>


_, dmax = self.axis.get_data_interval()<EOL>vmin, vmax = self.axis.get_view_interval()<EOL>if self.lag and x >= dmax * <NUM_LIT:0.5>:<EOL><INDENT>if x > dmax:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>value = np.abs(x - dmax)<EOL>sign = '<STR_LIT:->'<EOL><DEDENT>else:<EOL><INDENT>value = x<EOL>sign = '<STR_LIT>'<EOL><DEDENT>if self.unit == '<STR_LIT:s>':<EOL><INDENT>s = '<STR_LIT>'.format(value)<EOL><DEDENT>elif self.unit == '<STR_LIT>':<EOL><INDENT>s = '<STR_LIT>'.format(value * <NUM_LIT:1000>)<EOL><DEDENT>else:<EOL><INDENT>if vmax - vmin > <NUM_LIT>:<EOL><INDENT>s = '<STR_LIT>'.format(int(value / <NUM_LIT>),<EOL>int(np.mod(value / <NUM_LIT>, <NUM_LIT>)),<EOL>int(np.mod(value, <NUM_LIT>)))<EOL><DEDENT>elif vmax - vmin > <NUM_LIT>:<EOL><INDENT>s = '<STR_LIT>'.format(int(value / <NUM_LIT>),<EOL>int(np.mod(value, <NUM_LIT>)))<EOL><DEDENT>else:<EOL><INDENT>s = '<STR_LIT>'.format(value)<EOL><DEDENT><DEDENT>return '<STR_LIT>'.format(sign, s)<EOL>


return core.midi_to_note(int(x), octave=False, cents=False)<EOL>


return [r'<STR_LIT>', r'<STR_LIT>', r'<STR_LIT>',<EOL>r'<STR_LIT>', r'<STR_LIT>', r'<STR_LIT>'][int(x)]<EOL>


def load(path, sr=<NUM_LIT>, mono=True, offset=<NUM_LIT:0.0>, duration=None,<EOL>dtype=np.float32, res_type='<STR_LIT>'):

try:<EOL><INDENT>with sf.SoundFile(path) as sf_desc:<EOL><INDENT>sr_native = sf_desc.samplerate<EOL>if offset:<EOL><INDENT>sf_desc.seek(int(offset * sr_native))<EOL><DEDENT>if duration is not None:<EOL><INDENT>frame_duration = int(duration * sr_native)<EOL><DEDENT>else:<EOL><INDENT>frame_duration = -<NUM_LIT:1><EOL><DEDENT>y = sf_desc.read(frames=frame_duration, dtype=dtype, always_2d=False).T<EOL><DEDENT><DEDENT>except RuntimeError as exc:<EOL><INDENT>y, sr_native = __audioread_load(path, offset, duration, dtype)<EOL><DEDENT>if mono:<EOL><INDENT>y = to_mono(y)<EOL><DEDENT>if sr is not None:<EOL><INDENT>y = resample(y, sr_native, sr, res_type=res_type)<EOL><DEDENT>else:<EOL><INDENT>sr = sr_native<EOL><DEDENT>return y, sr<EOL>

Load an audio file as a floating point time series.

    Audio will be automatically resampled to the given rate
    (default `sr=22050`).

    To preserve the native sampling rate of the file, use `sr=None`.

    Parameters
    ----------
    path : string, int, or file-like object
        path to the input file.

        Any codec supported by `soundfile` or `audioread` will work.

        If the codec is supported by `soundfile`, then `path` can also be
        an open file descriptor (int), or any object implementing Python's
        file interface.

        If the codec is not supported by `soundfile` (e.g., MP3), then only
        string file paths are supported.

    sr   : number > 0 [scalar]
        target sampling rate

        'None' uses the native sampling rate

    mono : bool
        convert signal to mono

    offset : float
        start reading after this time (in seconds)

    duration : float
        only load up to this much audio (in seconds)

    dtype : numeric type
        data type of `y`

    res_type : str
        resample type (see note)

        .. note::
            By default, this uses `resampy`'s high-quality mode ('kaiser_best').

            For alternative resampling modes, see `resample`

        .. note::
           `audioread` may truncate the precision of the audio data to 16 bits.

           See https://librosa.github.io/librosa/ioformats.html for alternate
           loading methods.

    Returns
    -------
    y    : np.ndarray [shape=(n,) or (2, n)]
        audio time series

    sr   : number > 0 [scalar]
        sampling rate of `y`

    Examples
    --------
    >>> # Load an ogg vorbis file
    >>> filename = librosa.util.example_audio_file()
    >>> y, sr = librosa.load(filename)
    >>> y
    array([ -4.756e-06,  -6.020e-06, ...,  -1.040e-06,   0.000e+00], dtype=float32)
    >>> sr
    22050

    >>> # Load a file and resample to 11 KHz
    >>> filename = librosa.util.example_audio_file()
    >>> y, sr = librosa.load(filename, sr=11025)
    >>> y
    array([ -2.077e-06,  -2.928e-06, ...,  -4.395e-06,   0.000e+00], dtype=float32)
    >>> sr
    11025

    >>> # Load 5 seconds of a file, starting 15 seconds in
    >>> filename = librosa.util.example_audio_file()
    >>> y, sr = librosa.load(filename, offset=15.0, duration=5.0)
    >>> y
    array([ 0.069,  0.1  , ..., -0.101,  0.   ], dtype=float32)
    >>> sr
    22050


def __audioread_load(path, offset, duration, dtype):

y = []<EOL>with audioread.audio_open(path) as input_file:<EOL><INDENT>sr_native = input_file.samplerate<EOL>n_channels = input_file.channels<EOL>s_start = int(np.round(sr_native * offset)) * n_channels<EOL>if duration is None:<EOL><INDENT>s_end = np.inf<EOL><DEDENT>else:<EOL><INDENT>s_end = s_start + (int(np.round(sr_native * duration))<EOL>* n_channels)<EOL><DEDENT>n = <NUM_LIT:0><EOL>for frame in input_file:<EOL><INDENT>frame = util.buf_to_float(frame, dtype=dtype)<EOL>n_prev = n<EOL>n = n + len(frame)<EOL>if n < s_start:<EOL><INDENT>continue<EOL><DEDENT>if s_end < n_prev:<EOL><INDENT>break<EOL><DEDENT>if s_end < n:<EOL><INDENT>frame = frame[:s_end - n_prev]<EOL><DEDENT>if n_prev <= s_start <= n:<EOL><INDENT>frame = frame[(s_start - n_prev):]<EOL><DEDENT>y.append(frame)<EOL><DEDENT><DEDENT>if y:<EOL><INDENT>y = np.concatenate(y)<EOL>if n_channels > <NUM_LIT:1>:<EOL><INDENT>y = y.reshape((-<NUM_LIT:1>, n_channels)).T<EOL><DEDENT><DEDENT>else:<EOL><INDENT>y = np.empty(<NUM_LIT:0>, dtype=dtype)<EOL><DEDENT>return y, sr_native<EOL>

Load an audio buffer using audioread.

    This loads one block at a time, and then concatenates the results.


<EOL>util.valid_audio(y, mono=False)<EOL>if y.ndim > <NUM_LIT:1>:<EOL><INDENT>y = np.mean(y, axis=<NUM_LIT:0>)<EOL><DEDENT>return y<EOL>

Force an audio signal down to mono.

    Parameters
    ----------
    y : np.ndarray [shape=(2,n) or shape=(n,)]
        audio time series, either stereo or mono

    Returns
    -------
    y_mono : np.ndarray [shape=(n,)]
        `y` as a monophonic time-series

    Notes
    -----
    This function caches at level 20.

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file(), mono=False)
    >>> y.shape
    (2, 1355168)
    >>> y_mono = librosa.to_mono(y)
    >>> y_mono.shape
    (1355168,)


@cache(level=<NUM_LIT:20>)<EOL>def resample(y, orig_sr, target_sr, res_type='<STR_LIT>', fix=True, scale=False, **kwargs):

<EOL>util.valid_audio(y, mono=False)<EOL>if orig_sr == target_sr:<EOL><INDENT>return y<EOL><DEDENT>ratio = float(target_sr) / orig_sr<EOL>n_samples = int(np.ceil(y.shape[-<NUM_LIT:1>] * ratio))<EOL>if res_type in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>y_hat = scipy.signal.resample(y, n_samples, axis=-<NUM_LIT:1>)<EOL><DEDENT>elif res_type == '<STR_LIT>':<EOL><INDENT>if int(orig_sr) != orig_sr or int(target_sr) != target_sr:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>orig_sr = int(orig_sr)<EOL>target_sr = int(target_sr)<EOL>gcd = np.gcd(orig_sr, target_sr)<EOL>y_hat = scipy.signal.resample_poly(y, target_sr // gcd, orig_sr // gcd, axis=-<NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>y_hat = resampy.resample(y, orig_sr, target_sr, filter=res_type, axis=-<NUM_LIT:1>)<EOL><DEDENT>if fix:<EOL><INDENT>y_hat = util.fix_length(y_hat, n_samples, **kwargs)<EOL><DEDENT>if scale:<EOL><INDENT>y_hat /= np.sqrt(ratio)<EOL><DEDENT>return np.ascontiguousarray(y_hat, dtype=y.dtype)<EOL>

Resample a time series from orig_sr to target_sr

    Parameters
    ----------
    y : np.ndarray [shape=(n,) or shape=(2, n)]
        audio time series.  Can be mono or stereo.

    orig_sr : number > 0 [scalar]
        original sampling rate of `y`

    target_sr : number > 0 [scalar]
        target sampling rate

    res_type : str
        resample type (see note)

        .. note::
            By default, this uses `resampy`'s high-quality mode ('kaiser_best').

            To use a faster method, set `res_type='kaiser_fast'`.

            To use `scipy.signal.resample`, set `res_type='fft'` or `res_type='scipy'`.

            To use `scipy.signal.resample_poly`, set `res_type='polyphase'`.

        .. note::
            When using `res_type='polyphase'`, only integer sampling rates are
            supported.

    fix : bool
        adjust the length of the resampled signal to be of size exactly
        `ceil(target_sr * len(y) / orig_sr)`

    scale : bool
        Scale the resampled signal so that `y` and `y_hat` have approximately
        equal total energy.

    kwargs : additional keyword arguments
        If `fix==True`, additional keyword arguments to pass to
        `librosa.util.fix_length`.

    Returns
    -------
    y_hat : np.ndarray [shape=(n * target_sr / orig_sr,)]
        `y` resampled from `orig_sr` to `target_sr`

    Raises
    ------
    ParameterError
        If `res_type='polyphase'` and `orig_sr` or `target_sr` are not both
        integer-valued.

    See Also
    --------
    librosa.util.fix_length
    scipy.signal.resample
    resampy.resample

    Notes
    -----
    This function caches at level 20.

    Examples
    --------
    Downsample from 22 KHz to 8 KHz

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), sr=22050)
    >>> y_8k = librosa.resample(y, sr, 8000)
    >>> y.shape, y_8k.shape
    ((1355168,), (491671,))


def get_duration(y=None, sr=<NUM_LIT>, S=None, n_fft=<NUM_LIT>, hop_length=<NUM_LIT>,<EOL>center=True, filename=None):

if filename is not None:<EOL><INDENT>try:<EOL><INDENT>return sf.info(filename).duration<EOL><DEDENT>except:<EOL><INDENT>with audioread.audio_open(filename) as fdesc:<EOL><INDENT>return fdesc.duration<EOL><DEDENT><DEDENT><DEDENT>if y is None:<EOL><INDENT>if S is None:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>n_frames = S.shape[<NUM_LIT:1>]<EOL>n_samples = n_fft + hop_length * (n_frames - <NUM_LIT:1>)<EOL>if center:<EOL><INDENT>n_samples = n_samples - <NUM_LIT:2> * int(n_fft / <NUM_LIT:2>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>util.valid_audio(y, mono=False)<EOL>if y.ndim == <NUM_LIT:1>:<EOL><INDENT>n_samples = len(y)<EOL><DEDENT>else:<EOL><INDENT>n_samples = y.shape[-<NUM_LIT:1>]<EOL><DEDENT><DEDENT>return float(n_samples) / sr<EOL>

Compute the duration (in seconds) of an audio time series,
    feature matrix, or filename.

    Examples
    --------
    >>> # Load the example audio file
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.get_duration(y=y, sr=sr)
    61.45886621315193

    >>> # Or directly from an audio file
    >>> librosa.get_duration(filename=librosa.util.example_audio_file())
    61.4

    >>> # Or compute duration from an STFT matrix
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> S = librosa.stft(y)
    >>> librosa.get_duration(S=S, sr=sr)
    61.44

    >>> # Or a non-centered STFT matrix
    >>> S_left = librosa.stft(y, center=False)
    >>> librosa.get_duration(S=S_left, sr=sr)
    61.3471201814059

    Parameters
    ----------
    y : np.ndarray [shape=(n,), (2, n)] or None
        audio time series

    sr : number > 0 [scalar]
        audio sampling rate of `y`

    S : np.ndarray [shape=(d, t)] or None
        STFT matrix, or any STFT-derived matrix (e.g., chromagram
        or mel spectrogram).
        Durations calculated from spectrogram inputs are only accurate
        up to the frame resolution. If high precision is required,
        it is better to use the audio time series directly.

    n_fft       : int > 0 [scalar]
        FFT window size for `S`

    hop_length  : int > 0 [ scalar]
        number of audio samples between columns of `S`

    center  : boolean
        - If `True`, `S[:, t]` is centered at `y[t * hop_length]`
        - If `False`, then `S[:, t]` begins at `y[t * hop_length]`

    filename : str
        If provided, all other parameters are ignored, and the
        duration is calculated directly from the audio file.
        Note that this avoids loading the contents into memory,
        and is therefore useful for querying the duration of
        long files.

    Returns
    -------
    d : float >= 0
        Duration (in seconds) of the input time series or spectrogram.

    Raises
    ------
    ParameterError
        if none of `y`, `S`, or `filename` are provided.

    Notes
    -----
    `get_duration` can be applied to a file (`filename`), a spectrogram (`S`),
    or audio buffer (`y, sr`).  Only one of these three options should be
    provided.  If you do provide multiple options (e.g., `filename` and `S`),
    then `filename` takes precedence over `S`, and `S` takes precedence over
    `(y, sr)`.


@cache(level=<NUM_LIT:20>)<EOL>def autocorrelate(y, max_size=None, axis=-<NUM_LIT:1>):

if max_size is None:<EOL><INDENT>max_size = y.shape[axis]<EOL><DEDENT>max_size = int(min(max_size, y.shape[axis]))<EOL>fft = get_fftlib()<EOL>powspec = np.abs(fft.fft(y, n=<NUM_LIT:2> * y.shape[axis] + <NUM_LIT:1>, axis=axis))**<NUM_LIT:2><EOL>autocorr = fft.ifft(powspec, axis=axis)<EOL>subslice = [slice(None)] * autocorr.ndim<EOL>subslice[axis] = slice(max_size)<EOL>autocorr = autocorr[tuple(subslice)]<EOL>if not np.iscomplexobj(y):<EOL><INDENT>autocorr = autocorr.real<EOL><DEDENT>return autocorr<EOL>

Bounded auto-correlation

    Parameters
    ----------
    y : np.ndarray
        array to autocorrelate

    max_size  : int > 0 or None
        maximum correlation lag.
        If unspecified, defaults to `y.shape[axis]` (unbounded)

    axis : int
        The axis along which to autocorrelate.
        By default, the last axis (-1) is taken.

    Returns
    -------
    z : np.ndarray
        truncated autocorrelation `y*y` along the specified axis.
        If `max_size` is specified, then `z.shape[axis]` is bounded
        to `max_size`.

    Notes
    -----
    This function caches at level 20.

    Examples
    --------
    Compute full autocorrelation of y

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), offset=20, duration=10)
    >>> librosa.autocorrelate(y)
    array([  3.226e+03,   3.217e+03, ...,   8.277e-04,   3.575e-04], dtype=float32)

    Compute onset strength auto-correlation up to 4 seconds

    >>> import matplotlib.pyplot as plt
    >>> odf = librosa.onset.onset_strength(y=y, sr=sr, hop_length=512)
    >>> ac = librosa.autocorrelate(odf, max_size=4* sr / 512)
    >>> plt.plot(ac)
    >>> plt.title('Auto-correlation')
    >>> plt.xlabel('Lag (frames)')


if not isinstance(order, int) or order < <NUM_LIT:1>:<EOL><INDENT>raise ParameterError("<STR_LIT>")<EOL><DEDENT>util.valid_audio(y, mono=True)<EOL>return __lpc(y, order)<EOL>

Linear Prediction Coefficients via Burg's method

    This function applies Burg's method to estimate coefficients of a linear
    filter on `y` of order `order`.  Burg's method is an extension to the
    Yule-Walker approach, which are both sometimes referred to as LPC parameter
    estimation by autocorrelation.

    It follows the description and implementation approach described in the
    introduction in [1]_.  N.B. This paper describes a different method, which
    is not implemented here, but has been chosen for its clear explanation of
    Burg's technique in its introduction.

    .. [1] Larry Marple
           A New Autoregressive Spectrum Analysis Algorithm
           IEEE Transactions on Accoustics, Speech, and Signal Processing
           vol 28, no. 4, 1980

    Parameters
    ----------
    y : np.ndarray
        Time series to fit

    order : int > 0
        Order of the linear filter

    Returns
    -------
    a : np.ndarray of length order + 1
        LP prediction error coefficients, i.e. filter denominator polynomial

    Raises
    ------
    ParameterError
        - If y is not valid audio as per `util.valid_audio`
        - If order < 1 or not integer
    FloatingPointError
        - If y is ill-conditioned

    See also
    --------
    scipy.signal.lfilter

    Examples
    --------
    Compute LP coefficients of y at order 16 on entire series

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), offset=30,
    ...                      duration=10)
    >>> librosa.lpc(y, 16)

    Compute LP coefficients, and plot LP estimate of original series

    >>> import matplotlib.pyplot as plt
    >>> import scipy
    >>> y, sr = librosa.load(librosa.util.example_audio_file(), offset=30,
    ...                      duration=0.020)
    >>> a = librosa.lpc(y, 2)
    >>> y_hat = scipy.signal.lfilter([0] + -1*a[1:], [1], y)
    >>> plt.figure()
    >>> plt.plot(y)
    >>> plt.plot(y_hat)
    >>> plt.legend(['y', 'y_hat'])
    >>> plt.title('LP Model Forward Prediction')


@cache(level=<NUM_LIT:20>)<EOL>def zero_crossings(y, threshold=<NUM_LIT>, ref_magnitude=None, pad=True,<EOL>zero_pos=True, axis=-<NUM_LIT:1>):

<EOL>if threshold is None:<EOL><INDENT>threshold = <NUM_LIT:0.0><EOL><DEDENT>if six.callable(ref_magnitude):<EOL><INDENT>threshold = threshold * ref_magnitude(np.abs(y))<EOL><DEDENT>elif ref_magnitude is not None:<EOL><INDENT>threshold = threshold * ref_magnitude<EOL><DEDENT>if threshold > <NUM_LIT:0>:<EOL><INDENT>y = y.copy()<EOL>y[np.abs(y) <= threshold] = <NUM_LIT:0><EOL><DEDENT>if zero_pos:<EOL><INDENT>y_sign = np.signbit(y)<EOL><DEDENT>else:<EOL><INDENT>y_sign = np.sign(y)<EOL><DEDENT>slice_pre = [slice(None)] * y.ndim<EOL>slice_pre[axis] = slice(<NUM_LIT:1>, None)<EOL>slice_post = [slice(None)] * y.ndim<EOL>slice_post[axis] = slice(-<NUM_LIT:1>)<EOL>padding = [(<NUM_LIT:0>, <NUM_LIT:0>)] * y.ndim<EOL>padding[axis] = (<NUM_LIT:1>, <NUM_LIT:0>)<EOL>return np.pad((y_sign[tuple(slice_post)] != y_sign[tuple(slice_pre)]),<EOL>padding,<EOL>mode='<STR_LIT>',<EOL>constant_values=pad)<EOL>

Find the zero-crossings of a signal `y`: indices `i` such that
    `sign(y[i]) != sign(y[j])`.

    If `y` is multi-dimensional, then zero-crossings are computed along
    the specified `axis`.

    Parameters
    ----------
    y : np.ndarray
        The input array

    threshold : float > 0 or None
        If specified, values where `-threshold <= y <= threshold` are
        clipped to 0.

    ref_magnitude : float > 0 or callable
        If numeric, the threshold is scaled relative to `ref_magnitude`.

        If callable, the threshold is scaled relative to
        `ref_magnitude(np.abs(y))`.

    pad : boolean
        If `True`, then `y[0]` is considered a valid zero-crossing.

    zero_pos : boolean
        If `True` then the value 0 is interpreted as having positive sign.

        If `False`, then 0, -1, and +1 all have distinct signs.

    axis : int
        Axis along which to compute zero-crossings.

    Returns
    -------
    zero_crossings : np.ndarray [shape=y.shape, dtype=boolean]
        Indicator array of zero-crossings in `y` along the selected axis.

    Notes
    -----
    This function caches at level 20.

    Examples
    --------
    >>> # Generate a time-series
    >>> y = np.sin(np.linspace(0, 4 * 2 * np.pi, 20))
    >>> y
    array([  0.000e+00,   9.694e-01,   4.759e-01,  -7.357e-01,
            -8.372e-01,   3.247e-01,   9.966e-01,   1.646e-01,
            -9.158e-01,  -6.142e-01,   6.142e-01,   9.158e-01,
            -1.646e-01,  -9.966e-01,  -3.247e-01,   8.372e-01,
             7.357e-01,  -4.759e-01,  -9.694e-01,  -9.797e-16])
    >>> # Compute zero-crossings
    >>> z = librosa.zero_crossings(y)
    >>> z
    array([ True, False, False,  True, False,  True, False, False,
            True, False,  True, False,  True, False, False,  True,
           False,  True, False,  True], dtype=bool)
    >>> # Stack y against the zero-crossing indicator
    >>> np.vstack([y, z]).T
    array([[  0.000e+00,   1.000e+00],
           [  9.694e-01,   0.000e+00],
           [  4.759e-01,   0.000e+00],
           [ -7.357e-01,   1.000e+00],
           [ -8.372e-01,   0.000e+00],
           [  3.247e-01,   1.000e+00],
           [  9.966e-01,   0.000e+00],
           [  1.646e-01,   0.000e+00],
           [ -9.158e-01,   1.000e+00],
           [ -6.142e-01,   0.000e+00],
           [  6.142e-01,   1.000e+00],
           [  9.158e-01,   0.000e+00],
           [ -1.646e-01,   1.000e+00],
           [ -9.966e-01,   0.000e+00],
           [ -3.247e-01,   0.000e+00],
           [  8.372e-01,   1.000e+00],
           [  7.357e-01,   0.000e+00],
           [ -4.759e-01,   1.000e+00],
           [ -9.694e-01,   0.000e+00],
           [ -9.797e-16,   1.000e+00]])
    >>> # Find the indices of zero-crossings
    >>> np.nonzero(z)
    (array([ 0,  3,  5,  8, 10, 12, 15, 17, 19]),)


def clicks(times=None, frames=None, sr=<NUM_LIT>, hop_length=<NUM_LIT>,<EOL>click_freq=<NUM_LIT>, click_duration=<NUM_LIT:0.1>, click=None, length=None):

<EOL>if times is None:<EOL><INDENT>if frames is None:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>positions = frames_to_samples(frames, hop_length=hop_length)<EOL><DEDENT>else:<EOL><INDENT>positions = time_to_samples(times, sr=sr)<EOL><DEDENT>if click is not None:<EOL><INDENT>util.valid_audio(click, mono=True)<EOL><DEDENT>else:<EOL><INDENT>if click_duration <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if click_freq <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>angular_freq = <NUM_LIT:2> * np.pi * click_freq / float(sr)<EOL>click = np.logspace(<NUM_LIT:0>, -<NUM_LIT:10>,<EOL>num=int(np.round(sr * click_duration)),<EOL>base=<NUM_LIT>)<EOL>click *= np.sin(angular_freq * np.arange(len(click)))<EOL><DEDENT>if length is None:<EOL><INDENT>length = positions.max() + click.shape[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>if length < <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>positions = positions[positions < length]<EOL><DEDENT>click_signal = np.zeros(length, dtype=np.float32)<EOL>for start in positions:<EOL><INDENT>end = start + click.shape[<NUM_LIT:0>]<EOL>if end >= length:<EOL><INDENT>click_signal[start:] += click[:length - start]<EOL><DEDENT>else:<EOL><INDENT>click_signal[start:end] += click<EOL><DEDENT><DEDENT>return click_signal<EOL>

Returns a signal with the signal `click` placed at each specified time

    Parameters
    ----------
    times : np.ndarray or None
        times to place clicks, in seconds

    frames : np.ndarray or None
        frame indices to place clicks

    sr : number > 0
        desired sampling rate of the output signal

    hop_length : int > 0
        if positions are specified by `frames`, the number of samples between frames.

    click_freq : float > 0
        frequency (in Hz) of the default click signal.  Default is 1KHz.

    click_duration : float > 0
        duration (in seconds) of the default click signal.  Default is 100ms.

    click : np.ndarray or None
        optional click signal sample to use instead of the default blip.

    length : int > 0
        desired number of samples in the output signal

    Returns
    -------
    click_signal : np.ndarray
        Synthesized click signal

    Raises
    ------
    ParameterError
        - If neither `times` nor `frames` are provided.
        - If any of `click_freq`, `click_duration`, or `length` are out of range.

    Examples
    --------
    >>> # Sonify detected beat events
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr)
    >>> y_beats = librosa.clicks(frames=beats, sr=sr)

    >>> # Or generate a signal of the same length as y
    >>> y_beats = librosa.clicks(frames=beats, sr=sr, length=len(y))

    >>> # Or use timing instead of frame indices
    >>> times = librosa.frames_to_time(beats, sr=sr)
    >>> y_beat_times = librosa.clicks(times=times, sr=sr)

    >>> # Or with a click frequency of 880Hz and a 500ms sample
    >>> y_beat_times880 = librosa.clicks(times=times, sr=sr,
    ...                                  click_freq=880, click_duration=0.5)

    Display click waveform next to the spectrogram

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> S = librosa.feature.melspectrogram(y=y, sr=sr)
    >>> ax = plt.subplot(2,1,2)
    >>> librosa.display.specshow(librosa.power_to_db(S, ref=np.max),
    ...                          x_axis='time', y_axis='mel')
    >>> plt.subplot(2,1,1, sharex=ax)
    >>> librosa.display.waveplot(y_beat_times, sr=sr, label='Beat clicks')
    >>> plt.legend()
    >>> plt.xlim(15, 30)
    >>> plt.tight_layout()


def tone(frequency, sr=<NUM_LIT>, length=None, duration=None, phi=None):

if frequency is None:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if length is None:<EOL><INDENT>if duration is None:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>length = duration * sr<EOL><DEDENT>if phi is None:<EOL><INDENT>phi = -np.pi * <NUM_LIT:0.5><EOL><DEDENT>step = <NUM_LIT:1.0> / sr<EOL>return np.cos(<NUM_LIT:2> * np.pi * frequency * (np.arange(step * length, step=step)) + phi)<EOL>

Returns a pure tone signal. The signal generated is a cosine wave.

    Parameters
    ----------
    frequency : float > 0
        frequency

    sr : number > 0
        desired sampling rate of the output signal

    length : int > 0
        desired number of samples in the output signal. When both `duration` and `length` are defined,
        `length` would take priority.

    duration : float > 0
        desired duration in seconds. When both `duration` and `length` are defined, `length` would take priority.

    phi : float or None
        phase offset, in radians. If unspecified, defaults to `-np.pi * 0.5`.

    Returns
    -------
    tone_signal : np.ndarray [shape=(length,), dtype=float64]
        Synthesized pure sine tone signal

    Raises
    ------
    ParameterError
        - If `frequency` is not provided.
        - If neither `length` nor `duration` are provided.

    Examples
    --------
    >>> # Generate a pure sine tone A4
    >>> tone = librosa.tone(440, duration=1)

    >>> # Or generate the same signal using `length`
    >>> tone = librosa.tone(440, sr=22050, length=22050)

    Display spectrogram

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> S = librosa.feature.melspectrogram(y=tone)
    >>> librosa.display.specshow(librosa.power_to_db(S, ref=np.max),
    ...                          x_axis='time', y_axis='mel')


def chirp(fmin, fmax, sr=<NUM_LIT>, length=None, duration=None, linear=False, phi=None):

if fmin is None or fmax is None:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>period = <NUM_LIT:1.0> / sr<EOL>if length is None:<EOL><INDENT>if duration is None:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT><DEDENT>else:<EOL><INDENT>duration = period * length<EOL><DEDENT>if phi is None:<EOL><INDENT>phi = -np.pi * <NUM_LIT:0.5><EOL><DEDENT>method = '<STR_LIT>' if linear else '<STR_LIT>'<EOL>return scipy.signal.chirp(<EOL>np.arange(duration, step=period),<EOL>fmin,<EOL>duration,<EOL>fmax,<EOL>method=method,<EOL>phi=phi / np.pi * <NUM_LIT>,  <EOL>)<EOL>

Returns a chirp signal that goes from frequency `fmin` to frequency `fmax`

    Parameters
    ----------
    fmin : float > 0
        initial frequency

    fmax : float > 0
        final frequency

    sr : number > 0
        desired sampling rate of the output signal

    length : int > 0
        desired number of samples in the output signal.
        When both `duration` and `length` are defined, `length` would take priority.

    duration : float > 0
        desired duration in seconds.
        When both `duration` and `length` are defined, `length` would take priority.

    linear : boolean
        - If `True`, use a linear sweep, i.e., frequency changes linearly with time
        - If `False`, use a exponential sweep.
        Default is `False`.

    phi : float or None
        phase offset, in radians.
        If unspecified, defaults to `-np.pi * 0.5`.

    Returns
    -------
    chirp_signal : np.ndarray [shape=(length,), dtype=float64]
        Synthesized chirp signal

    Raises
    ------
    ParameterError
        - If either `fmin` or `fmax` are not provided.
        - If neither `length` nor `duration` are provided.

    See Also
    --------
    scipy.signal.chirp

    Examples
    --------
    >>> # Generate a exponential chirp from A4 to A5
    >>> exponential_chirp = librosa.chirp(440, 880, duration=1)

    >>> # Or generate the same signal using `length`
    >>> exponential_chirp = librosa.chirp(440, 880, sr=22050, length=22050)

    >>> # Or generate a linear chirp instead
    >>> linear_chirp = librosa.chirp(440, 880, duration=1, linear=True)

    Display spectrogram for both exponential and linear chirps

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> S_exponential = librosa.feature.melspectrogram(y=exponential_chirp)
    >>> ax = plt.subplot(2,1,1)
    >>> librosa.display.specshow(librosa.power_to_db(S_exponential, ref=np.max),
    ...                          x_axis='time', y_axis='mel')
    >>> plt.subplot(2,1,2, sharex=ax)
    >>> S_linear = librosa.feature.melspectrogram(y=linear_chirp)
    >>> librosa.display.specshow(librosa.power_to_db(S_linear, ref=np.max),
    ...                          x_axis='time', y_axis='mel')
    >>> plt.tight_layout()


def salience(S, freqs, h_range, weights=None, aggregate=None,<EOL>filter_peaks=True, fill_value=np.nan,  kind='<STR_LIT>', axis=<NUM_LIT:0>):

if aggregate is None:<EOL><INDENT>aggregate = np.average<EOL><DEDENT>if weights is None:<EOL><INDENT>weights = np.ones((len(h_range), ))<EOL><DEDENT>else:<EOL><INDENT>weights = np.array(weights, dtype=float)<EOL><DEDENT>S_harm = interp_harmonics(S, freqs, h_range, kind=kind, axis=axis)<EOL>if aggregate is np.average:<EOL><INDENT>S_sal = aggregate(S_harm, axis=<NUM_LIT:0>, weights=weights)<EOL><DEDENT>else:<EOL><INDENT>S_sal = aggregate(S_harm, axis=<NUM_LIT:0>)<EOL><DEDENT>if filter_peaks:<EOL><INDENT>S_peaks = scipy.signal.argrelmax(S, axis=<NUM_LIT:0>)<EOL>S_out = np.empty(S.shape)<EOL>S_out.fill(fill_value)<EOL>S_out[S_peaks[<NUM_LIT:0>], S_peaks[<NUM_LIT:1>]] = S_sal[S_peaks[<NUM_LIT:0>], S_peaks[<NUM_LIT:1>]]<EOL>S_sal = S_out<EOL><DEDENT>return S_sal<EOL>

Harmonic salience function.

    Parameters
    ----------
    S : np.ndarray [shape=(d, n)]
        input time frequency magnitude representation (stft, ifgram, etc).
        Must be real-valued and non-negative.
    freqs : np.ndarray, shape=(S.shape[axis])
        The frequency values corresponding to S's elements along the
        chosen axis.
    h_range : list-like, non-negative
        Harmonics to include in salience computation.  The first harmonic (1)
        corresponds to `S` itself. Values less than one (e.g., 1/2) correspond
        to sub-harmonics.
    weights : list-like
        The weight to apply to each harmonic in the summation. (default:
        uniform weights). Must be the same length as `harmonics`.
    aggregate : function
        aggregation function (default: `np.average`)
        If `aggregate=np.average`, then a weighted average is
        computed per-harmonic according to the specified weights.
        For all other aggregation functions, all harmonics
        are treated equally.
    filter_peaks : bool
        If true, returns harmonic summation only on frequencies of peak
        magnitude. Otherwise returns harmonic summation over the full spectrum.
        Defaults to True.
    fill_value : float
        The value to fill non-peaks in the output representation. (default:
        np.nan) Only used if `filter_peaks == True`.
    kind : str
        Interpolation type for harmonic estimation.
        See `scipy.interpolate.interp1d`.
    axis : int
        The axis along which to compute harmonics

    Returns
    -------
    S_sal : np.ndarray, shape=(len(h_range), [x.shape])
        `S_sal` will have the same shape as `S`, and measure
        the overal harmonic energy at each frequency.

    See Also
    --------
    interp_harmonics

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file(),
    ...                      duration=15, offset=30)
    >>> S = np.abs(librosa.stft(y))
    >>> freqs = librosa.core.fft_frequencies(sr)
    >>> harms = [1, 2, 3, 4]
    >>> weights = [1.0, 0.5, 0.33, 0.25]
    >>> S_sal = librosa.salience(S, freqs, harms, weights, fill_value=0)
    >>> print(S_sal.shape)
    (1025, 646)
    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> librosa.display.specshow(librosa.amplitude_to_db(S_sal,
    ...                                                  ref=np.max),
    ...                          sr=sr, y_axis='log', x_axis='time')
    >>> plt.colorbar()
    >>> plt.title('Salience spectrogram')
    >>> plt.tight_layout()


def interp_harmonics(x, freqs, h_range, kind='<STR_LIT>', fill_value=<NUM_LIT:0>, axis=<NUM_LIT:0>):

<EOL>out_shape = [len(h_range)]<EOL>out_shape.extend(x.shape)<EOL>x_out = np.zeros(out_shape, dtype=x.dtype)<EOL>if freqs.ndim == <NUM_LIT:1> and len(freqs) == x.shape[axis]:<EOL><INDENT>harmonics_1d(x_out, x, freqs, h_range,<EOL>kind=kind, fill_value=fill_value,<EOL>axis=axis)<EOL><DEDENT>elif freqs.ndim == <NUM_LIT:2> and freqs.shape == x.shape:<EOL><INDENT>harmonics_2d(x_out, x, freqs, h_range,<EOL>kind=kind, fill_value=fill_value,<EOL>axis=axis)<EOL><DEDENT>else:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(freqs.shape, x.shape))<EOL><DEDENT>return x_out<EOL>

Compute the energy at harmonics of time-frequency representation.

    Given a frequency-based energy representation such as a spectrogram
    or tempogram, this function computes the energy at the chosen harmonics
    of the frequency axis.  (See examples below.)
    The resulting harmonic array can then be used as input to a salience
    computation.

    Parameters
    ----------
    x : np.ndarray
        The input energy

    freqs : np.ndarray, shape=(X.shape[axis])
        The frequency values corresponding to X's elements along the
        chosen axis.

    h_range : list-like, non-negative
        Harmonics to compute.  The first harmonic (1) corresponds to `x`
        itself.
        Values less than one (e.g., 1/2) correspond to sub-harmonics.

    kind : str
        Interpolation type.  See `scipy.interpolate.interp1d`.

    fill_value : float
        The value to fill when extrapolating beyond the observed
        frequency range.

    axis : int
        The axis along which to compute harmonics

    Returns
    -------
    x_harm : np.ndarray, shape=(len(h_range), [x.shape])
        `x_harm[i]` will have the same shape as `x`, and measure
        the energy at the `h_range[i]` harmonic of each frequency.

    See Also
    --------
    scipy.interpolate.interp1d

    Examples
    --------
    Estimate the harmonics of a time-averaged tempogram

    >>> y, sr = librosa.load(librosa.util.example_audio_file(),
    ...                      duration=15, offset=30)
    >>> # Compute the time-varying tempogram and average over time
    >>> tempi = np.mean(librosa.feature.tempogram(y=y, sr=sr), axis=1)
    >>> # We'll measure the first five harmonics
    >>> h_range = [1, 2, 3, 4, 5]
    >>> f_tempo = librosa.tempo_frequencies(len(tempi), sr=sr)
    >>> # Build the harmonic tensor
    >>> t_harmonics = librosa.interp_harmonics(tempi, f_tempo, h_range)
    >>> print(t_harmonics.shape)
    (5, 384)

    >>> # And plot the results
    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> librosa.display.specshow(t_harmonics, x_axis='tempo', sr=sr)
    >>> plt.yticks(0.5 + np.arange(len(h_range)),
    ...            ['{:.3g}'.format(_) for _ in h_range])
    >>> plt.ylabel('Harmonic')
    >>> plt.xlabel('Tempo (BPM)')
    >>> plt.tight_layout()

    We can also compute frequency harmonics for spectrograms.
    To calculate sub-harmonic energy, use values < 1.

    >>> h_range = [1./3, 1./2, 1, 2, 3, 4]
    >>> S = np.abs(librosa.stft(y))
    >>> fft_freqs = librosa.fft_frequencies(sr=sr)
    >>> S_harm = librosa.interp_harmonics(S, fft_freqs, h_range, axis=0)
    >>> print(S_harm.shape)
    (6, 1025, 646)

    >>> plt.figure()
    >>> for i, _sh in enumerate(S_harm, 1):
    ...     plt.subplot(3, 2, i)
    ...     librosa.display.specshow(librosa.amplitude_to_db(_sh,
    ...                                                      ref=S.max()),
    ...                              sr=sr, y_axis='log')
    ...     plt.title('h={:.3g}'.format(h_range[i-1]))
    ...     plt.yticks([])
    >>> plt.tight_layout()


def harmonics_1d(harmonic_out, x, freqs, h_range, kind='<STR_LIT>',<EOL>fill_value=<NUM_LIT:0>, axis=<NUM_LIT:0>):

<EOL>f_interp = scipy.interpolate.interp1d(freqs, x,<EOL>kind=kind,<EOL>axis=axis,<EOL>copy=False,<EOL>bounds_error=False,<EOL>fill_value=fill_value)<EOL>idx_out = [slice(None)] * harmonic_out.ndim<EOL>interp_axis = <NUM_LIT:1> + (axis % x.ndim)<EOL>for h_index, harmonic in enumerate(h_range):<EOL><INDENT>idx_out[<NUM_LIT:0>] = h_index<EOL>for f_index, frequency in enumerate(freqs):<EOL><INDENT>idx_out[interp_axis] = f_index<EOL>harmonic_out[tuple(idx_out)] = f_interp(harmonic * frequency)<EOL><DEDENT><DEDENT>

Populate a harmonic tensor from a time-frequency representation.

    Parameters
    ----------
    harmonic_out : np.ndarray, shape=(len(h_range), X.shape)
        The output array to store harmonics

    X : np.ndarray
        The input energy

    freqs : np.ndarray, shape=(x.shape[axis])
        The frequency values corresponding to x's elements along the
        chosen axis.

    h_range : list-like, non-negative
        Harmonics to compute.  The first harmonic (1) corresponds to `x`
        itself.
        Values less than one (e.g., 1/2) correspond to sub-harmonics.

    kind : str
        Interpolation type.  See `scipy.interpolate.interp1d`.

    fill_value : float
        The value to fill when extrapolating beyond the observed
        frequency range.

    axis : int
        The axis along which to compute harmonics

    See Also
    --------
    harmonics
    scipy.interpolate.interp1d

    Examples
    --------
    Estimate the harmonics of a time-averaged tempogram

    >>> y, sr = librosa.load(librosa.util.example_audio_file(),
    ...                      duration=15, offset=30)
    >>> # Compute the time-varying tempogram and average over time
    >>> tempi = np.mean(librosa.feature.tempogram(y=y, sr=sr), axis=1)
    >>> # We'll measure the first five harmonics
    >>> h_range = [1, 2, 3, 4, 5]
    >>> f_tempo = librosa.tempo_frequencies(len(tempi), sr=sr)
    >>> # Build the harmonic tensor
    >>> t_harmonics = librosa.interp_harmonics(tempi, f_tempo, h_range)
    >>> print(t_harmonics.shape)
    (5, 384)

    >>> # And plot the results
    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> librosa.display.specshow(t_harmonics, x_axis='tempo', sr=sr)
    >>> plt.yticks(0.5 + np.arange(len(h_range)),
    ...            ['{:.3g}'.format(_) for _ in h_range])
    >>> plt.ylabel('Harmonic')
    >>> plt.xlabel('Tempo (BPM)')
    >>> plt.tight_layout()

    We can also compute frequency harmonics for spectrograms.
    To calculate subharmonic energy, use values < 1.

    >>> h_range = [1./3, 1./2, 1, 2, 3, 4]
    >>> S = np.abs(librosa.stft(y))
    >>> fft_freqs = librosa.fft_frequencies(sr=sr)
    >>> S_harm = librosa.interp_harmonics(S, fft_freqs, h_range, axis=0)
    >>> print(S_harm.shape)
    (6, 1025, 646)

    >>> plt.figure()
    >>> for i, _sh in enumerate(S_harm, 1):
    ...     plt.subplot(3,2,i)
    ...     librosa.display.specshow(librosa.amplitude_to_db(_sh,
    ...                                                      ref=S.max()),
    ...                              sr=sr, y_axis='log')
    ...     plt.title('h={:.3g}'.format(h_range[i-1]))
    ...     plt.yticks([])
    >>> plt.tight_layout()


def harmonics_2d(harmonic_out, x, freqs, h_range, kind='<STR_LIT>', fill_value=<NUM_LIT:0>,<EOL>axis=<NUM_LIT:0>):

idx_in = [slice(None)] * x.ndim<EOL>idx_freq = [slice(None)] * x.ndim<EOL>idx_out = [slice(None)] * harmonic_out.ndim<EOL>ni_axis = (<NUM_LIT:1> + axis) % x.ndim<EOL>for i in range(x.shape[ni_axis]):<EOL><INDENT>idx_in[ni_axis] = slice(i, i + <NUM_LIT:1>)<EOL>idx_freq[ni_axis] = i<EOL>idx_out[<NUM_LIT:1> + ni_axis] = idx_in[ni_axis]<EOL>harmonics_1d(harmonic_out[tuple(idx_out)], x[tuple(idx_in)], freqs[tuple(idx_freq)],<EOL>h_range, kind=kind, fill_value=fill_value,<EOL>axis=axis)<EOL><DEDENT>

Populate a harmonic tensor from a time-frequency representation with
    time-varying frequencies.

    Parameters
    ----------
    harmonic_out : np.ndarray
        The output array to store harmonics

    x : np.ndarray
        The input energy

    freqs : np.ndarray, shape=x.shape
        The frequency values corresponding to each element of `x`

    h_range : list-like, non-negative
        Harmonics to compute.  The first harmonic (1) corresponds to `x`
        itself.  Values less than one (e.g., 1/2) correspond to
        sub-harmonics.

    kind : str
        Interpolation type.  See `scipy.interpolate.interp1d`.

    fill_value : float
        The value to fill when extrapolating beyond the observed
        frequency range.

    axis : int
        The axis along which to compute harmonics

    See Also
    --------
    harmonics
    harmonics_1d


@cache(level=<NUM_LIT:20>)<EOL>def cqt(y, sr=<NUM_LIT>, hop_length=<NUM_LIT>, fmin=None, n_bins=<NUM_LIT>,<EOL>bins_per_octave=<NUM_LIT:12>, tuning=<NUM_LIT:0.0>, filter_scale=<NUM_LIT:1>,<EOL>norm=<NUM_LIT:1>, sparsity=<NUM_LIT>, window='<STR_LIT>',<EOL>scale=True, pad_mode='<STR_LIT>', res_type=None):

<EOL>n_octaves = int(np.ceil(float(n_bins) / bins_per_octave))<EOL>n_filters = min(bins_per_octave, n_bins)<EOL>len_orig = len(y)<EOL>if fmin is None:<EOL><INDENT>fmin = note_to_hz('<STR_LIT>')<EOL><DEDENT>if tuning is None:<EOL><INDENT>tuning = estimate_tuning(y=y, sr=sr)<EOL><DEDENT>freqs = cqt_frequencies(n_bins, fmin,<EOL>bins_per_octave=bins_per_octave, tuning=tuning)[-bins_per_octave:]<EOL>fmin_t = np.min(freqs)<EOL>fmax_t = np.max(freqs)<EOL>Q = float(filter_scale) / (<NUM_LIT>**(<NUM_LIT:1.> / bins_per_octave) - <NUM_LIT:1>)<EOL>filter_cutoff = fmax_t * (<NUM_LIT:1> + <NUM_LIT:0.5> * filters.window_bandwidth(window) / Q)<EOL>nyquist = sr / <NUM_LIT><EOL>auto_resample = False<EOL>if not res_type:<EOL><INDENT>auto_resample = True<EOL>if filter_cutoff < audio.BW_FASTEST * nyquist:<EOL><INDENT>res_type = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>res_type = '<STR_LIT>'<EOL><DEDENT><DEDENT>y, sr, hop_length = __early_downsample(y, sr, hop_length,<EOL>res_type,<EOL>n_octaves,<EOL>nyquist, filter_cutoff, scale)<EOL>cqt_resp = []<EOL>if auto_resample and res_type != '<STR_LIT>':<EOL><INDENT>fft_basis, n_fft, _ = __cqt_filter_fft(sr, fmin_t,<EOL>n_filters,<EOL>bins_per_octave,<EOL>tuning,<EOL>filter_scale,<EOL>norm,<EOL>sparsity,<EOL>window=window)<EOL>cqt_resp.append(__cqt_response(y, n_fft, hop_length, fft_basis, pad_mode))<EOL>fmin_t /= <NUM_LIT:2><EOL>fmax_t /= <NUM_LIT:2><EOL>n_octaves -= <NUM_LIT:1><EOL>filter_cutoff = fmax_t * (<NUM_LIT:1> + <NUM_LIT:0.5> * filters.window_bandwidth(window) / Q)<EOL>res_type = '<STR_LIT>'<EOL><DEDENT>num_twos = __num_two_factors(hop_length)<EOL>if num_twos < n_octaves - <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>.format(n_octaves - <NUM_LIT:1>, n_octaves))<EOL><DEDENT>fft_basis, n_fft, _ = __cqt_filter_fft(sr, fmin_t,<EOL>n_filters,<EOL>bins_per_octave,<EOL>tuning,<EOL>filter_scale,<EOL>norm,<EOL>sparsity,<EOL>window=window)<EOL>my_y, my_sr, my_hop = y, sr, hop_length<EOL>for i in range(n_octaves):<EOL><INDENT>if i > <NUM_LIT:0>:<EOL><INDENT>if len(my_y) < <NUM_LIT:2>:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(len_orig,<EOL>n_octaves))<EOL><DEDENT>my_y = audio.resample(my_y, <NUM_LIT:2>, <NUM_LIT:1>,<EOL>res_type=res_type,<EOL>scale=True)<EOL>fft_basis[:] *= np.sqrt(<NUM_LIT:2>)<EOL>my_sr /= <NUM_LIT><EOL>my_hop //= <NUM_LIT:2><EOL><DEDENT>cqt_resp.append(__cqt_response(my_y, n_fft, my_hop, fft_basis, pad_mode))<EOL><DEDENT>C = __trim_stack(cqt_resp, n_bins)<EOL>if scale:<EOL><INDENT>lengths = filters.constant_q_lengths(sr, fmin,<EOL>n_bins=n_bins,<EOL>bins_per_octave=bins_per_octave,<EOL>tuning=tuning,<EOL>window=window,<EOL>filter_scale=filter_scale)<EOL>C /= np.sqrt(lengths[:, np.newaxis])<EOL><DEDENT>return C<EOL>

Compute the constant-Q transform of an audio signal.

    This implementation is based on the recursive sub-sampling method
    described by [1]_.

    .. [1] Schoerkhuber, Christian, and Anssi Klapuri.
        "Constant-Q transform toolbox for music processing."
        7th Sound and Music Computing Conference, Barcelona, Spain. 2010.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)]
        audio time series

    sr : number > 0 [scalar]
        sampling rate of `y`

    hop_length : int > 0 [scalar]
        number of samples between successive CQT columns.

    fmin : float > 0 [scalar]
        Minimum frequency. Defaults to C1 ~= 32.70 Hz

    n_bins : int > 0 [scalar]
        Number of frequency bins, starting at `fmin`

    bins_per_octave : int > 0 [scalar]
        Number of bins per octave

    tuning : None or float in `[-0.5, 0.5)`
        Tuning offset in fractions of a bin (cents).

        If `None`, tuning will be automatically estimated from the signal.

    filter_scale : float > 0
        Filter scale factor. Small values (<1) use shorter windows
        for improved time resolution.

    norm : {inf, -inf, 0, float > 0}
        Type of norm to use for basis function normalization.
        See `librosa.util.normalize`.

    sparsity : float in [0, 1)
        Sparsify the CQT basis by discarding up to `sparsity`
        fraction of the energy in each basis.

        Set `sparsity=0` to disable sparsification.

    window : str, tuple, number, or function
        Window specification for the basis filters.
        See `filters.get_window` for details.

    scale : bool
        If `True`, scale the CQT response by square-root the length of
        each channel's filter.  This is analogous to `norm='ortho'` in FFT.

        If `False`, do not scale the CQT. This is analogous to
        `norm=None` in FFT.

    pad_mode : string
        Padding mode for centered frame analysis.

        See also: `librosa.core.stft` and `np.pad`.

    res_type : string [optional]
        The resampling mode for recursive downsampling.

        By default, `cqt` will adaptively select a resampling mode
        which trades off accuracy at high frequencies for efficiency at low frequencies.

        You can override this by specifying a resampling mode as supported by
        `librosa.core.resample`.  For example, `res_type='fft'` will use a high-quality,
        but potentially slow FFT-based down-sampling, while `res_type='polyphase'` will
        use a fast, but potentially inaccurate down-sampling.

    Returns
    -------
    CQT : np.ndarray [shape=(n_bins, t), dtype=np.complex or np.float]
        Constant-Q value each frequency at each time.

    Raises
    ------
    ParameterError
        If `hop_length` is not an integer multiple of
        `2**(n_bins / bins_per_octave)`

        Or if `y` is too short to support the frequency range of the CQT.

    See Also
    --------
    librosa.core.resample
    librosa.util.normalize

    Notes
    -----
    This function caches at level 20.

    Examples
    --------
    Generate and plot a constant-Q power spectrum

    >>> import matplotlib.pyplot as plt
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> C = np.abs(librosa.cqt(y, sr=sr))
    >>> librosa.display.specshow(librosa.amplitude_to_db(C, ref=np.max),
    ...                          sr=sr, x_axis='time', y_axis='cqt_note')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Constant-Q power spectrum')
    >>> plt.tight_layout()

    Limit the frequency range

    >>> C = np.abs(librosa.cqt(y, sr=sr, fmin=librosa.note_to_hz('C2'),
    ...                 n_bins=60))
    >>> C
    array([[  8.827e-04,   9.293e-04, ...,   3.133e-07,   2.942e-07],
           [  1.076e-03,   1.068e-03, ...,   1.153e-06,   1.148e-06],
           ...,
           [  1.042e-07,   4.087e-07, ...,   1.612e-07,   1.928e-07],
           [  2.363e-07,   5.329e-07, ...,   1.294e-07,   1.611e-07]])

    Using a higher frequency resolution

    >>> C = np.abs(librosa.cqt(y, sr=sr, fmin=librosa.note_to_hz('C2'),
    ...                 n_bins=60 * 2, bins_per_octave=12 * 2))
    >>> C
    array([[  1.536e-05,   5.848e-05, ...,   3.241e-07,   2.453e-07],
           [  1.856e-03,   1.854e-03, ...,   2.397e-08,   3.549e-08],
           ...,
           [  2.034e-07,   4.245e-07, ...,   6.213e-08,   1.463e-07],
           [  4.896e-08,   5.407e-07, ...,   9.176e-08,   1.051e-07]])


@cache(level=<NUM_LIT:20>)<EOL>def hybrid_cqt(y, sr=<NUM_LIT>, hop_length=<NUM_LIT>, fmin=None, n_bins=<NUM_LIT>,<EOL>bins_per_octave=<NUM_LIT:12>, tuning=<NUM_LIT:0.0>, filter_scale=<NUM_LIT:1>,<EOL>norm=<NUM_LIT:1>, sparsity=<NUM_LIT>, window='<STR_LIT>', scale=True,<EOL>pad_mode='<STR_LIT>', res_type=None):

if fmin is None:<EOL><INDENT>fmin = note_to_hz('<STR_LIT>')<EOL><DEDENT>if tuning is None:<EOL><INDENT>tuning = estimate_tuning(y=y, sr=sr)<EOL><DEDENT>freqs = cqt_frequencies(n_bins, fmin,<EOL>bins_per_octave=bins_per_octave,<EOL>tuning=tuning)<EOL>lengths = filters.constant_q_lengths(sr, fmin,<EOL>n_bins=n_bins,<EOL>bins_per_octave=bins_per_octave,<EOL>tuning=tuning,<EOL>filter_scale=filter_scale,<EOL>window=window)<EOL>pseudo_filters = <NUM_LIT>**np.ceil(np.log2(lengths)) < <NUM_LIT:2> * hop_length<EOL>n_bins_pseudo = int(np.sum(pseudo_filters))<EOL>n_bins_full = n_bins - n_bins_pseudo<EOL>cqt_resp = []<EOL>if n_bins_pseudo > <NUM_LIT:0>:<EOL><INDENT>fmin_pseudo = np.min(freqs[pseudo_filters])<EOL>cqt_resp.append(pseudo_cqt(y, sr,<EOL>hop_length=hop_length,<EOL>fmin=fmin_pseudo,<EOL>n_bins=n_bins_pseudo,<EOL>bins_per_octave=bins_per_octave,<EOL>tuning=tuning,<EOL>filter_scale=filter_scale,<EOL>norm=norm,<EOL>sparsity=sparsity,<EOL>window=window,<EOL>scale=scale,<EOL>pad_mode=pad_mode))<EOL><DEDENT>if n_bins_full > <NUM_LIT:0>:<EOL><INDENT>cqt_resp.append(np.abs(cqt(y, sr,<EOL>hop_length=hop_length,<EOL>fmin=fmin,<EOL>n_bins=n_bins_full,<EOL>bins_per_octave=bins_per_octave,<EOL>tuning=tuning,<EOL>filter_scale=filter_scale,<EOL>norm=norm,<EOL>sparsity=sparsity,<EOL>window=window,<EOL>scale=scale,<EOL>pad_mode=pad_mode,<EOL>res_type=res_type)))<EOL><DEDENT>return __trim_stack(cqt_resp, n_bins)<EOL>

Compute the hybrid constant-Q transform of an audio signal.

    Here, the hybrid CQT uses the pseudo CQT for higher frequencies where
    the hop_length is longer than half the filter length and the full CQT
    for lower frequencies.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)]
        audio time series

    sr : number > 0 [scalar]
        sampling rate of `y`

    hop_length : int > 0 [scalar]
        number of samples between successive CQT columns.

    fmin : float > 0 [scalar]
        Minimum frequency. Defaults to C1 ~= 32.70 Hz

    n_bins : int > 0 [scalar]
        Number of frequency bins, starting at `fmin`

    bins_per_octave : int > 0 [scalar]
        Number of bins per octave

    tuning : None or float in `[-0.5, 0.5)`
        Tuning offset in fractions of a bin (cents).

        If `None`, tuning will be automatically estimated from the signal.

    filter_scale : float > 0
        Filter filter_scale factor. Larger values use longer windows.

    sparsity : float in [0, 1)
        Sparsify the CQT basis by discarding up to `sparsity`
        fraction of the energy in each basis.

        Set `sparsity=0` to disable sparsification.

    window : str, tuple, number, or function
        Window specification for the basis filters.
        See `filters.get_window` for details.

    pad_mode : string
        Padding mode for centered frame analysis.

        See also: `librosa.core.stft` and `np.pad`.

    res_type : string
        Resampling mode.  See `librosa.core.cqt` for details.

    Returns
    -------
    CQT : np.ndarray [shape=(n_bins, t), dtype=np.float]
        Constant-Q energy for each frequency at each time.

    Raises
    ------
    ParameterError
        If `hop_length` is not an integer multiple of
        `2**(n_bins / bins_per_octave)`

        Or if `y` is too short to support the frequency range of the CQT.

    See Also
    --------
    cqt
    pseudo_cqt

    Notes
    -----
    This function caches at level 20.


@cache(level=<NUM_LIT:20>)<EOL>def pseudo_cqt(y, sr=<NUM_LIT>, hop_length=<NUM_LIT>, fmin=None, n_bins=<NUM_LIT>,<EOL>bins_per_octave=<NUM_LIT:12>, tuning=<NUM_LIT:0.0>, filter_scale=<NUM_LIT:1>,<EOL>norm=<NUM_LIT:1>, sparsity=<NUM_LIT>, window='<STR_LIT>', scale=True,<EOL>pad_mode='<STR_LIT>'):

if fmin is None:<EOL><INDENT>fmin = note_to_hz('<STR_LIT>')<EOL><DEDENT>if tuning is None:<EOL><INDENT>tuning = estimate_tuning(y=y, sr=sr)<EOL><DEDENT>fft_basis, n_fft, _ = __cqt_filter_fft(sr, fmin, n_bins,<EOL>bins_per_octave,<EOL>tuning, filter_scale,<EOL>norm, sparsity,<EOL>hop_length=hop_length,<EOL>window=window)<EOL>fft_basis = np.abs(fft_basis)<EOL>D = np.abs(stft(y, n_fft=n_fft, hop_length=hop_length, pad_mode=pad_mode))<EOL>C = fft_basis.dot(D)<EOL>if scale:<EOL><INDENT>C /= np.sqrt(n_fft)<EOL><DEDENT>else:<EOL><INDENT>lengths = filters.constant_q_lengths(sr, fmin,<EOL>n_bins=n_bins,<EOL>bins_per_octave=bins_per_octave,<EOL>tuning=tuning,<EOL>window=window,<EOL>filter_scale=filter_scale)<EOL>C *= np.sqrt(lengths[:, np.newaxis] / n_fft)<EOL><DEDENT>return C<EOL>

Compute the pseudo constant-Q transform of an audio signal.

    This uses a single fft size that is the smallest power of 2 that is greater
    than or equal to the max of:

        1. The longest CQT filter
        2. 2x the hop_length

    Parameters
    ----------
    y : np.ndarray [shape=(n,)]
        audio time series

    sr : number > 0 [scalar]
        sampling rate of `y`

    hop_length : int > 0 [scalar]
        number of samples between successive CQT columns.

    fmin : float > 0 [scalar]
        Minimum frequency. Defaults to C1 ~= 32.70 Hz

    n_bins : int > 0 [scalar]
        Number of frequency bins, starting at `fmin`

    bins_per_octave : int > 0 [scalar]
        Number of bins per octave

    tuning : None or float in `[-0.5, 0.5)`
        Tuning offset in fractions of a bin (cents).

        If `None`, tuning will be automatically estimated from the signal.

    filter_scale : float > 0
        Filter filter_scale factor. Larger values use longer windows.

    sparsity : float in [0, 1)
        Sparsify the CQT basis by discarding up to `sparsity`
        fraction of the energy in each basis.

        Set `sparsity=0` to disable sparsification.

    window : str, tuple, number, or function
        Window specification for the basis filters.
        See `filters.get_window` for details.

    pad_mode : string
        Padding mode for centered frame analysis.

        See also: `librosa.core.stft` and `np.pad`.

    Returns
    -------
    CQT : np.ndarray [shape=(n_bins, t), dtype=np.float]
        Pseudo Constant-Q energy for each frequency at each time.

    Raises
    ------
    ParameterError
        If `hop_length` is not an integer multiple of
        `2**(n_bins / bins_per_octave)`

        Or if `y` is too short to support the frequency range of the CQT.

    Notes
    -----
    This function caches at level 20.


@cache(level=<NUM_LIT>)<EOL>def icqt(C, sr=<NUM_LIT>, hop_length=<NUM_LIT>, fmin=None, bins_per_octave=<NUM_LIT:12>,<EOL>tuning=<NUM_LIT:0.0>, filter_scale=<NUM_LIT:1>, norm=<NUM_LIT:1>, sparsity=<NUM_LIT>, window='<STR_LIT>',<EOL>scale=True, length=None, amin=util.Deprecated(), res_type='<STR_LIT>'):

if fmin is None:<EOL><INDENT>fmin = note_to_hz('<STR_LIT>')<EOL><DEDENT>n_bins = len(C)<EOL>freqs = cqt_frequencies(n_bins, fmin,<EOL>bins_per_octave=bins_per_octave,<EOL>tuning=tuning)[-bins_per_octave:]<EOL>n_filters = min(n_bins, bins_per_octave)<EOL>fft_basis, n_fft, lengths = __cqt_filter_fft(sr, np.min(freqs),<EOL>n_filters,<EOL>bins_per_octave,<EOL>tuning,<EOL>filter_scale,<EOL>norm,<EOL>sparsity=sparsity,<EOL>window=window)<EOL>if hop_length > min(lengths):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(hop_length, min(lengths)))<EOL><DEDENT>fft_basis = fft_basis.todense() * n_fft / lengths[:, np.newaxis]<EOL>inv_basis = fft_basis.H<EOL>n_octaves = int(np.ceil(float(n_bins) / bins_per_octave))<EOL>y = None<EOL>for octave in range(n_octaves - <NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>slice_ = slice(-(octave+<NUM_LIT:1>) * bins_per_octave - <NUM_LIT:1>,<EOL>-(octave) * bins_per_octave - <NUM_LIT:1>)<EOL>C_oct = C[slice_]<EOL>inv_oct = inv_basis[:, -C_oct.shape[<NUM_LIT:0>]:]<EOL>oct_hop = hop_length // <NUM_LIT:2>**octave<EOL>if scale:<EOL><INDENT>C_scale = np.sqrt(lengths[-C_oct.shape[<NUM_LIT:0>]:, np.newaxis]) / n_fft<EOL><DEDENT>else:<EOL><INDENT>C_scale = lengths[-C_oct.shape[<NUM_LIT:0>]:, np.newaxis] * np.sqrt(<NUM_LIT:2>**octave) / n_fft<EOL><DEDENT>D_oct = inv_oct.dot(C_oct / C_scale)<EOL>y_oct = istft(D_oct, window='<STR_LIT>', hop_length=oct_hop)<EOL>if y is None:<EOL><INDENT>y = y_oct<EOL><DEDENT>else:<EOL><INDENT>y = audio.resample(y, <NUM_LIT:1>, <NUM_LIT:2>, scale=True, res_type=res_type, fix=False)<EOL>y[:len(y_oct)] += y_oct<EOL><DEDENT><DEDENT>if length:<EOL><INDENT>y = util.fix_length(y, length)<EOL><DEDENT>return y<EOL>

Compute the inverse constant-Q transform.

    Given a constant-Q transform representation `C` of an audio signal `y`,
    this function produces an approximation `y_hat`.

    Parameters
    ----------
    C : np.ndarray, [shape=(n_bins, n_frames)]
        Constant-Q representation as produced by `core.cqt`

    hop_length : int > 0 [scalar]
        number of samples between successive frames

    fmin : float > 0 [scalar]
        Minimum frequency. Defaults to C1 ~= 32.70 Hz

    tuning : float in `[-0.5, 0.5)` [scalar]
        Tuning offset in fractions of a bin (cents).

    filter_scale : float > 0 [scalar]
        Filter scale factor. Small values (<1) use shorter windows
        for improved time resolution.

    norm : {inf, -inf, 0, float > 0}
        Type of norm to use for basis function normalization.
        See `librosa.util.normalize`.

    sparsity : float in [0, 1)
        Sparsify the CQT basis by discarding up to `sparsity`
        fraction of the energy in each basis.

        Set `sparsity=0` to disable sparsification.

    window : str, tuple, number, or function
        Window specification for the basis filters.
        See `filters.get_window` for details.

    scale : bool
        If `True`, scale the CQT response by square-root the length
        of each channel's filter. This is analogous to `norm='ortho'` in FFT.

        If `False`, do not scale the CQT. This is analogous to `norm=None`
        in FFT.

    length : int > 0, optional
        If provided, the output `y` is zero-padded or clipped to exactly
        `length` samples.

    amin : float or None [DEPRECATED]

        .. note:: This parameter is deprecated in 0.7.0 and will be removed in 0.8.0.

    res_type : string
        Resampling mode.  By default, this uses `fft` mode for high-quality
        reconstruction, but this may be slow depending on your signal duration.
        See `librosa.resample` for supported modes.

    Returns
    -------
    y : np.ndarray, [shape=(n_samples), dtype=np.float]
        Audio time-series reconstructed from the CQT representation.

    See Also
    --------
    cqt
    core.resample

    Notes
    -----
    This function caches at level 40.

    Examples
    --------
    Using default parameters

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=15)
    >>> C = librosa.cqt(y=y, sr=sr)
    >>> y_hat = librosa.icqt(C=C, sr=sr)

    Or with a different hop length and frequency resolution:

    >>> hop_length = 256
    >>> bins_per_octave = 12 * 3
    >>> C = librosa.cqt(y=y, sr=sr, hop_length=256, n_bins=7*bins_per_octave,
    ...                 bins_per_octave=bins_per_octave)
    >>> y_hat = librosa.icqt(C=C, sr=sr, hop_length=hop_length,
    ...                 bins_per_octave=bins_per_octave)


@cache(level=<NUM_LIT:10>)<EOL>def __cqt_filter_fft(sr, fmin, n_bins, bins_per_octave, tuning,<EOL>filter_scale, norm, sparsity, hop_length=None,<EOL>window='<STR_LIT>'):

basis, lengths = filters.constant_q(sr,<EOL>fmin=fmin,<EOL>n_bins=n_bins,<EOL>bins_per_octave=bins_per_octave,<EOL>tuning=tuning,<EOL>filter_scale=filter_scale,<EOL>norm=norm,<EOL>pad_fft=True,<EOL>window=window)<EOL>n_fft = basis.shape[<NUM_LIT:1>]<EOL>if (hop_length is not None and<EOL>n_fft < <NUM_LIT>**(<NUM_LIT:1> + np.ceil(np.log2(hop_length)))):<EOL><INDENT>n_fft = int(<NUM_LIT> ** (<NUM_LIT:1> + np.ceil(np.log2(hop_length))))<EOL><DEDENT>basis *= lengths[:, np.newaxis] / float(n_fft)<EOL>fft = get_fftlib()<EOL>fft_basis = fft.fft(basis, n=n_fft, axis=<NUM_LIT:1>)[:, :(n_fft // <NUM_LIT:2>)+<NUM_LIT:1>]<EOL>fft_basis = util.sparsify_rows(fft_basis, quantile=sparsity)<EOL>return fft_basis, n_fft, lengths<EOL>

Generate the frequency domain constant-Q filter basis.


<EOL>max_col = min(x.shape[<NUM_LIT:1>] for x in cqt_resp)<EOL>cqt_resp = np.vstack([x[:, :max_col] for x in cqt_resp][::-<NUM_LIT:1>])<EOL>return np.ascontiguousarray(cqt_resp[-n_bins:].T).T<EOL>

Helper function to trim and stack a collection of CQT responses


def __cqt_response(y, n_fft, hop_length, fft_basis, mode):

<EOL>D = stft(y, n_fft=n_fft, hop_length=hop_length,<EOL>window='<STR_LIT>',<EOL>pad_mode=mode)<EOL>return fft_basis.dot(D)<EOL>

Compute the filter response with a target STFT hop.


def __early_downsample_count(nyquist, filter_cutoff, hop_length, n_octaves):

downsample_count1 = max(<NUM_LIT:0>, int(np.ceil(np.log2(audio.BW_FASTEST * nyquist /<EOL>filter_cutoff)) - <NUM_LIT:1>) - <NUM_LIT:1>)<EOL>num_twos = __num_two_factors(hop_length)<EOL>downsample_count2 = max(<NUM_LIT:0>, num_twos - n_octaves + <NUM_LIT:1>)<EOL>return min(downsample_count1, downsample_count2)<EOL>

Compute the number of early downsampling operations


def __early_downsample(y, sr, hop_length, res_type, n_octaves,<EOL>nyquist, filter_cutoff, scale):

downsample_count = __early_downsample_count(nyquist, filter_cutoff,<EOL>hop_length, n_octaves)<EOL>if downsample_count > <NUM_LIT:0> and res_type == '<STR_LIT>':<EOL><INDENT>downsample_factor = <NUM_LIT:2>**(downsample_count)<EOL>hop_length //= downsample_factor<EOL>if len(y) < downsample_factor:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(len(y), n_octaves))<EOL><DEDENT>new_sr = sr / float(downsample_factor)<EOL>y = audio.resample(y, sr, new_sr,<EOL>res_type=res_type,<EOL>scale=True)<EOL>if not scale:<EOL><INDENT>y *= np.sqrt(downsample_factor)<EOL><DEDENT>sr = new_sr<EOL><DEDENT>return y, sr, hop_length<EOL>

Perform early downsampling on an audio signal, if it applies.


if x <= <NUM_LIT:0>:<EOL><INDENT>return <NUM_LIT:0><EOL><DEDENT>num_twos = <NUM_LIT:0><EOL>while x % <NUM_LIT:2> == <NUM_LIT:0>:<EOL><INDENT>num_twos += <NUM_LIT:1><EOL>x //= <NUM_LIT:2><EOL><DEDENT>return num_twos<EOL>

Return how many times integer x can be evenly divided by 2.

    Returns 0 for non-positive integers.


def frames_to_samples(frames, hop_length=<NUM_LIT>, n_fft=None):

offset = <NUM_LIT:0><EOL>if n_fft is not None:<EOL><INDENT>offset = int(n_fft // <NUM_LIT:2>)<EOL><DEDENT>return (np.asanyarray(frames) * hop_length + offset).astype(int)<EOL>

Converts frame indices to audio sample indices.

    Parameters
    ----------
    frames     : number or np.ndarray [shape=(n,)]
        frame index or vector of frame indices

    hop_length : int > 0 [scalar]
        number of samples between successive frames

    n_fft : None or int > 0 [scalar]
        Optional: length of the FFT window.
        If given, time conversion will include an offset of `n_fft / 2`
        to counteract windowing effects when using a non-centered STFT.

    Returns
    -------
    times : number or np.ndarray
        time (in samples) of each given frame number:
        `times[i] = frames[i] * hop_length`

    See Also
    --------
    frames_to_time : convert frame indices to time values
    samples_to_frames : convert sample indices to frame indices

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> tempo, beats = librosa.beat.beat_track(y, sr=sr)
    >>> beat_samples = librosa.frames_to_samples(beats)


def samples_to_frames(samples, hop_length=<NUM_LIT>, n_fft=None):

offset = <NUM_LIT:0><EOL>if n_fft is not None:<EOL><INDENT>offset = int(n_fft // <NUM_LIT:2>)<EOL><DEDENT>samples = np.asanyarray(samples)<EOL>return np.floor((samples - offset) // hop_length).astype(int)<EOL>

Converts sample indices into STFT frames.

    Examples
    --------
    >>> # Get the frame numbers for every 256 samples
    >>> librosa.samples_to_frames(np.arange(0, 22050, 256))
    array([ 0,  0,  1,  1,  2,  2,  3,  3,  4,  4,  5,  5,  6,  6,
            7,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 13, 13,
           14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20,
           21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
           28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34,
           35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41,
           42, 42, 43])

    Parameters
    ----------
    samples : int or np.ndarray [shape=(n,)]
        sample index or vector of sample indices

    hop_length : int > 0 [scalar]
        number of samples between successive frames

    n_fft : None or int > 0 [scalar]
        Optional: length of the FFT window.
        If given, time conversion will include an offset of `- n_fft / 2`
        to counteract windowing effects in STFT.

        .. note:: This may result in negative frame indices.

    Returns
    -------
    frames : int or np.ndarray [shape=(n,), dtype=int]
        Frame numbers corresponding to the given times:
        `frames[i] = floor( samples[i] / hop_length )`

    See Also
    --------
    samples_to_time : convert sample indices to time values
    frames_to_samples : convert frame indices to sample indices


def frames_to_time(frames, sr=<NUM_LIT>, hop_length=<NUM_LIT>, n_fft=None):

samples = frames_to_samples(frames,<EOL>hop_length=hop_length,<EOL>n_fft=n_fft)<EOL>return samples_to_time(samples, sr=sr)<EOL>

Converts frame counts to time (seconds).

    Parameters
    ----------
    frames     : np.ndarray [shape=(n,)]
        frame index or vector of frame indices

    sr         : number > 0 [scalar]
        audio sampling rate

    hop_length : int > 0 [scalar]
        number of samples between successive frames

    n_fft : None or int > 0 [scalar]
        Optional: length of the FFT window.
        If given, time conversion will include an offset of `n_fft / 2`
        to counteract windowing effects when using a non-centered STFT.

    Returns
    -------
    times : np.ndarray [shape=(n,)]
        time (in seconds) of each given frame number:
        `times[i] = frames[i] * hop_length / sr`

    See Also
    --------
    time_to_frames : convert time values to frame indices
    frames_to_samples : convert frame indices to sample indices

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> tempo, beats = librosa.beat.beat_track(y, sr=sr)
    >>> beat_times = librosa.frames_to_time(beats, sr=sr)


def time_to_frames(times, sr=<NUM_LIT>, hop_length=<NUM_LIT>, n_fft=None):

samples = time_to_samples(times, sr=sr)<EOL>return samples_to_frames(samples, hop_length=hop_length, n_fft=n_fft)<EOL>

Converts time stamps into STFT frames.

    Parameters
    ----------
    times : np.ndarray [shape=(n,)]
        time (in seconds) or vector of time values

    sr : number > 0 [scalar]
        audio sampling rate

    hop_length : int > 0 [scalar]
        number of samples between successive frames

    n_fft : None or int > 0 [scalar]
        Optional: length of the FFT window.
        If given, time conversion will include an offset of `- n_fft / 2`
        to counteract windowing effects in STFT.

        .. note:: This may result in negative frame indices.

    Returns
    -------
    frames : np.ndarray [shape=(n,), dtype=int]
        Frame numbers corresponding to the given times:
        `frames[i] = floor( times[i] * sr / hop_length )`

    See Also
    --------
    frames_to_time : convert frame indices to time values
    time_to_samples : convert time values to sample indices

    Examples
    --------
    Get the frame numbers for every 100ms

    >>> librosa.time_to_frames(np.arange(0, 1, 0.1),
    ...                         sr=22050, hop_length=512)
    array([ 0,  4,  8, 12, 17, 21, 25, 30, 34, 38])


return (np.asanyarray(times) * sr).astype(int)<EOL>

Convert timestamps (in seconds) to sample indices.

    Parameters
    ----------
    times : number or np.ndarray
        Time value or array of time values (in seconds)

    sr : number > 0
        Sampling rate

    Returns
    -------
    samples : int or np.ndarray [shape=times.shape, dtype=int]
        Sample indices corresponding to values in `times`

    See Also
    --------
    time_to_frames : convert time values to frame indices
    samples_to_time : convert sample indices to time values

    Examples
    --------
    >>> librosa.time_to_samples(np.arange(0, 1, 0.1), sr=22050)
    array([    0,  2205,  4410,  6615,  8820, 11025, 13230, 15435,
           17640, 19845])


return np.asanyarray(samples) / float(sr)<EOL>

Convert sample indices to time (in seconds).

    Parameters
    ----------
    samples : np.ndarray
        Sample index or array of sample indices

    sr : number > 0
        Sampling rate

    Returns
    -------
    times : np.ndarray [shape=samples.shape, dtype=int]
        Time values corresponding to `samples` (in seconds)

    See Also
    --------
    samples_to_frames : convert sample indices to frame indices
    time_to_samples : convert time values to sample indices

    Examples
    --------
    Get timestamps corresponding to every 512 samples

    >>> librosa.samples_to_time(np.arange(0, 22050, 512))
    array([ 0.   ,  0.023,  0.046,  0.07 ,  0.093,  0.116,  0.139,
            0.163,  0.186,  0.209,  0.232,  0.255,  0.279,  0.302,
            0.325,  0.348,  0.372,  0.395,  0.418,  0.441,  0.464,
            0.488,  0.511,  0.534,  0.557,  0.58 ,  0.604,  0.627,
            0.65 ,  0.673,  0.697,  0.72 ,  0.743,  0.766,  0.789,
            0.813,  0.836,  0.859,  0.882,  0.906,  0.929,  0.952,
            0.975,  0.998])


return midi_to_hz(note_to_midi(note, **kwargs))<EOL>

Convert one or more note names to frequency (Hz)

    Examples
    --------
    >>> # Get the frequency of a note
    >>> librosa.note_to_hz('C')
    array([ 16.352])
    >>> # Or multiple notes
    >>> librosa.note_to_hz(['A3', 'A4', 'A5'])
    array([ 220.,  440.,  880.])
    >>> # Or notes with tuning deviations
    >>> librosa.note_to_hz('C2-32', round_midi=False)
    array([ 64.209])

    Parameters
    ----------
    note : str or iterable of str
        One or more note names to convert

    kwargs : additional keyword arguments
        Additional parameters to `note_to_midi`

    Returns
    -------
    frequencies : number or np.ndarray [shape=(len(note),)]
        Array of frequencies (in Hz) corresponding to `note`

    See Also
    --------
    midi_to_hz
    note_to_midi
    hz_to_note


if not isinstance(note, six.string_types):<EOL><INDENT>return np.array([note_to_midi(n, round_midi=round_midi) for n in note])<EOL><DEDENT>pitch_map = {'<STR_LIT:C>': <NUM_LIT:0>, '<STR_LIT:D>': <NUM_LIT:2>, '<STR_LIT:E>': <NUM_LIT:4>, '<STR_LIT:F>': <NUM_LIT:5>, '<STR_LIT>': <NUM_LIT:7>, '<STR_LIT:A>': <NUM_LIT:9>, '<STR_LIT:B>': <NUM_LIT:11>}<EOL>acc_map = {'<STR_LIT:#>': <NUM_LIT:1>, '<STR_LIT>': <NUM_LIT:0>, '<STR_LIT:b>': -<NUM_LIT:1>, '<STR_LIT:!>': -<NUM_LIT:1>}<EOL>match = re.match(r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>'<EOL>r'<STR_LIT>',<EOL>note)<EOL>if not match:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(note))<EOL><DEDENT>pitch = match.group('<STR_LIT>').upper()<EOL>offset = np.sum([acc_map[o] for o in match.group('<STR_LIT>')])<EOL>octave = match.group('<STR_LIT>')<EOL>cents = match.group('<STR_LIT>')<EOL>if not octave:<EOL><INDENT>octave = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>octave = int(octave)<EOL><DEDENT>if not cents:<EOL><INDENT>cents = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>cents = int(cents) * <NUM_LIT><EOL><DEDENT>note_value = <NUM_LIT:12> * (octave + <NUM_LIT:1>) + pitch_map[pitch] + offset + cents<EOL>if round_midi:<EOL><INDENT>note_value = int(np.round(note_value))<EOL><DEDENT>return note_value<EOL>

Convert one or more spelled notes to MIDI number(s).

    Notes may be spelled out with optional accidentals or octave numbers.

    The leading note name is case-insensitive.

    Sharps are indicated with ``#``, flats may be indicated with ``!`` or ``b``.

    Parameters
    ----------
    note : str or iterable of str
        One or more note names.

    round_midi : bool
        - If `True`, allow for fractional midi notes
        - Otherwise, round cent deviations to the nearest note

    Returns
    -------
    midi : float or np.array
        Midi note numbers corresponding to inputs.

    Raises
    ------
    ParameterError
        If the input is not in valid note format

    See Also
    --------
    midi_to_note
    note_to_hz

    Examples
    --------
    >>> librosa.note_to_midi('C')
    12
    >>> librosa.note_to_midi('C#3')
    49
    >>> librosa.note_to_midi('f4')
    65
    >>> librosa.note_to_midi('Bb-1')
    10
    >>> librosa.note_to_midi('A!8')
    116
    >>> # Lists of notes also work
    >>> librosa.note_to_midi(['C', 'E', 'G'])
    array([12, 16, 19])


def midi_to_note(midi, octave=True, cents=False):

if cents and not octave:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if not np.isscalar(midi):<EOL><INDENT>return [midi_to_note(x, octave=octave, cents=cents) for x in midi]<EOL><DEDENT>note_map = ['<STR_LIT:C>', '<STR_LIT>', '<STR_LIT:D>', '<STR_LIT>',<EOL>'<STR_LIT:E>', '<STR_LIT:F>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT:A>', '<STR_LIT>', '<STR_LIT:B>']<EOL>note_num = int(np.round(midi))<EOL>note_cents = int(<NUM_LIT:100> * np.around(midi - note_num, <NUM_LIT:2>))<EOL>note = note_map[note_num % <NUM_LIT:12>]<EOL>if octave:<EOL><INDENT>note = '<STR_LIT>'.format(note, int(note_num / <NUM_LIT:12>) - <NUM_LIT:1>)<EOL><DEDENT>if cents:<EOL><INDENT>note = '<STR_LIT>'.format(note, note_cents)<EOL><DEDENT>return note<EOL>

Convert one or more MIDI numbers to note strings.

    MIDI numbers will be rounded to the nearest integer.

    Notes will be of the format 'C0', 'C#0', 'D0', ...

    Examples
    --------
    >>> librosa.midi_to_note(0)
    'C-1'
    >>> librosa.midi_to_note(37)
    'C#2'
    >>> librosa.midi_to_note(-2)
    'A#-2'
    >>> librosa.midi_to_note(104.7)
    'A7'
    >>> librosa.midi_to_note(104.7, cents=True)
    'A7-30'
    >>> librosa.midi_to_note(list(range(12, 24)))
    ['C0', 'C#0', 'D0', 'D#0', 'E0', 'F0', 'F#0', 'G0', 'G#0', 'A0', 'A#0', 'B0']

    Parameters
    ----------
    midi : int or iterable of int
        Midi numbers to convert.

    octave: bool
        If True, include the octave number

    cents: bool
        If true, cent markers will be appended for fractional notes.
        Eg, `midi_to_note(69.3, cents=True)` == `A4+03`

    Returns
    -------
    notes : str or iterable of str
        Strings describing each midi note.

    Raises
    ------
    ParameterError
        if `cents` is True and `octave` is False

    See Also
    --------
    midi_to_hz
    note_to_midi
    hz_to_note


return <NUM_LIT> * (<NUM_LIT> ** ((np.asanyarray(notes) - <NUM_LIT>)/<NUM_LIT>))<EOL>

Get the frequency (Hz) of MIDI note(s)

    Examples
    --------
    >>> librosa.midi_to_hz(36)
    65.406

    >>> librosa.midi_to_hz(np.arange(36, 48))
    array([  65.406,   69.296,   73.416,   77.782,   82.407,
             87.307,   92.499,   97.999,  103.826,  110.   ,
            116.541,  123.471])

    Parameters
    ----------
    notes       : int or np.ndarray [shape=(n,), dtype=int]
        midi number(s) of the note(s)

    Returns
    -------
    frequency   : number or np.ndarray [shape=(n,), dtype=float]
        frequency (frequencies) of `notes` in Hz

    See Also
    --------
    hz_to_midi
    note_to_hz


return <NUM_LIT:12> * (np.log2(np.asanyarray(frequencies)) - np.log2(<NUM_LIT>)) + <NUM_LIT><EOL>

Get MIDI note number(s) for given frequencies

    Examples
    --------
    >>> librosa.hz_to_midi(60)
    34.506
    >>> librosa.hz_to_midi([110, 220, 440])
    array([ 45.,  57.,  69.])

    Parameters
    ----------
    frequencies   : float or np.ndarray [shape=(n,), dtype=float]
        frequencies to convert

    Returns
    -------
    note_nums     : number or np.ndarray [shape=(n,), dtype=float]
        MIDI notes to `frequencies`

    See Also
    --------
    midi_to_hz
    note_to_midi
    hz_to_note


return midi_to_note(hz_to_midi(frequencies), **kwargs)<EOL>

Convert one or more frequencies (in Hz) to the nearest note names.

    Parameters
    ----------
    frequencies : float or iterable of float
        Input frequencies, specified in Hz

    kwargs : additional keyword arguments
        Arguments passed through to `midi_to_note`

    Returns
    -------
    notes : list of str
        `notes[i]` is the closest note name to `frequency[i]`
        (or `frequency` if the input is scalar)

    See Also
    --------
    hz_to_midi
    midi_to_note
    note_to_hz

    Examples
    --------
    Get a single note name for a frequency

    >>> librosa.hz_to_note(440.0)
    ['A5']

    Get multiple notes with cent deviation

    >>> librosa.hz_to_note([32, 64], cents=True)
    ['C1-38', 'C2-38']

    Get multiple notes, but suppress octave labels

    >>> librosa.hz_to_note(440.0 * (2.0 ** np.linspace(0, 1, 12)),
    ...                    octave=False)
    ['A', 'A#', 'B', 'C', 'C#', 'D', 'E', 'F', 'F#', 'G', 'G#', 'A']


frequencies = np.asanyarray(frequencies)<EOL>if htk:<EOL><INDENT>return <NUM_LIT> * np.log10(<NUM_LIT:1.0> + frequencies / <NUM_LIT>)<EOL><DEDENT>f_min = <NUM_LIT:0.0><EOL>f_sp = <NUM_LIT> / <NUM_LIT:3><EOL>mels = (frequencies - f_min) / f_sp<EOL>min_log_hz = <NUM_LIT>                         <EOL>min_log_mel = (min_log_hz - f_min) / f_sp   <EOL>logstep = np.log(<NUM_LIT>) / <NUM_LIT>                <EOL>if frequencies.ndim:<EOL><INDENT>log_t = (frequencies >= min_log_hz)<EOL>mels[log_t] = min_log_mel + np.log(frequencies[log_t]/min_log_hz) / logstep<EOL><DEDENT>elif frequencies >= min_log_hz:<EOL><INDENT>mels = min_log_mel + np.log(frequencies / min_log_hz) / logstep<EOL><DEDENT>return mels<EOL>

Convert Hz to Mels

    Examples
    --------
    >>> librosa.hz_to_mel(60)
    0.9
    >>> librosa.hz_to_mel([110, 220, 440])
    array([ 1.65,  3.3 ,  6.6 ])

    Parameters
    ----------
    frequencies   : number or np.ndarray [shape=(n,)] , float
        scalar or array of frequencies
    htk           : bool
        use HTK formula instead of Slaney

    Returns
    -------
    mels        : number or np.ndarray [shape=(n,)]
        input frequencies in Mels

    See Also
    --------
    mel_to_hz


mels = np.asanyarray(mels)<EOL>if htk:<EOL><INDENT>return <NUM_LIT> * (<NUM_LIT>**(mels / <NUM_LIT>) - <NUM_LIT:1.0>)<EOL><DEDENT>f_min = <NUM_LIT:0.0><EOL>f_sp = <NUM_LIT> / <NUM_LIT:3><EOL>freqs = f_min + f_sp * mels<EOL>min_log_hz = <NUM_LIT>                         <EOL>min_log_mel = (min_log_hz - f_min) / f_sp   <EOL>logstep = np.log(<NUM_LIT>) / <NUM_LIT>                <EOL>if mels.ndim:<EOL><INDENT>log_t = (mels >= min_log_mel)<EOL>freqs[log_t] = min_log_hz * np.exp(logstep * (mels[log_t] - min_log_mel))<EOL><DEDENT>elif mels >= min_log_mel:<EOL><INDENT>freqs = min_log_hz * np.exp(logstep * (mels - min_log_mel))<EOL><DEDENT>return freqs<EOL>

Convert mel bin numbers to frequencies

    Examples
    --------
    >>> librosa.mel_to_hz(3)
    200.

    >>> librosa.mel_to_hz([1,2,3,4,5])
    array([  66.667,  133.333,  200.   ,  266.667,  333.333])

    Parameters
    ----------
    mels          : np.ndarray [shape=(n,)], float
        mel bins to convert
    htk           : bool
        use HTK formula instead of Slaney

    Returns
    -------
    frequencies   : np.ndarray [shape=(n,)]
        input mels in Hz

    See Also
    --------
    hz_to_mel


return np.log2(np.asanyarray(frequencies) / (float(A440) / <NUM_LIT:16>))<EOL>

Convert frequencies (Hz) to (fractional) octave numbers.

    Examples
    --------
    >>> librosa.hz_to_octs(440.0)
    4.
    >>> librosa.hz_to_octs([32, 64, 128, 256])
    array([ 0.219,  1.219,  2.219,  3.219])

    Parameters
    ----------
    frequencies   : number >0 or np.ndarray [shape=(n,)] or float
        scalar or vector of frequencies
    A440          : float
        frequency of A440 (in Hz)

    Returns
    -------
    octaves       : number or np.ndarray [shape=(n,)]
        octave number for each frequency

    See Also
    --------
    octs_to_hz


return (float(A440) / <NUM_LIT:16>)*(<NUM_LIT>**np.asanyarray(octs))<EOL>

Convert octaves numbers to frequencies.

    Octaves are counted relative to A.

    Examples
    --------
    >>> librosa.octs_to_hz(1)
    55.
    >>> librosa.octs_to_hz([-2, -1, 0, 1, 2])
    array([   6.875,   13.75 ,   27.5  ,   55.   ,  110.   ])

    Parameters
    ----------
    octaves       : np.ndarray [shape=(n,)] or float
        octave number for each frequency
    A440          : float
        frequency of A440

    Returns
    -------
    frequencies   : number or np.ndarray [shape=(n,)]
        scalar or vector of frequencies

    See Also
    --------
    hz_to_octs


return np.linspace(<NUM_LIT:0>,<EOL>float(sr) / <NUM_LIT:2>,<EOL>int(<NUM_LIT:1> + n_fft//<NUM_LIT:2>),<EOL>endpoint=True)<EOL>

Alternative implementation of `np.fft.fftfreq`

    Parameters
    ----------
    sr : number > 0 [scalar]
        Audio sampling rate

    n_fft : int > 0 [scalar]
        FFT window size

    Returns
    -------
    freqs : np.ndarray [shape=(1 + n_fft/2,)]
        Frequencies `(0, sr/n_fft, 2*sr/n_fft, ..., sr/2)`

    Examples
    --------
    >>> librosa.fft_frequencies(sr=22050, n_fft=16)
    array([     0.   ,   1378.125,   2756.25 ,   4134.375,
             5512.5  ,   6890.625,   8268.75 ,   9646.875,  11025.   ])


def cqt_frequencies(n_bins, fmin, bins_per_octave=<NUM_LIT:12>, tuning=<NUM_LIT:0.0>):

correction = <NUM_LIT>**(float(tuning) / bins_per_octave)<EOL>frequencies = <NUM_LIT>**(np.arange(<NUM_LIT:0>, n_bins, dtype=float) / bins_per_octave)<EOL>return correction * fmin * frequencies<EOL>

Compute the center frequencies of Constant-Q bins.

    Examples
    --------
    >>> # Get the CQT frequencies for 24 notes, starting at C2
    >>> librosa.cqt_frequencies(24, fmin=librosa.note_to_hz('C2'))
    array([  65.406,   69.296,   73.416,   77.782,   82.407,   87.307,
             92.499,   97.999,  103.826,  110.   ,  116.541,  123.471,
            130.813,  138.591,  146.832,  155.563,  164.814,  174.614,
            184.997,  195.998,  207.652,  220.   ,  233.082,  246.942])

    Parameters
    ----------
    n_bins  : int > 0 [scalar]
        Number of constant-Q bins

    fmin    : float > 0 [scalar]
        Minimum frequency

    bins_per_octave : int > 0 [scalar]
        Number of bins per octave

    tuning : float in `[-0.5, +0.5)`
        Deviation from A440 tuning in fractional bins (cents)

    Returns
    -------
    frequencies : np.ndarray [shape=(n_bins,)]
        Center frequency for each CQT bin