def mel_frequencies(n_mels=<NUM_LIT>, fmin=<NUM_LIT:0.0>, fmax=<NUM_LIT>, htk=False):

<EOL>min_mel = hz_to_mel(fmin, htk=htk)<EOL>max_mel = hz_to_mel(fmax, htk=htk)<EOL>mels = np.linspace(min_mel, max_mel, n_mels)<EOL>return mel_to_hz(mels, htk=htk)<EOL>

Compute an array of acoustic frequencies tuned to the mel scale.

    The mel scale is a quasi-logarithmic function of acoustic frequency
    designed such that perceptually similar pitch intervals (e.g. octaves)
    appear equal in width over the full hearing range.

    Because the definition of the mel scale is conditioned by a finite number
    of subjective psychoaoustical experiments, several implementations coexist
    in the audio signal processing literature [1]_. By default, librosa replicates
    the behavior of the well-established MATLAB Auditory Toolbox of Slaney [2]_.
    According to this default implementation,  the conversion from Hertz to mel is
    linear below 1 kHz and logarithmic above 1 kHz. Another available implementation
    replicates the Hidden Markov Toolkit [3]_ (HTK) according to the following formula:

    `mel = 2595.0 * np.log10(1.0 + f / 700.0).`

    The choice of implementation is determined by the `htk` keyword argument: setting
    `htk=False` leads to the Auditory toolbox implementation, whereas setting it `htk=True`
    leads to the HTK implementation.

    .. [1] Umesh, S., Cohen, L., & Nelson, D. Fitting the mel scale.
        In Proc. International Conference on Acoustics, Speech, and Signal Processing
        (ICASSP), vol. 1, pp. 217-220, 1998.

    .. [2] Slaney, M. Auditory Toolbox: A MATLAB Toolbox for Auditory
        Modeling Work. Technical Report, version 2, Interval Research Corporation, 1998.

    .. [3] Young, S., Evermann, G., Gales, M., Hain, T., Kershaw, D., Liu, X.,
        Moore, G., Odell, J., Ollason, D., Povey, D., Valtchev, V., & Woodland, P.
        The HTK book, version 3.4. Cambridge University, March 2009.

    See Also
    --------
    hz_to_mel
    mel_to_hz
    librosa.feature.melspectrogram
    librosa.feature.mfcc

    Parameters
    ----------
    n_mels    : int > 0 [scalar]
        Number of mel bins.

    fmin      : float >= 0 [scalar]
        Minimum frequency (Hz).

    fmax      : float >= 0 [scalar]
        Maximum frequency (Hz).

    htk       : bool
        If True, use HTK formula to convert Hz to mel.
        Otherwise (False), use Slaney's Auditory Toolbox.

    Returns
    -------
    bin_frequencies : ndarray [shape=(n_mels,)]
        Vector of n_mels frequencies in Hz which are uniformly spaced on the Mel
        axis.

    Examples
    --------
    >>> librosa.mel_frequencies(n_mels=40)
    array([     0.   ,     85.317,    170.635,    255.952,
              341.269,    426.586,    511.904,    597.221,
              682.538,    767.855,    853.173,    938.49 ,
             1024.856,   1119.114,   1222.042,   1334.436,
             1457.167,   1591.187,   1737.532,   1897.337,
             2071.84 ,   2262.393,   2470.47 ,   2697.686,
             2945.799,   3216.731,   3512.582,   3835.643,
             4188.417,   4573.636,   4994.285,   5453.621,
             5955.205,   6502.92 ,   7101.009,   7754.107,
             8467.272,   9246.028,  10096.408,  11025.   ])


def tempo_frequencies(n_bins, hop_length=<NUM_LIT>, sr=<NUM_LIT>):

bin_frequencies = np.zeros(int(n_bins), dtype=np.float)<EOL>bin_frequencies[<NUM_LIT:0>] = np.inf<EOL>bin_frequencies[<NUM_LIT:1>:] = <NUM_LIT> * sr / (hop_length * np.arange(<NUM_LIT:1.0>, n_bins))<EOL>return bin_frequencies<EOL>

Compute the frequencies (in beats-per-minute) corresponding
    to an onset auto-correlation or tempogram matrix.

    Parameters
    ----------
    n_bins : int > 0
        The number of lag bins

    hop_length : int > 0
        The number of samples between each bin

    sr : number > 0
        The audio sampling rate

    Returns
    -------
    bin_frequencies : ndarray [shape=(n_bins,)]
        vector of bin frequencies measured in BPM.

        .. note:: `bin_frequencies[0] = +np.inf` corresponds to 0-lag

    Examples
    --------
    Get the tempo frequencies corresponding to a 384-bin (8-second) tempogram

    >>> librosa.tempo_frequencies(384)
    array([      inf,  2583.984,  1291.992, ...,     6.782,
               6.764,     6.747])


<EOL>frequencies = np.asanyarray(frequencies)<EOL>f_sq = frequencies**<NUM_LIT><EOL>const = np.array([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>])**<NUM_LIT><EOL>weights = <NUM_LIT> + <NUM_LIT> * (np.log10(const[<NUM_LIT:0>]) + <NUM_LIT:4> * np.log10(frequencies)<EOL>- np.log10(f_sq + const[<NUM_LIT:0>])<EOL>- np.log10(f_sq + const[<NUM_LIT:1>])<EOL>- <NUM_LIT:0.5> * np.log10(f_sq + const[<NUM_LIT:2>])<EOL>- <NUM_LIT:0.5> * np.log10(f_sq + const[<NUM_LIT:3>]))<EOL>if min_db is not None:<EOL><INDENT>weights = np.maximum(min_db, weights)<EOL><DEDENT>return weights<EOL>

Compute the A-weighting of a set of frequencies.

    Parameters
    ----------
    frequencies : scalar or np.ndarray [shape=(n,)]
        One or more frequencies (in Hz)

    min_db : float [scalar] or None
        Clip weights below this threshold.
        If `None`, no clipping is performed.

    Returns
    -------
    A_weighting : scalar or np.ndarray [shape=(n,)]
        `A_weighting[i]` is the A-weighting of `frequencies[i]`

    See Also
    --------
    perceptual_weighting

    Examples
    --------

    Get the A-weighting for CQT frequencies

    >>> import matplotlib.pyplot as plt
    >>> freqs = librosa.cqt_frequencies(108, librosa.note_to_hz('C1'))
    >>> aw = librosa.A_weighting(freqs)
    >>> plt.plot(freqs, aw)
    >>> plt.xlabel('Frequency (Hz)')
    >>> plt.ylabel('Weighting (log10)')
    >>> plt.title('A-Weighting of CQT frequencies')


def times_like(X, sr=<NUM_LIT>, hop_length=<NUM_LIT>, n_fft=None, axis=-<NUM_LIT:1>):

samples = samples_like(X, hop_length=hop_length, n_fft=n_fft, axis=axis)<EOL>return samples_to_time(samples, sr=sr)<EOL>

Return an array of time values to match the time axis from a feature matrix.

    Parameters
    ----------
    X : np.ndarray or scalar
        - If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram.
        - If scalar, X represents the number of frames.

    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.

    axis : int [scalar]
        The axis representing the time axis of X.
        By default, the last axis (-1) is taken.

    Returns
    -------
    times : np.ndarray [shape=(n,)]
        ndarray of times (in seconds) corresponding to each frame of X.

    See Also
    --------
    samples_like : Return an array of sample indices to match the time axis from a feature matrix.

    Examples
    --------
    Provide a feature matrix input:

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> X = librosa.stft(y)
    >>> times = librosa.times_like(X)
    >>> times
    array([  0.00000000e+00,   2.32199546e-02,   4.64399093e-02, ...,
             6.13935601e+01,   6.14167800e+01,   6.14400000e+01])

    Provide a scalar input:

    >>> n_frames = 2647
    >>> times = librosa.times_like(n_frames)
    >>> times
    array([  0.00000000e+00,   2.32199546e-02,   4.64399093e-02, ...,
             6.13935601e+01,   6.14167800e+01,   6.14400000e+01])


def samples_like(X, hop_length=<NUM_LIT>, n_fft=None, axis=-<NUM_LIT:1>):

if np.isscalar(X):<EOL><INDENT>frames = np.arange(X)<EOL><DEDENT>else:<EOL><INDENT>frames = np.arange(X.shape[axis])<EOL><DEDENT>return frames_to_samples(frames, hop_length=hop_length, n_fft=n_fft)<EOL>

Return an array of sample indices to match the time axis from a feature matrix.

    Parameters
    ----------
    X : np.ndarray or scalar
        - If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram.
        - If scalar, X represents the number of frames.

    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.

    axis : int [scalar]
        The axis representing the time axis of X.
        By default, the last axis (-1) is taken.

    Returns
    -------
    samples : np.ndarray [shape=(n,)]
        ndarray of sample indices corresponding to each frame of X.

    See Also
    --------
    times_like : Return an array of time values to match the time axis from a feature matrix.

    Examples
    --------
    Provide a feature matrix input:

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> X = librosa.stft(y)
    >>> samples = librosa.samples_like(X)
    >>> samples
    array([      0,     512,    1024, ..., 1353728, 1354240, 1354752])

    Provide a scalar input:

    >>> n_frames = 2647
    >>> samples = librosa.samples_like(n_frames)
    >>> samples
    array([      0,     512,    1024, ..., 1353728, 1354240, 1354752])


@cache(level=<NUM_LIT:20>)<EOL>def stft(y, n_fft=<NUM_LIT>, hop_length=None, win_length=None, window='<STR_LIT>',<EOL>center=True, dtype=np.complex64, pad_mode='<STR_LIT>'):

<EOL>if win_length is None:<EOL><INDENT>win_length = n_fft<EOL><DEDENT>if hop_length is None:<EOL><INDENT>hop_length = int(win_length // <NUM_LIT:4>)<EOL><DEDENT>fft_window = get_window(window, win_length, fftbins=True)<EOL>fft_window = util.pad_center(fft_window, n_fft)<EOL>fft_window = fft_window.reshape((-<NUM_LIT:1>, <NUM_LIT:1>))<EOL>util.valid_audio(y)<EOL>if center:<EOL><INDENT>y = np.pad(y, int(n_fft // <NUM_LIT:2>), mode=pad_mode)<EOL><DEDENT>y_frames = util.frame(y, frame_length=n_fft, hop_length=hop_length)<EOL>stft_matrix = np.empty((int(<NUM_LIT:1> + n_fft // <NUM_LIT:2>), y_frames.shape[<NUM_LIT:1>]),<EOL>dtype=dtype,<EOL>order='<STR_LIT:F>')<EOL>fft = get_fftlib()<EOL>n_columns = int(util.MAX_MEM_BLOCK / (stft_matrix.shape[<NUM_LIT:0>] *<EOL>stft_matrix.itemsize))<EOL>for bl_s in range(<NUM_LIT:0>, stft_matrix.shape[<NUM_LIT:1>], n_columns):<EOL><INDENT>bl_t = min(bl_s + n_columns, stft_matrix.shape[<NUM_LIT:1>])<EOL>stft_matrix[:, bl_s:bl_t] = fft.rfft(fft_window *<EOL>y_frames[:, bl_s:bl_t],<EOL>axis=<NUM_LIT:0>)<EOL><DEDENT>return stft_matrix<EOL>

Short-time Fourier transform (STFT)

    Returns a complex-valued matrix D such that
        `np.abs(D[f, t])` is the magnitude of frequency bin `f`
        at frame `t`

        `np.angle(D[f, t])` is the phase of frequency bin `f`
        at frame `t`

    Parameters
    ----------
    y : np.ndarray [shape=(n,)], real-valued
        the input signal (audio time series)

    n_fft : int > 0 [scalar]
        FFT window size

    hop_length : int > 0 [scalar]
        number audio of frames between STFT columns.
        If unspecified, defaults `win_length / 4`.

    win_length : int <= n_fft [scalar]
        Each frame of audio is windowed by `window()`.
        The window will be of length `win_length` and then padded
        with zeros to match `n_fft`.

        If unspecified, defaults to ``win_length = n_fft``.

    window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)]
        - a window specification (string, tuple, or number);
          see `scipy.signal.get_window`
        - a window function, such as `scipy.signal.hanning`
        - a vector or array of length `n_fft`

        .. see also:: `filters.get_window`

    center : boolean
        - If `True`, the signal `y` is padded so that frame
          `D[:, t]` is centered at `y[t * hop_length]`.
        - If `False`, then `D[:, t]` begins at `y[t * hop_length]`

    dtype : numeric type
        Complex numeric type for `D`.  Default is 64-bit complex.

    pad_mode : string
        If `center=True`, the padding mode to use at the edges of the signal.
        By default, STFT uses reflection padding.

    Returns
    -------
    D : np.ndarray [shape=(1 + n_fft/2, t), dtype=dtype]
        STFT matrix

    See Also
    --------
    istft : Inverse STFT

    ifgram : Instantaneous frequency spectrogram

    np.pad : array padding

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

    Examples
    --------

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> D = np.abs(librosa.stft(y))
    >>> D
    array([[2.58028018e-03, 4.32422794e-02, 6.61255598e-01, ...,
            6.82710262e-04, 2.51654536e-04, 7.23036574e-05],
           [2.49403086e-03, 5.15930466e-02, 6.00107312e-01, ...,
            3.48026224e-04, 2.35853557e-04, 7.54836728e-05],
           [7.82410789e-04, 1.05394892e-01, 4.37517226e-01, ...,
            6.29352580e-04, 3.38571583e-04, 8.38094638e-05],
           ...,
           [9.48568513e-08, 4.74725084e-07, 1.50052492e-05, ...,
            1.85637656e-08, 2.89708542e-08, 5.74304337e-09],
           [1.25165826e-07, 8.58259284e-07, 1.11157215e-05, ...,
            3.49099771e-08, 3.11740926e-08, 5.29926236e-09],
           [1.70630571e-07, 8.92518756e-07, 1.23656537e-05, ...,
            5.33256745e-08, 3.33264900e-08, 5.13272980e-09]], dtype=float32)

    Use left-aligned frames, instead of centered frames

    >>> D_left = np.abs(librosa.stft(y, center=False))

    Use a shorter hop length

    >>> D_short = np.abs(librosa.stft(y, hop_length=64))

    Display a spectrogram

    >>> import matplotlib.pyplot as plt
    >>> librosa.display.specshow(librosa.amplitude_to_db(D,
    ...                                                  ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.title('Power spectrogram')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.tight_layout()


@cache(level=<NUM_LIT:30>)<EOL>def istft(stft_matrix, hop_length=None, win_length=None, window='<STR_LIT>',<EOL>center=True, dtype=np.float32, length=None):

n_fft = <NUM_LIT:2> * (stft_matrix.shape[<NUM_LIT:0>] - <NUM_LIT:1>)<EOL>if win_length is None:<EOL><INDENT>win_length = n_fft<EOL><DEDENT>if hop_length is None:<EOL><INDENT>hop_length = int(win_length // <NUM_LIT:4>)<EOL><DEDENT>ifft_window = get_window(window, win_length, fftbins=True)<EOL>ifft_window = util.pad_center(ifft_window, n_fft)[:, np.newaxis]<EOL>n_frames = stft_matrix.shape[<NUM_LIT:1>]<EOL>expected_signal_len = n_fft + hop_length * (n_frames - <NUM_LIT:1>)<EOL>y = np.zeros(expected_signal_len, dtype=dtype)<EOL>n_columns = int(util.MAX_MEM_BLOCK // (stft_matrix.shape[<NUM_LIT:0>] *<EOL>stft_matrix.itemsize))<EOL>fft = get_fftlib()<EOL>frame = <NUM_LIT:0><EOL>for bl_s in range(<NUM_LIT:0>, n_frames, n_columns):<EOL><INDENT>bl_t = min(bl_s + n_columns, n_frames)<EOL>ytmp = ifft_window * fft.irfft(stft_matrix[:, bl_s:bl_t], axis=<NUM_LIT:0>)<EOL>__overlap_add(y[frame * hop_length:], ytmp, hop_length)<EOL>frame += (bl_t - bl_s)<EOL><DEDENT>ifft_window_sum = window_sumsquare(window,<EOL>n_frames,<EOL>win_length=win_length,<EOL>n_fft=n_fft,<EOL>hop_length=hop_length,<EOL>dtype=dtype)<EOL>approx_nonzero_indices = ifft_window_sum > util.tiny(ifft_window_sum)<EOL>y[approx_nonzero_indices] /= ifft_window_sum[approx_nonzero_indices]<EOL>if length is None:<EOL><INDENT>if center:<EOL><INDENT>y = y[int(n_fft // <NUM_LIT:2>):-int(n_fft // <NUM_LIT:2>)]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if center:<EOL><INDENT>start = int(n_fft // <NUM_LIT:2>)<EOL><DEDENT>else:<EOL><INDENT>start = <NUM_LIT:0><EOL><DEDENT>y = util.fix_length(y[start:], length)<EOL><DEDENT>return y<EOL>

Inverse short-time Fourier transform (ISTFT).

Converts a complex-valued spectrogram `stft_matrix` to time-series `y`
by minimizing the mean squared error between `stft_matrix` and STFT of
`y` as described in [1]_ up to Section 2 (reconstruction from MSTFT).

In general, window function, hop length and other parameters should be same
as in stft, which mostly leads to perfect reconstruction of a signal from
unmodified `stft_matrix`.

.. [1] D. W. Griffin and J. S. Lim,
    "Signal estimation from modified short-time Fourier transform,"
    IEEE Trans. ASSP, vol.32, no.2, pp.236–243, Apr. 1984.

Parameters
----------
stft_matrix : np.ndarray [shape=(1 + n_fft/2, t)]
    STFT matrix from `stft`

hop_length : int > 0 [scalar]
    Number of frames between STFT columns.
    If unspecified, defaults to `win_length / 4`.

win_length : int <= n_fft = 2 * (stft_matrix.shape[0] - 1)
    When reconstructing the time series, each frame is windowed
    and each sample is normalized by the sum of squared window
    according to the `window` function (see below).

    If unspecified, defaults to `n_fft`.

window : string, tuple, number, function, np.ndarray [shape=(n_fft,)]
    - a window specification (string, tuple, or number);
      see `scipy.signal.get_window`
    - a window function, such as `scipy.signal.hanning`
    - a user-specified window vector of length `n_fft`

    .. see also:: `filters.get_window`

center : boolean
    - If `True`, `D` is assumed to have centered frames.
    - If `False`, `D` is assumed to have left-aligned frames.

dtype : numeric type
    Real numeric type for `y`.  Default is 32-bit float.

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

Returns
-------
y : np.ndarray [shape=(n,)]
    time domain signal reconstructed from `stft_matrix`

See Also
--------
stft : Short-time Fourier Transform

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

Examples
--------
>>> y, sr = librosa.load(librosa.util.example_audio_file())
>>> D = librosa.stft(y)
>>> y_hat = librosa.istft(D)
>>> y_hat
array([ -4.812e-06,  -4.267e-06, ...,   6.271e-06,   2.827e-07], dtype=float32)

Exactly preserving length of the input signal requires explicit padding.
Otherwise, a partial frame at the end of `y` will not be represented.

>>> n = len(y)
>>> n_fft = 2048
>>> y_pad = librosa.util.fix_length(y, n + n_fft // 2)
>>> D = librosa.stft(y_pad, n_fft=n_fft)
>>> y_out = librosa.istft(D, length=n)
>>> np.max(np.abs(y - y_out))
1.4901161e-07


def ifgram(y, sr=<NUM_LIT>, n_fft=<NUM_LIT>, hop_length=None, win_length=None,<EOL>window='<STR_LIT>', norm=False, center=True, ref_power=<NUM_LIT>,<EOL>clip=True, dtype=np.complex64, pad_mode='<STR_LIT>'):

if win_length is None:<EOL><INDENT>win_length = n_fft<EOL><DEDENT>if hop_length is None:<EOL><INDENT>hop_length = int(win_length // <NUM_LIT:4>)<EOL><DEDENT>fft_window = util.pad_center(get_window(window, win_length,<EOL>fftbins=True),<EOL>n_fft)<EOL>freq_angular = np.linspace(<NUM_LIT:0>, <NUM_LIT:2> * np.pi, n_fft, endpoint=False)<EOL>d_window = np.sin(-freq_angular) * np.pi / n_fft<EOL>stft_matrix = stft(y, n_fft=n_fft, hop_length=hop_length,<EOL>win_length=win_length,<EOL>window=window, center=center,<EOL>dtype=dtype, pad_mode=pad_mode)<EOL>diff_stft = stft(y, n_fft=n_fft, hop_length=hop_length,<EOL>window=d_window, center=center,<EOL>dtype=dtype, pad_mode=pad_mode).conj()<EOL>mag, phase = magphase(stft_matrix)<EOL>if six.callable(ref_power):<EOL><INDENT>ref_power = ref_power(mag**<NUM_LIT:2>)<EOL><DEDENT>elif ref_power < <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>freq_angular = freq_angular.reshape((-<NUM_LIT:1>, <NUM_LIT:1>))<EOL>bin_offset = (-phase * diff_stft).imag / mag<EOL>bin_offset[mag < ref_power**<NUM_LIT:0.5>] = <NUM_LIT:0><EOL>if_gram = freq_angular[:n_fft//<NUM_LIT:2> + <NUM_LIT:1>] + bin_offset<EOL>if norm:<EOL><INDENT>stft_matrix = stft_matrix * <NUM_LIT> / fft_window.sum()<EOL><DEDENT>if clip:<EOL><INDENT>np.clip(if_gram, <NUM_LIT:0>, np.pi, out=if_gram)<EOL><DEDENT>if_gram *= float(sr) * <NUM_LIT:0.5> / np.pi<EOL>return if_gram, stft_matrix<EOL>

Compute the instantaneous frequency (as a proportion of the sampling rate)
    obtained as the time-derivative of the phase of the complex spectrum as
    described by [1]_.

    Calculates regular STFT as a side effect.

    .. [1] Abe, Toshihiko, Takao Kobayashi, and Satoshi Imai.
        "Harmonics tracking and pitch extraction based on instantaneous
        frequency."
        International Conference on Acoustics, Speech, and Signal Processing,
        ICASSP-95., Vol. 1. IEEE, 1995.

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

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

    n_fft : int > 0 [scalar]
        FFT window size

    hop_length : int > 0 [scalar]
        hop length, number samples between subsequent frames.
        If not supplied, defaults to `win_length / 4`.

    win_length : int > 0, <= n_fft
        Window length. Defaults to `n_fft`.
        See `stft` for details.

    window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)]
        - a window specification (string, tuple, number);
          see `scipy.signal.get_window`
        - a window function, such as `scipy.signal.hanning`
        - a user-specified window vector of length `n_fft`

        See `stft` for details.

        .. see also:: `filters.get_window`

    norm : bool
        Normalize the STFT.

    center : boolean
        - If `True`, the signal `y` is padded so that frame
            `D[:, t]` (and `if_gram`) is centered at `y[t * hop_length]`.
        - If `False`, then `D[:, t]` at `y[t * hop_length]`

    ref_power : float >= 0 or callable
        Minimum power threshold for estimating instantaneous frequency.
        Any bin with `np.abs(D[f, t])**2 < ref_power` will receive the
        default frequency estimate.

        If callable, the threshold is set to `ref_power(np.abs(D)**2)`.

    clip : boolean
        - If `True`, clip estimated frequencies to the range `[0, 0.5 * sr]`.
        - If `False`, estimated frequencies can be negative or exceed
          `0.5 * sr`.

    dtype : numeric type
        Complex numeric type for `D`.  Default is 64-bit complex.

    pad_mode : string
        If `center=True`, the padding mode to use at the edges of the signal.
        By default, STFT uses reflection padding.

    Returns
    -------
    if_gram : np.ndarray [shape=(1 + n_fft/2, t), dtype=real]
        Instantaneous frequency spectrogram:
        `if_gram[f, t]` is the frequency at bin `f`, time `t`

    D : np.ndarray [shape=(1 + n_fft/2, t), dtype=complex]
        Short-time Fourier transform

    See Also
    --------
    stft : Short-time Fourier Transform

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> frequencies, D = librosa.ifgram(y, sr=sr)
    >>> frequencies
    array([[  0.000e+00,   0.000e+00, ...,   0.000e+00,   0.000e+00],
           [  3.150e+01,   3.070e+01, ...,   1.077e+01,   1.077e+01],
           ...,
           [  1.101e+04,   1.101e+04, ...,   1.101e+04,   1.101e+04],
           [  1.102e+04,   1.102e+04, ...,   1.102e+04,   1.102e+04]])


mag = np.abs(D)<EOL>mag **= power<EOL>phase = np.exp(<NUM_LIT> * np.angle(D))<EOL>return mag, phase<EOL>


def phase_vocoder(D, rate, hop_length=None):

n_fft = <NUM_LIT:2> * (D.shape[<NUM_LIT:0>] - <NUM_LIT:1>)<EOL>if hop_length is None:<EOL><INDENT>hop_length = int(n_fft // <NUM_LIT:4>)<EOL><DEDENT>time_steps = np.arange(<NUM_LIT:0>, D.shape[<NUM_LIT:1>], rate, dtype=np.float)<EOL>d_stretch = np.zeros((D.shape[<NUM_LIT:0>], len(time_steps)), D.dtype, order='<STR_LIT:F>')<EOL>phi_advance = np.linspace(<NUM_LIT:0>, np.pi * hop_length, D.shape[<NUM_LIT:0>])<EOL>phase_acc = np.angle(D[:, <NUM_LIT:0>])<EOL>D = np.pad(D, [(<NUM_LIT:0>, <NUM_LIT:0>), (<NUM_LIT:0>, <NUM_LIT:2>)], mode='<STR_LIT>')<EOL>for (t, step) in enumerate(time_steps):<EOL><INDENT>columns = D[:, int(step):int(step + <NUM_LIT:2>)]<EOL>alpha = np.mod(step, <NUM_LIT:1.0>)<EOL>mag = ((<NUM_LIT:1.0> - alpha) * np.abs(columns[:, <NUM_LIT:0>])<EOL>+ alpha * np.abs(columns[:, <NUM_LIT:1>]))<EOL>d_stretch[:, t] = mag * np.exp(<NUM_LIT> * phase_acc)<EOL>dphase = (np.angle(columns[:, <NUM_LIT:1>])<EOL>- np.angle(columns[:, <NUM_LIT:0>])<EOL>- phi_advance)<EOL>dphase = dphase - <NUM_LIT> * np.pi * np.round(dphase / (<NUM_LIT> * np.pi))<EOL>phase_acc += phi_advance + dphase<EOL><DEDENT>return d_stretch<EOL>

Phase vocoder.  Given an STFT matrix D, speed up by a factor of `rate`

    Based on the implementation provided by [1]_.

    .. [1] Ellis, D. P. W. "A phase vocoder in Matlab."
        Columbia University, 2002.
        http://www.ee.columbia.edu/~dpwe/resources/matlab/pvoc/

    Examples
    --------
    >>> # Play at double speed
    >>> y, sr   = librosa.load(librosa.util.example_audio_file())
    >>> D       = librosa.stft(y, n_fft=2048, hop_length=512)
    >>> D_fast  = librosa.phase_vocoder(D, 2.0, hop_length=512)
    >>> y_fast  = librosa.istft(D_fast, hop_length=512)

    >>> # Or play at 1/3 speed
    >>> y, sr   = librosa.load(librosa.util.example_audio_file())
    >>> D       = librosa.stft(y, n_fft=2048, hop_length=512)
    >>> D_slow  = librosa.phase_vocoder(D, 1./3, hop_length=512)
    >>> y_slow  = librosa.istft(D_slow, hop_length=512)

    Parameters
    ----------
    D : np.ndarray [shape=(d, t), dtype=complex]
        STFT matrix

    rate :  float > 0 [scalar]
        Speed-up factor: `rate > 1` is faster, `rate < 1` is slower.

    hop_length : int > 0 [scalar] or None
        The number of samples between successive columns of `D`.

        If None, defaults to `n_fft/4 = (D.shape[0]-1)/2`

    Returns
    -------
    D_stretched : np.ndarray [shape=(d, t / rate), dtype=complex]
        time-stretched STFT


@cache(level=<NUM_LIT:20>)<EOL>def iirt(y, sr=<NUM_LIT>, win_length=<NUM_LIT>, hop_length=None, center=True,<EOL>tuning=<NUM_LIT:0.0>, pad_mode='<STR_LIT>', flayout=None, **kwargs):

if flayout is None:<EOL><INDENT>warnings.warn('<STR_LIT>',<EOL>FutureWarning)<EOL>flayout = '<STR_LIT>'<EOL><DEDENT>elif flayout not in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(flayout))<EOL><DEDENT>util.valid_audio(y)<EOL>if hop_length is None:<EOL><INDENT>hop_length = int(win_length // <NUM_LIT:4>)<EOL><DEDENT>if center:<EOL><INDENT>y = np.pad(y, int(hop_length), mode=pad_mode)<EOL><DEDENT>filterbank_ct, sample_rates = semitone_filterbank(tuning=tuning, flayout=flayout, **kwargs)<EOL>y_resampled = []<EOL>y_srs = np.unique(sample_rates)<EOL>for cur_sr in y_srs:<EOL><INDENT>y_resampled.append(resample(y, sr, cur_sr))<EOL><DEDENT>n_frames = <NUM_LIT:1> + int((len(y) - win_length) / float(hop_length))<EOL>bands_power = []<EOL>for cur_sr, cur_filter in zip(sample_rates, filterbank_ct):<EOL><INDENT>factor = float(sr) / float(cur_sr)<EOL>win_length_STMSP = int(np.round(win_length / factor))<EOL>hop_length_STMSP = int(np.round(hop_length / factor))<EOL>cur_sr_idx = np.flatnonzero(y_srs == cur_sr)[<NUM_LIT:0>]<EOL>if flayout == '<STR_LIT>':<EOL><INDENT>cur_filter_output = scipy.signal.filtfilt(cur_filter[<NUM_LIT:0>], cur_filter[<NUM_LIT:1>],<EOL>y_resampled[cur_sr_idx])<EOL><DEDENT>elif flayout == '<STR_LIT>':<EOL><INDENT>cur_filter_output = scipy.signal.sosfiltfilt(cur_filter,<EOL>y_resampled[cur_sr_idx])<EOL><DEDENT>cur_frames = util.frame(np.ascontiguousarray(cur_filter_output),<EOL>frame_length=win_length_STMSP,<EOL>hop_length=hop_length_STMSP)<EOL>bands_power.append(factor * np.sum(cur_frames**<NUM_LIT:2>, axis=<NUM_LIT:0>)[:n_frames])<EOL><DEDENT>return np.asarray(bands_power)<EOL>

r'''Time-frequency representation using IIR filters [1]_.

    This function will return a time-frequency representation
    using a multirate filter bank consisting of IIR filters.
    First, `y` is resampled as needed according to the provided `sample_rates`.
    Then, a filterbank with with `n` band-pass filters is designed.
    The resampled input signals are processed by the filterbank as a whole.
    (`scipy.signal.filtfilt` resp. `sosfiltfilt` is used to make the phase linear.)
    The output of the filterbank is cut into frames.
    For each band, the short-time mean-square power (STMSP) is calculated by
    summing `win_length` subsequent filtered time samples.

    When called with the default set of parameters, it will generate the TF-representation
    as described in [1]_ (pitch filterbank):

        * 85 filters with MIDI pitches [24, 108] as `center_freqs`.
        * each filter having a bandwith of one semitone.

    .. [1] Müller, Meinard.
           "Information Retrieval for Music and Motion."
           Springer Verlag. 2007.

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

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

    win_length : int > 0, <= n_fft
        Window length.

    hop_length : int > 0 [scalar]
        Hop length, number samples between subsequent frames.
        If not supplied, defaults to `win_length / 4`.

    center : boolean
        - If `True`, the signal `y` is padded so that frame
          `D[:, t]` is centered at `y[t * hop_length]`.
        - If `False`, then `D[:, t]` begins at `y[t * hop_length]`

    tuning : float in `[-0.5, +0.5)` [scalar]
        Tuning deviation from A440 in fractions of a bin.

    pad_mode : string
        If `center=True`, the padding mode to use at the edges of the signal.
        By default, this function uses reflection padding.

    flayout : string
        - If `ba`, the standard difference equation is used for filtering with `scipy.signal.filtfilt`.
          Can be unstable for high-order filters.
        - If `sos`, a series of second-order filters is used for filtering with `scipy.signal.sosfiltfilt`.
          Minimizes numerical precision errors for high-order filters, but is slower.

    kwargs : additional keyword arguments
        Additional arguments for `librosa.filters.semitone_filterbank()`
        (e.g., could be used to provide another set of `center_freqs` and `sample_rates`).

    Returns
    -------
    bands_power : np.ndarray [shape=(n, t), dtype=dtype]
        Short-time mean-square power for the input signal.

    Raises
    ------
    ParameterError
        If `flayout` is not None, `ba`, or `sos`.

    See Also
    --------
    librosa.filters.semitone_filterbank
    librosa.filters._multirate_fb
    librosa.filters.mr_frequencies
    librosa.core.cqt
    scipy.signal.filtfilt
    scipy.signal.sosfiltfilt

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> D = np.abs(librosa.iirt(y))
    >>> librosa.display.specshow(librosa.amplitude_to_db(D, ref=np.max),
    ...                          y_axis='cqt_hz', x_axis='time')
    >>> plt.title('Semitone spectrogram')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.tight_layout()


@cache(level=<NUM_LIT:30>)<EOL>def power_to_db(S, ref=<NUM_LIT:1.0>, amin=<NUM_LIT>, top_db=<NUM_LIT>):

S = np.asarray(S)<EOL>if amin <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if np.issubdtype(S.dtype, np.complexfloating):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>magnitude = np.abs(S)<EOL><DEDENT>else:<EOL><INDENT>magnitude = S<EOL><DEDENT>if six.callable(ref):<EOL><INDENT>ref_value = ref(magnitude)<EOL><DEDENT>else:<EOL><INDENT>ref_value = np.abs(ref)<EOL><DEDENT>log_spec = <NUM_LIT> * np.log10(np.maximum(amin, magnitude))<EOL>log_spec -= <NUM_LIT> * np.log10(np.maximum(amin, ref_value))<EOL>if top_db is not None:<EOL><INDENT>if top_db < <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>log_spec = np.maximum(log_spec, log_spec.max() - top_db)<EOL><DEDENT>return log_spec<EOL>

Convert a power spectrogram (amplitude squared) to decibel (dB) units

    This computes the scaling ``10 * log10(S / ref)`` in a numerically
    stable way.

    Parameters
    ----------
    S : np.ndarray
        input power

    ref : scalar or callable
        If scalar, the amplitude `abs(S)` is scaled relative to `ref`:
        `10 * log10(S / ref)`.
        Zeros in the output correspond to positions where `S == ref`.

        If callable, the reference value is computed as `ref(S)`.

    amin : float > 0 [scalar]
        minimum threshold for `abs(S)` and `ref`

    top_db : float >= 0 [scalar]
        threshold the output at `top_db` below the peak:
        ``max(10 * log10(S)) - top_db``

    Returns
    -------
    S_db : np.ndarray
        ``S_db ~= 10 * log10(S) - 10 * log10(ref)``

    See Also
    --------
    perceptual_weighting
    db_to_power
    amplitude_to_db
    db_to_amplitude

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

    Examples
    --------
    Get a power spectrogram from a waveform ``y``

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> S = np.abs(librosa.stft(y))
    >>> librosa.power_to_db(S**2)
    array([[-33.293, -27.32 , ..., -33.293, -33.293],
           [-33.293, -25.723, ..., -33.293, -33.293],
           ...,
           [-33.293, -33.293, ..., -33.293, -33.293],
           [-33.293, -33.293, ..., -33.293, -33.293]], dtype=float32)

    Compute dB relative to peak power

    >>> librosa.power_to_db(S**2, ref=np.max)
    array([[-80.   , -74.027, ..., -80.   , -80.   ],
           [-80.   , -72.431, ..., -80.   , -80.   ],
           ...,
           [-80.   , -80.   , ..., -80.   , -80.   ],
           [-80.   , -80.   , ..., -80.   , -80.   ]], dtype=float32)

    Or compare to median power

    >>> librosa.power_to_db(S**2, ref=np.median)
    array([[-0.189,  5.784, ..., -0.189, -0.189],
           [-0.189,  7.381, ..., -0.189, -0.189],
           ...,
           [-0.189, -0.189, ..., -0.189, -0.189],
           [-0.189, -0.189, ..., -0.189, -0.189]], dtype=float32)

    And plot the results

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2, 1, 1)
    >>> librosa.display.specshow(S**2, sr=sr, y_axis='log')
    >>> plt.colorbar()
    >>> plt.title('Power spectrogram')
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(librosa.power_to_db(S**2, ref=np.max),
    ...                          sr=sr, y_axis='log', x_axis='time')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Log-Power spectrogram')
    >>> plt.tight_layout()


return ref * np.power(<NUM_LIT>, <NUM_LIT:0.1> * S_db)<EOL>

Convert a dB-scale spectrogram to a power spectrogram.

    This effectively inverts `power_to_db`:

        `db_to_power(S_db) ~= ref * 10.0**(S_db / 10)`

    Parameters
    ----------
    S_db : np.ndarray
        dB-scaled spectrogram

    ref : number > 0
        Reference power: output will be scaled by this value

    Returns
    -------
    S : np.ndarray
        Power spectrogram

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


@cache(level=<NUM_LIT:30>)<EOL>def amplitude_to_db(S, ref=<NUM_LIT:1.0>, amin=<NUM_LIT>, top_db=<NUM_LIT>):

S = np.asarray(S)<EOL>if np.issubdtype(S.dtype, np.complexfloating):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>magnitude = np.abs(S)<EOL>if six.callable(ref):<EOL><INDENT>ref_value = ref(magnitude)<EOL><DEDENT>else:<EOL><INDENT>ref_value = np.abs(ref)<EOL><DEDENT>power = np.square(magnitude, out=magnitude)<EOL>return power_to_db(power, ref=ref_value**<NUM_LIT:2>, amin=amin**<NUM_LIT:2>,<EOL>top_db=top_db)<EOL>

Convert an amplitude spectrogram to dB-scaled spectrogram.

    This is equivalent to ``power_to_db(S**2)``, but is provided for convenience.

    Parameters
    ----------
    S : np.ndarray
        input amplitude

    ref : scalar or callable
        If scalar, the amplitude `abs(S)` is scaled relative to `ref`:
        `20 * log10(S / ref)`.
        Zeros in the output correspond to positions where `S == ref`.

        If callable, the reference value is computed as `ref(S)`.

    amin : float > 0 [scalar]
        minimum threshold for `S` and `ref`

    top_db : float >= 0 [scalar]
        threshold the output at `top_db` below the peak:
        ``max(20 * log10(S)) - top_db``

    Returns
    -------
    S_db : np.ndarray
        ``S`` measured in dB

    See Also
    --------
    power_to_db, db_to_amplitude

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


return db_to_power(S_db, ref=ref**<NUM_LIT:2>)**<NUM_LIT:0.5><EOL>

Convert a dB-scaled spectrogram to an amplitude spectrogram.

    This effectively inverts `amplitude_to_db`:

        `db_to_amplitude(S_db) ~= 10.0**(0.5 * (S_db + log10(ref)/10))`

    Parameters
    ----------
    S_db : np.ndarray
        dB-scaled spectrogram

    ref: number > 0
        Optional reference power.

    Returns
    -------
    S : np.ndarray
        Linear magnitude spectrogram

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


@cache(level=<NUM_LIT:30>)<EOL>def perceptual_weighting(S, frequencies, **kwargs):

offset = time_frequency.A_weighting(frequencies).reshape((-<NUM_LIT:1>, <NUM_LIT:1>))<EOL>return offset + power_to_db(S, **kwargs)<EOL>

Perceptual weighting of a power spectrogram:

    `S_p[f] = A_weighting(f) + 10*log(S[f] / ref)`

    Parameters
    ----------
    S : np.ndarray [shape=(d, t)]
        Power spectrogram

    frequencies : np.ndarray [shape=(d,)]
        Center frequency for each row of `S`

    kwargs : additional keyword arguments
        Additional keyword arguments to `power_to_db`.

    Returns
    -------
    S_p : np.ndarray [shape=(d, t)]
        perceptually weighted version of `S`

    See Also
    --------
    power_to_db

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

    Examples
    --------
    Re-weight a CQT power spectrum, using peak power as reference

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> C = np.abs(librosa.cqt(y, sr=sr, fmin=librosa.note_to_hz('A1')))
    >>> freqs = librosa.cqt_frequencies(C.shape[0],
    ...                                 fmin=librosa.note_to_hz('A1'))
    >>> perceptual_CQT = librosa.perceptual_weighting(C**2,
    ...                                               freqs,
    ...                                               ref=np.max)
    >>> perceptual_CQT
    array([[ -80.076,  -80.049, ..., -104.735, -104.735],
           [ -78.344,  -78.555, ..., -103.725, -103.725],
           ...,
           [ -76.272,  -76.272, ...,  -76.272,  -76.272],
           [ -76.485,  -76.485, ...,  -76.485,  -76.485]])

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2, 1, 1)
    >>> librosa.display.specshow(librosa.amplitude_to_db(C,
    ...                                                  ref=np.max),
    ...                          fmin=librosa.note_to_hz('A1'),
    ...                          y_axis='cqt_hz')
    >>> plt.title('Log CQT power')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(perceptual_CQT, y_axis='cqt_hz',
    ...                          fmin=librosa.note_to_hz('A1'),
    ...                          x_axis='time')
    >>> plt.title('Perceptually weighted log CQT')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.tight_layout()


@cache(level=<NUM_LIT:30>)<EOL>def fmt(y, t_min=<NUM_LIT:0.5>, n_fmt=None, kind='<STR_LIT>', beta=<NUM_LIT:0.5>, over_sample=<NUM_LIT:1>, axis=-<NUM_LIT:1>):

n = y.shape[axis]<EOL>if n < <NUM_LIT:3>:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(axis, n))<EOL><DEDENT>if t_min <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if n_fmt is None:<EOL><INDENT>if over_sample < <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>log_base = np.log(n - <NUM_LIT:1>) - np.log(n - <NUM_LIT:2>)<EOL>n_fmt = int(np.ceil(over_sample * (np.log(n - <NUM_LIT:1>) - np.log(t_min)) / log_base))<EOL><DEDENT>elif n_fmt < <NUM_LIT:3>:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(n_fmt))<EOL><DEDENT>else:<EOL><INDENT>log_base = (np.log(n_fmt - <NUM_LIT:1>) - np.log(n_fmt - <NUM_LIT:2>)) / over_sample<EOL><DEDENT>if not np.all(np.isfinite(y)):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>base = np.exp(log_base)<EOL>x = np.linspace(<NUM_LIT:0>, <NUM_LIT:1>, num=n, endpoint=False)<EOL>f_interp = scipy.interpolate.interp1d(x, y, kind=kind, axis=axis)<EOL>n_over = int(np.ceil(over_sample))<EOL>x_exp = np.logspace((np.log(t_min) - np.log(n)) / log_base,<EOL><NUM_LIT:0>,<EOL>num=n_fmt + n_over,<EOL>endpoint=False,<EOL>base=base)[:-n_over]<EOL>if x_exp[<NUM_LIT:0>] < t_min or x_exp[-<NUM_LIT:1>] > float(n - <NUM_LIT:1.0>) / n:<EOL><INDENT>x_exp = np.clip(x_exp, float(t_min) / n, x[-<NUM_LIT:1>])<EOL><DEDENT>if len(np.unique(x_exp)) != len(x_exp):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>y_res = f_interp(x_exp)<EOL>shape = [<NUM_LIT:1>] * y_res.ndim<EOL>shape[axis] = -<NUM_LIT:1><EOL>fft = get_fftlib()<EOL>return fft.rfft(y_res * ((x_exp**beta).reshape(shape) * np.sqrt(n) / n_fmt),<EOL>axis=axis)<EOL>

The fast Mellin transform (FMT) [1]_ of a uniformly sampled signal y.

    When the Mellin parameter (beta) is 1/2, it is also known as the scale transform [2]_.
    The scale transform can be useful for audio analysis because its magnitude is invariant
    to scaling of the domain (e.g., time stretching or compression).  This is analogous
    to the magnitude of the Fourier transform being invariant to shifts in the input domain.

    .. [1] De Sena, Antonio, and Davide Rocchesso.
        "A fast Mellin and scale transform."
        EURASIP Journal on Applied Signal Processing 2007.1 (2007): 75-75.

    .. [2] Cohen, L.
        "The scale representation."
        IEEE Transactions on Signal Processing 41, no. 12 (1993): 3275-3292.

    Parameters
    ----------
    y : np.ndarray, real-valued
        The input signal(s).  Can be multidimensional.
        The target axis must contain at least 3 samples.

    t_min : float > 0
        The minimum time spacing (in samples).
        This value should generally be less than 1 to preserve as much information as
        possible.

    n_fmt : int > 2 or None
        The number of scale transform bins to use.
        If None, then `n_bins = over_sample * ceil(n * log((n-1)/t_min))` is taken,
        where `n = y.shape[axis]`

    kind : str
        The type of interpolation to use when re-sampling the input.
        See `scipy.interpolate.interp1d` for possible values.

        Note that the default is to use high-precision (cubic) interpolation.
        This can be slow in practice; if speed is preferred over accuracy,
        then consider using `kind='linear'`.

    beta : float
        The Mellin parameter.  `beta=0.5` provides the scale transform.

    over_sample : float >= 1
        Over-sampling factor for exponential resampling.

    axis : int
        The axis along which to transform `y`

    Returns
    -------
    x_scale : np.ndarray [dtype=complex]
        The scale transform of `y` along the `axis` dimension.

    Raises
    ------
    ParameterError
        if `n_fmt < 2` or `t_min <= 0`
        or if `y` is not finite
        or if `y.shape[axis] < 3`.

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

    Examples
    --------
    >>> # Generate a signal and time-stretch it (with energy normalization)
    >>> scale = 1.25
    >>> freq = 3.0
    >>> x1 = np.linspace(0, 1, num=1024, endpoint=False)
    >>> x2 = np.linspace(0, 1, num=scale * len(x1), endpoint=False)
    >>> y1 = np.sin(2 * np.pi * freq * x1)
    >>> y2 = np.sin(2 * np.pi * freq * x2) / np.sqrt(scale)
    >>> # Verify that the two signals have the same energy
    >>> np.sum(np.abs(y1)**2), np.sum(np.abs(y2)**2)
        (255.99999999999997, 255.99999999999969)
    >>> scale1 = librosa.fmt(y1, n_fmt=512)
    >>> scale2 = librosa.fmt(y2, n_fmt=512)
    >>> # And plot the results
    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8, 4))
    >>> plt.subplot(1, 2, 1)
    >>> plt.plot(y1, label='Original')
    >>> plt.plot(y2, linestyle='--', label='Stretched')
    >>> plt.xlabel('time (samples)')
    >>> plt.title('Input signals')
    >>> plt.legend(frameon=True)
    >>> plt.axis('tight')
    >>> plt.subplot(1, 2, 2)
    >>> plt.semilogy(np.abs(scale1), label='Original')
    >>> plt.semilogy(np.abs(scale2), linestyle='--', label='Stretched')
    >>> plt.xlabel('scale coefficients')
    >>> plt.title('Scale transform magnitude')
    >>> plt.legend(frameon=True)
    >>> plt.axis('tight')
    >>> plt.tight_layout()

    >>> # Plot the scale transform of an onset strength autocorrelation
    >>> y, sr = librosa.load(librosa.util.example_audio_file(),
    ...                      offset=10.0, duration=30.0)
    >>> odf = librosa.onset.onset_strength(y=y, sr=sr)
    >>> # Auto-correlate with up to 10 seconds lag
    >>> odf_ac = librosa.autocorrelate(odf, max_size=10 * sr // 512)
    >>> # Normalize
    >>> odf_ac = librosa.util.normalize(odf_ac, norm=np.inf)
    >>> # Compute the scale transform
    >>> odf_ac_scale = librosa.fmt(librosa.util.normalize(odf_ac), n_fmt=512)
    >>> # Plot the results
    >>> plt.figure()
    >>> plt.subplot(3, 1, 1)
    >>> plt.plot(odf, label='Onset strength')
    >>> plt.axis('tight')
    >>> plt.xlabel('Time (frames)')
    >>> plt.xticks([])
    >>> plt.legend(frameon=True)
    >>> plt.subplot(3, 1, 2)
    >>> plt.plot(odf_ac, label='Onset autocorrelation')
    >>> plt.axis('tight')
    >>> plt.xlabel('Lag (frames)')
    >>> plt.xticks([])
    >>> plt.legend(frameon=True)
    >>> plt.subplot(3, 1, 3)
    >>> plt.semilogy(np.abs(odf_ac_scale), label='Scale transform magnitude')
    >>> plt.axis('tight')
    >>> plt.xlabel('scale coefficients')
    >>> plt.legend(frameon=True)
    >>> plt.tight_layout()


@cache(level=<NUM_LIT:30>)<EOL>def pcen(S, sr=<NUM_LIT>, hop_length=<NUM_LIT>, gain=<NUM_LIT>, bias=<NUM_LIT:2>, power=<NUM_LIT:0.5>,<EOL>time_constant=<NUM_LIT>, eps=<NUM_LIT>, b=None, max_size=<NUM_LIT:1>, ref=None,<EOL>axis=-<NUM_LIT:1>, max_axis=None, zi=None, return_zf=False):

if power <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(power))<EOL><DEDENT>if gain < <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(gain))<EOL><DEDENT>if bias < <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(bias))<EOL><DEDENT>if eps <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(eps))<EOL><DEDENT>if time_constant <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(time_constant))<EOL><DEDENT>if max_size < <NUM_LIT:1> or not isinstance(max_size, int):<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(max_size))<EOL><DEDENT>if b is None:<EOL><INDENT>t_frames = time_constant * sr / float(hop_length)<EOL>b = (np.sqrt(<NUM_LIT:1> + <NUM_LIT:4> * t_frames**<NUM_LIT:2>) - <NUM_LIT:1>) / (<NUM_LIT:2> * t_frames**<NUM_LIT:2>)<EOL><DEDENT>if not <NUM_LIT:0> <= b <= <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(b))<EOL><DEDENT>if np.issubdtype(S.dtype, np.complexfloating):<EOL><INDENT>warnings.warn('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>S = np.abs(S)<EOL><DEDENT>if ref is None:<EOL><INDENT>if max_size == <NUM_LIT:1>:<EOL><INDENT>ref = S<EOL><DEDENT>elif S.ndim == <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>if max_axis is None:<EOL><INDENT>if S.ndim != <NUM_LIT:2>:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(S.ndim))<EOL><DEDENT>max_axis = np.mod(<NUM_LIT:1> - axis, <NUM_LIT:2>)<EOL><DEDENT>ref = scipy.ndimage.maximum_filter1d(S, max_size, axis=max_axis)<EOL><DEDENT><DEDENT>if zi is None:<EOL><INDENT>shape = tuple([<NUM_LIT:1>] * ref.ndim)<EOL>zi = np.empty(shape)<EOL>zi[:] = scipy.signal.lfilter_zi([b], [<NUM_LIT:1>, b - <NUM_LIT:1>])[:]<EOL><DEDENT>S_smooth, zf = scipy.signal.lfilter([b], [<NUM_LIT:1>, b - <NUM_LIT:1>], ref, zi=zi,<EOL>axis=axis)<EOL>smooth = np.exp(-gain * (np.log(eps) + np.log1p(S_smooth / eps)))<EOL>S_out = (S * smooth + bias)**power - bias**power<EOL>if return_zf:<EOL><INDENT>return S_out, zf<EOL><DEDENT>else:<EOL><INDENT>return S_out<EOL><DEDENT>

Per-channel energy normalization (PCEN) [1]_

    This function normalizes a time-frequency representation `S` by
    performing automatic gain control, followed by nonlinear compression:

        P[f, t] = (S / (eps + M[f, t])**gain + bias)**power - bias**power

    where `M` is the result of applying a low-pass, temporal IIR filter
    to `S`:

        M[f, t] = (1 - b) * M[f, t - 1] + b * S[f, t]

    If `b` is not provided, it is calculated as:

        b = (sqrt(1 + 4* T**2) - 1) / (2 * T**2)

    where `T = time_constant * sr / hop_length`.

    This normalization is designed to suppress background noise and
    emphasize foreground signals, and can be used as an alternative to
    decibel scaling (`amplitude_to_db`).

    This implementation also supports smoothing across frequency bins
    by specifying `max_size > 1`.  If this option is used, the filtered
    spectrogram `M` is computed as

        M[f, t] = (1 - b) * M[f, t - 1] + b * R[f, t]

    where `R` has been max-filtered along the frequency axis, similar to
    the SuperFlux algorithm implemented in `onset.onset_strength`:

        R[f, t] = max(S[f - max_size//2: f + max_size//2, t])

    This can be used to perform automatic gain control on signals that cross
    or span multiple frequency bans, which may be desirable for spectrograms
    with high frequency resolution.

    .. [1] Wang, Y., Getreuer, P., Hughes, T., Lyon, R. F., & Saurous, R. A.
       (2017, March). Trainable frontend for robust and far-field keyword spotting.
       In Acoustics, Speech and Signal Processing (ICASSP), 2017
       IEEE International Conference on (pp. 5670-5674). IEEE.

    Parameters
    ----------
    S : np.ndarray (non-negative)
        The input (magnitude) spectrogram

    sr : number > 0 [scalar]
        The audio sampling rate

    hop_length : int > 0 [scalar]
        The hop length of `S`, expressed in samples

    gain : number >= 0 [scalar]
        The gain factor.  Typical values should be slightly less than 1.

    bias : number >= 0 [scalar]
        The bias point of the nonlinear compression (default: 2)

    power : number > 0 [scalar]
        The compression exponent.  Typical values should be between 0 and 1.
        Smaller values of `power` result in stronger compression.

    time_constant : number > 0 [scalar]
        The time constant for IIR filtering, measured in seconds.

    eps : number > 0 [scalar]
        A small constant used to ensure numerical stability of the filter.

    b : number in [0, 1]  [scalar]
        The filter coefficient for the low-pass filter.
        If not provided, it will be inferred from `time_constant`.

    max_size : int > 0 [scalar]
        The width of the max filter applied to the frequency axis.
        If left as `1`, no filtering is performed.

    ref : None or np.ndarray (shape=S.shape)
        An optional pre-computed reference spectrum (`R` in the above).
        If not provided it will be computed from `S`.

    axis : int [scalar]
        The (time) axis of the input spectrogram.

    max_axis : None or int [scalar]
        The frequency axis of the input spectrogram.
        If `None`, and `S` is two-dimensional, it will be inferred
        as the opposite from `axis`.
        If `S` is not two-dimensional, and `max_size > 1`, an error
        will be raised.

    zi : np.ndarray
        The initial filter delay values.

        This may be the `zf` (final delay values) of a previous call to `pcen`, or
        computed by `scipy.signal.lfilter_zi`.

    return_zf : bool
        If `True`, return the final filter delay values along with the PCEN output `P`.
        This is primarily useful in streaming contexts, where the final state of one
        block of processing should be used to initialize the next block.

        If `False` (default) only the PCEN values `P` are returned.

    Returns
    -------
    P : np.ndarray, non-negative [shape=(n, m)]
        The per-channel energy normalized version of `S`.

    zf : np.ndarray (optional)
        The final filter delay values.  Only returned if `return_zf=True`.

    See Also
    --------
    amplitude_to_db
    librosa.onset.onset_strength

    Examples
    --------

    Compare PCEN to log amplitude (dB) scaling on Mel spectra

    >>> import matplotlib.pyplot as plt
    >>> y, sr = librosa.load(librosa.util.example_audio_file(),
    ...                      offset=10, duration=10)

    >>> # We'll use power=1 to get a magnitude spectrum
    >>> # instead of a power spectrum
    >>> S = librosa.feature.melspectrogram(y, sr=sr, power=1)
    >>> log_S = librosa.amplitude_to_db(S, ref=np.max)
    >>> pcen_S = librosa.pcen(S)
    >>> plt.figure()
    >>> plt.subplot(2,1,1)
    >>> librosa.display.specshow(log_S, x_axis='time', y_axis='mel')
    >>> plt.title('log amplitude (dB)')
    >>> plt.colorbar()
    >>> plt.subplot(2,1,2)
    >>> librosa.display.specshow(pcen_S, x_axis='time', y_axis='mel')
    >>> plt.title('Per-channel energy normalization')
    >>> plt.colorbar()
    >>> plt.tight_layout()

    Compare PCEN with and without max-filtering

    >>> pcen_max = librosa.pcen(S, max_size=3)
    >>> plt.figure()
    >>> plt.subplot(2,1,1)
    >>> librosa.display.specshow(pcen_S, x_axis='time', y_axis='mel')
    >>> plt.title('Per-channel energy normalization (no max-filter)')
    >>> plt.colorbar()
    >>> plt.subplot(2,1,2)
    >>> librosa.display.specshow(pcen_max, x_axis='time', y_axis='mel')
    >>> plt.title('Per-channel energy normalization (max_size=3)')
    >>> plt.colorbar()
    >>> plt.tight_layout()


def _spectrogram(y=None, S=None, n_fft=<NUM_LIT>, hop_length=<NUM_LIT>, power=<NUM_LIT:1>,<EOL>win_length=None, window='<STR_LIT>', center=True, pad_mode='<STR_LIT>'):

if S is not None:<EOL><INDENT>n_fft = <NUM_LIT:2> * (S.shape[<NUM_LIT:0>] - <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>S = np.abs(stft(y, n_fft=n_fft, hop_length=hop_length,<EOL>win_length=win_length, center=center,<EOL>window=window, pad_mode=pad_mode))**power<EOL><DEDENT>return S, n_fft<EOL>

Helper function to retrieve a magnitude spectrogram.

    This is primarily used in feature extraction functions that can operate on
    either audio time-series or spectrogram input.

    Parameters
    ----------
    y : None or np.ndarray [ndim=1]
        If provided, an audio time series

    S : None or np.ndarray
        Spectrogram input, optional

    n_fft : int > 0
        STFT window size

    hop_length : int > 0
        STFT hop length

    power : float > 0
        Exponent for the magnitude spectrogram,
        e.g., 1 for energy, 2 for power, etc.

    win_length : int <= n_fft [scalar]
        Each frame of audio is windowed by `window()`.
        The window will be of length `win_length` and then padded
        with zeros to match `n_fft`.

        If unspecified, defaults to ``win_length = n_fft``.

    window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)]
        - a window specification (string, tuple, or number);
          see `scipy.signal.get_window`
        - a window function, such as `scipy.signal.hanning`
        - a vector or array of length `n_fft`

        .. see also:: `filters.get_window`

    center : boolean
        - If `True`, the signal `y` is padded so that frame
          `t` is centered at `y[t * hop_length]`.
        - If `False`, then frame `t` begins at `y[t * hop_length]`

    pad_mode : string
        If `center=True`, the padding mode to use at the edges of the signal.
        By default, STFT uses reflection padding.

    Returns
    -------
    S_out : np.ndarray [dtype=np.float32]
        - If `S` is provided as input, then `S_out == S`
        - Else, `S_out = |stft(y, ...)|**power`

    n_fft : int > 0
        - If `S` is provided, then `n_fft` is inferred from `S`
        - Else, copied from input


global __FFTLIB<EOL>if lib is None:<EOL><INDENT>from numpy import fft<EOL>lib = fft<EOL><DEDENT>__FFTLIB = lib<EOL>

Set the FFT library used by librosa.

    Parameters
    ----------
    lib : None or module
        Must implement an interface compatible with `numpy.fft`.
        If `None`, reverts to `numpy.fft`.

    Examples
    --------
    Use `pyfftw`:

    >>> import pyfftw
    >>> librosa.set_fftlib(pyfftw.interfaces.numpy_fft)

    Reset to default `numpy` implementation

    >>> librosa.set_fftlib()


global __FFTLIB<EOL>return __FFTLIB<EOL>

Get the FFT library currently used by librosa

    Returns
    -------
    fft : module
        The FFT library currently used by librosa.
        Must API-compatible with `numpy.fft`.


def estimate_tuning(y=None, sr=<NUM_LIT>, S=None, n_fft=<NUM_LIT>,<EOL>resolution=<NUM_LIT>, bins_per_octave=<NUM_LIT:12>, **kwargs):

pitch, mag = piptrack(y=y, sr=sr, S=S, n_fft=n_fft, **kwargs)<EOL>pitch_mask = pitch > <NUM_LIT:0><EOL>if pitch_mask.any():<EOL><INDENT>threshold = np.median(mag[pitch_mask])<EOL><DEDENT>else:<EOL><INDENT>threshold = <NUM_LIT:0.0><EOL><DEDENT>return pitch_tuning(pitch[(mag >= threshold) & pitch_mask],<EOL>resolution=resolution,<EOL>bins_per_octave=bins_per_octave)<EOL>

Estimate the tuning of an audio time series or spectrogram input.

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

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

    S: np.ndarray [shape=(d, t)] or None
        magnitude or power spectrogram

    n_fft : int > 0 [scalar] or None
        number of FFT bins to use, if `y` is provided.

    resolution : float in `(0, 1)`
        Resolution of the tuning as a fraction of a bin.
        0.01 corresponds to measurements in cents.

    bins_per_octave : int > 0 [scalar]
        How many frequency bins per octave

    kwargs : additional keyword arguments
        Additional arguments passed to `piptrack`

    Returns
    -------
    tuning: float in `[-0.5, 0.5)`
        estimated tuning deviation (fractions of a bin)

    See Also
    --------
    piptrack
        Pitch tracking by parabolic interpolation

    Examples
    --------
    >>> # With time-series input
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.estimate_tuning(y=y, sr=sr)
    0.089999999999999969

    >>> # In tenths of a cent
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.estimate_tuning(y=y, sr=sr, resolution=1e-3)
    0.093999999999999972

    >>> # Using spectrogram input
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> S = np.abs(librosa.stft(y))
    >>> librosa.estimate_tuning(S=S, sr=sr)
    0.089999999999999969

    >>> # Using pass-through arguments to `librosa.piptrack`
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.estimate_tuning(y=y, sr=sr, n_fft=8192,
    ...                         fmax=librosa.note_to_hz('G#9'))
    0.070000000000000062


def pitch_tuning(frequencies, resolution=<NUM_LIT>, bins_per_octave=<NUM_LIT:12>):

frequencies = np.atleast_1d(frequencies)<EOL>frequencies = frequencies[frequencies > <NUM_LIT:0>]<EOL>if not np.any(frequencies):<EOL><INDENT>warnings.warn('<STR_LIT>')<EOL>return <NUM_LIT:0.0><EOL><DEDENT>residual = np.mod(bins_per_octave *<EOL>time_frequency.hz_to_octs(frequencies), <NUM_LIT:1.0>)<EOL>residual[residual >= <NUM_LIT:0.5>] -= <NUM_LIT:1.0><EOL>bins = np.linspace(-<NUM_LIT:0.5>, <NUM_LIT:0.5>, int(np.ceil(<NUM_LIT:1.> / resolution)) + <NUM_LIT:1>)<EOL>counts, tuning = np.histogram(residual, bins)<EOL>return tuning[np.argmax(counts)]<EOL>

Given a collection of pitches, estimate its tuning offset
    (in fractions of a bin) relative to A440=440.0Hz.

    Parameters
    ----------
    frequencies : array-like, float
        A collection of frequencies detected in the signal.
        See `piptrack`

    resolution : float in `(0, 1)`
        Resolution of the tuning as a fraction of a bin.
        0.01 corresponds to cents.

    bins_per_octave : int > 0 [scalar]
        How many frequency bins per octave

    Returns
    -------
    tuning: float in `[-0.5, 0.5)`
        estimated tuning deviation (fractions of a bin)

    See Also
    --------
    estimate_tuning
        Estimating tuning from time-series or spectrogram input

    Examples
    --------
    >>> # Generate notes at +25 cents
    >>> freqs = librosa.cqt_frequencies(24, 55, tuning=0.25)
    >>> librosa.pitch_tuning(freqs)
    0.25

    >>> # Track frequencies from a real spectrogram
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> pitches, magnitudes, stft = librosa.ifptrack(y, sr)
    >>> # Select out pitches with high energy
    >>> pitches = pitches[magnitudes > np.median(magnitudes)]
    >>> librosa.pitch_tuning(pitches)
    0.089999999999999969


@cache(level=<NUM_LIT:30>)<EOL>def piptrack(y=None, sr=<NUM_LIT>, S=None, n_fft=<NUM_LIT>, hop_length=None,<EOL>fmin=<NUM_LIT>, fmax=<NUM_LIT>, threshold=<NUM_LIT:0.1>,<EOL>win_length=None, window='<STR_LIT>', center=True, pad_mode='<STR_LIT>',<EOL>ref=None):

<EOL>S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length,<EOL>win_length=win_length, window=window,<EOL>center=center, pad_mode=pad_mode)<EOL>S = np.abs(S)<EOL>fmin = np.maximum(fmin, <NUM_LIT:0>)<EOL>fmax = np.minimum(fmax, float(sr) / <NUM_LIT:2>)<EOL>fft_freqs = time_frequency.fft_frequencies(sr=sr, n_fft=n_fft)<EOL>avg = <NUM_LIT:0.5> * (S[<NUM_LIT:2>:] - S[:-<NUM_LIT:2>])<EOL>shift = <NUM_LIT:2> * S[<NUM_LIT:1>:-<NUM_LIT:1>] - S[<NUM_LIT:2>:] - S[:-<NUM_LIT:2>]<EOL>shift = avg / (shift + (np.abs(shift) < util.tiny(shift)))<EOL>avg = np.pad(avg, ([<NUM_LIT:1>, <NUM_LIT:1>], [<NUM_LIT:0>, <NUM_LIT:0>]), mode='<STR_LIT>')<EOL>shift = np.pad(shift, ([<NUM_LIT:1>, <NUM_LIT:1>], [<NUM_LIT:0>, <NUM_LIT:0>]), mode='<STR_LIT>')<EOL>dskew = <NUM_LIT:0.5> * avg * shift<EOL>pitches = np.zeros_like(S)<EOL>mags = np.zeros_like(S)<EOL>freq_mask = ((fmin <= fft_freqs) & (fft_freqs < fmax)).reshape((-<NUM_LIT:1>, <NUM_LIT:1>))<EOL>if ref is None:<EOL><INDENT>ref = np.max<EOL><DEDENT>if six.callable(ref):<EOL><INDENT>ref_value = threshold * ref(S, axis=<NUM_LIT:0>)<EOL><DEDENT>else:<EOL><INDENT>ref_value = np.abs(ref)<EOL><DEDENT>idx = np.argwhere(freq_mask & util.localmax(S * (S > ref_value)))<EOL>pitches[idx[:, <NUM_LIT:0>], idx[:, <NUM_LIT:1>]] = ((idx[:, <NUM_LIT:0>] + shift[idx[:, <NUM_LIT:0>], idx[:, <NUM_LIT:1>]])<EOL>* float(sr) / n_fft)<EOL>mags[idx[:, <NUM_LIT:0>], idx[:, <NUM_LIT:1>]] = (S[idx[:, <NUM_LIT:0>], idx[:, <NUM_LIT:1>]]<EOL>+ dskew[idx[:, <NUM_LIT:0>], idx[:, <NUM_LIT:1>]])<EOL>return pitches, mags<EOL>

Pitch tracking on thresholded parabolically-interpolated STFT.

    This implementation uses the parabolic interpolation method described by [1]_.

    .. [1] https://ccrma.stanford.edu/~jos/sasp/Sinusoidal_Peak_Interpolation.html

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

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

    S: np.ndarray [shape=(d, t)] or None
        magnitude or power spectrogram

    n_fft : int > 0 [scalar] or None
        number of FFT bins to use, if `y` is provided.

    hop_length : int > 0 [scalar] or None
        number of samples to hop

    threshold : float in `(0, 1)`
        A bin in spectrum `S` is considered a pitch when it is greater than
        `threshold*ref(S)`.

        By default, `ref(S)` is taken to be `max(S, axis=0)` (the maximum value in
        each column).

    fmin : float > 0 [scalar]
        lower frequency cutoff.

    fmax : float > 0 [scalar]
        upper frequency cutoff.

    win_length : int <= n_fft [scalar]
        Each frame of audio is windowed by `window()`.
        The window will be of length `win_length` and then padded
        with zeros to match `n_fft`.

        If unspecified, defaults to ``win_length = n_fft``.

    window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)]
        - a window specification (string, tuple, or number);
          see `scipy.signal.get_window`
        - a window function, such as `scipy.signal.hanning`
        - a vector or array of length `n_fft`

        .. see also:: `filters.get_window`

    center : boolean
        - If `True`, the signal `y` is padded so that frame
          `t` is centered at `y[t * hop_length]`.
        - If `False`, then frame `t` begins at `y[t * hop_length]`

    pad_mode : string
        If `center=True`, the padding mode to use at the edges of the signal.
        By default, STFT uses reflection padding.

    ref : scalar or callable [default=np.max]
        If scalar, the reference value against which `S` is compared for determining
        pitches.

        If callable, the reference value is computed as `ref(S, axis=0)`.

    .. note::
        One of `S` or `y` must be provided.

        If `S` is not given, it is computed from `y` using
        the default parameters of `librosa.core.stft`.

    Returns
    -------
    pitches : np.ndarray [shape=(d, t)]
    magnitudes : np.ndarray [shape=(d,t)]
        Where `d` is the subset of FFT bins within `fmin` and `fmax`.

        `pitches[f, t]` contains instantaneous frequency at bin
        `f`, time `t`

        `magnitudes[f, t]` contains the corresponding magnitudes.

        Both `pitches` and `magnitudes` take value 0 at bins
        of non-maximal magnitude.

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

    Examples
    --------
    Computing pitches from a waveform input

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> pitches, magnitudes = librosa.piptrack(y=y, sr=sr)

    Or from a spectrogram input

    >>> S = np.abs(librosa.stft(y))
    >>> pitches, magnitudes = librosa.piptrack(S=S, sr=sr)

    Or with an alternate reference value for pitch detection, where
    values above the mean spectral energy in each frame are counted as pitches

    >>> pitches, magnitudes = librosa.piptrack(S=S, sr=sr, threshold=1,
    ...                                        ref=np.mean)


return pkg_resources.resource_filename(__name__, EXAMPLE_AUDIO)<EOL>

Get the path to an included audio example file.

    Examples
    --------
    >>> # Load the waveform from the example track
    >>> y, sr = librosa.load(librosa.util.example_audio_file())

    Returns
    -------
    filename : str
        Path to the audio example file included with librosa

    .. raw:: html

        Vibe Ace
        (Kevin MacLeod)
        / CC BY 3.0


def find_files(directory, ext=None, recurse=True, case_sensitive=False,<EOL>limit=None, offset=<NUM_LIT:0>):

if ext is None:<EOL><INDENT>ext = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL><DEDENT>elif isinstance(ext, six.string_types):<EOL><INDENT>ext = [ext]<EOL><DEDENT>ext = set(ext)<EOL>if not case_sensitive:<EOL><INDENT>ext = set([e.lower() for e in ext])<EOL>ext |= set([e.upper() for e in ext])<EOL><DEDENT>files = set()<EOL>if recurse:<EOL><INDENT>for walk in os.walk(directory):<EOL><INDENT>files |= __get_files(walk[<NUM_LIT:0>], ext)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>files = __get_files(directory, ext)<EOL><DEDENT>files = list(files)<EOL>files.sort()<EOL>files = files[offset:]<EOL>if limit is not None:<EOL><INDENT>files = files[:limit]<EOL><DEDENT>return files<EOL>

Get a sorted list of (audio) files in a directory or directory sub-tree.

    Examples
    --------
    >>> # Get all audio files in a directory sub-tree
    >>> files = librosa.util.find_files('~/Music')

    >>> # Look only within a specific directory, not the sub-tree
    >>> files = librosa.util.find_files('~/Music', recurse=False)

    >>> # Only look for mp3 files
    >>> files = librosa.util.find_files('~/Music', ext='mp3')

    >>> # Or just mp3 and ogg
    >>> files = librosa.util.find_files('~/Music', ext=['mp3', 'ogg'])

    >>> # Only get the first 10 files
    >>> files = librosa.util.find_files('~/Music', limit=10)

    >>> # Or last 10 files
    >>> files = librosa.util.find_files('~/Music', offset=-10)

    Parameters
    ----------
    directory : str
        Path to look for files

    ext : str or list of str
        A file extension or list of file extensions to include in the search.

        Default: `['aac', 'au', 'flac', 'm4a', 'mp3', 'ogg', 'wav']`

    recurse : boolean
        If `True`, then all subfolders of `directory` will be searched.

        Otherwise, only `directory` will be searched.

    case_sensitive : boolean
        If `False`, files matching upper-case version of
        extensions will be included.

    limit : int > 0 or None
        Return at most `limit` files. If `None`, all files are returned.

    offset : int
        Return files starting at `offset` within the list.

        Use negative values to offset from the end of the list.

    Returns
    -------
    files : list of str
        The list of audio files.


<EOL>dir_name = os.path.abspath(os.path.expanduser(dir_name))<EOL>myfiles = set()<EOL>for sub_ext in extensions:<EOL><INDENT>globstr = os.path.join(dir_name, '<STR_LIT:*>' + os.path.extsep + sub_ext)<EOL>myfiles |= set(glob.glob(globstr))<EOL><DEDENT>return myfiles<EOL>

Helper function to get files in a single directory


def rename_kw(old_name, old_value, new_name, new_value,<EOL>version_deprecated, version_removed):

if isinstance(old_value, Deprecated):<EOL><INDENT>return new_value<EOL><DEDENT>else:<EOL><INDENT>stack = inspect.stack()<EOL>dep_func = stack[<NUM_LIT:1>]<EOL>caller = stack[<NUM_LIT:2>]<EOL>warnings.warn_explicit("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(dep_func[<NUM_LIT:3>],<EOL>old_name, new_name,<EOL>version_deprecated,<EOL>version_removed),<EOL>category=DeprecationWarning,<EOL>filename=caller[<NUM_LIT:1>],<EOL>lineno=caller[<NUM_LIT:2>])<EOL>return old_value<EOL><DEDENT>

Handle renamed arguments.

    Parameters
    ----------
    old_name : str
    old_value
        The name and value of the old argument

    new_name : str
    new_value
        The name and value of the new argument

    version_deprecated : str
        The version at which the old name became deprecated

    version_removed : str
        The version at which the old name will be removed

    Returns
    -------
    value
        - `new_value` if `old_value` of type `Deprecated`
        - `old_value` otherwise

    Warnings
    --------
    if `old_value` is not of type `Deprecated`


def frame(y, frame_length=<NUM_LIT>, hop_length=<NUM_LIT>):

if not isinstance(y, np.ndarray):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(type(y)))<EOL><DEDENT>if y.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(y.ndim))<EOL><DEDENT>if len(y) < frame_length:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(len(y), frame_length))<EOL><DEDENT>if hop_length < <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(hop_length))<EOL><DEDENT>if not y.flags['<STR_LIT>']:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>n_frames = <NUM_LIT:1> + int((len(y) - frame_length) / hop_length)<EOL>y_frames = as_strided(y, shape=(frame_length, n_frames),<EOL>strides=(y.itemsize, hop_length * y.itemsize))<EOL>return y_frames<EOL>

Slice a time series into overlapping frames.

    This implementation uses low-level stride manipulation to avoid
    redundant copies of the time series data.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)]
        Time series to frame. Must be one-dimensional and contiguous
        in memory.

    frame_length : int > 0 [scalar]
        Length of the frame in samples

    hop_length : int > 0 [scalar]
        Number of samples to hop between frames

    Returns
    -------
    y_frames : np.ndarray [shape=(frame_length, N_FRAMES)]
        An array of frames sampled from `y`:
        `y_frames[i, j] == y[j * hop_length + i]`

    Raises
    ------
    ParameterError
        If `y` is not contiguous in memory, not an `np.ndarray`, or
        not one-dimensional.  See `np.ascontiguous()` for details.

        If `hop_length < 1`, frames cannot advance.

        If `len(y) < frame_length`.

    Examples
    --------
    Extract 2048-sample frames from `y` with a hop of 64 samples per frame

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.util.frame(y, frame_length=2048, hop_length=64)
    array([[ -9.216e-06,   7.710e-06, ...,  -2.117e-06,  -4.362e-07],
           [  2.518e-06,  -6.294e-06, ...,  -1.775e-05,  -6.365e-06],
           ...,
           [ -7.429e-04,   5.173e-03, ...,   1.105e-05,  -5.074e-06],
           [  2.169e-03,   4.867e-03, ...,   3.666e-06,  -5.571e-06]], dtype=float32)


if not isinstance(y, np.ndarray):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if not np.issubdtype(y.dtype, np.floating):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if mono and y.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(y.ndim, y.shape))<EOL><DEDENT>elif y.ndim > <NUM_LIT:2> or y.ndim == <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(y.shape))<EOL><DEDENT>if not np.isfinite(y).all():<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>return True<EOL>

Validate whether a variable contains valid, mono audio data.

    Parameters
    ----------
    y : np.ndarray
      The input data to validate

    mono : bool
      Whether or not to force monophonic audio

    Returns
    -------
    valid : bool
        True if all tests pass

    Raises
    ------
    ParameterError
        If `y` fails to meet the following criteria:
            - `type(y)` is `np.ndarray`
            - `y.dtype` is floating-point
            - `mono == True` and `y.ndim` is not 1
            - `mono == False` and `y.ndim` is not 1 or 2
            - `np.isfinite(y).all()` is not True

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

    Examples
    --------
    >>> # Only allow monophonic signals
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.util.valid_audio(y)
    True

    >>> # If we want to allow stereo signals
    >>> y, sr = librosa.load(librosa.util.example_audio_file(), mono=False)
    >>> librosa.util.valid_audio(y, mono=False)
    True


if cast is None:<EOL><INDENT>cast = np.floor<EOL><DEDENT>if not six.callable(cast):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>return int(cast(x))<EOL>

Ensure that an input value is integer-typed.
    This is primarily useful for ensuring integrable-valued
    array indices.

    Parameters
    ----------
    x : number
        A scalar value to be cast to int

    cast : function [optional]
        A function to modify `x` before casting.
        Default: `np.floor`

    Returns
    -------
    x_int : int
        `x_int = int(cast(x))`

    Raises
    ------
    ParameterError
        If `cast` is provided and is not callable.


if intervals.ndim != <NUM_LIT:2> or intervals.shape[-<NUM_LIT:1>] != <NUM_LIT:2>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if np.any(intervals[:, <NUM_LIT:0>] > intervals[:, <NUM_LIT:1>]):<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(intervals))<EOL><DEDENT>return True<EOL>

Ensure that an array is a valid representation of time intervals:

        - intervals.ndim == 2
        - intervals.shape[1] == 2
        - intervals[i, 0] <= intervals[i, 1] for all i

    Parameters
    ----------
    intervals : np.ndarray [shape=(n, 2)]
        set of time intervals

    Returns
    -------
    valid : bool
        True if `intervals` passes validation.


def pad_center(data, size, axis=-<NUM_LIT:1>, **kwargs):

kwargs.setdefault('<STR_LIT>', '<STR_LIT>')<EOL>n = data.shape[axis]<EOL>lpad = int((size - n) // <NUM_LIT:2>)<EOL>lengths = [(<NUM_LIT:0>, <NUM_LIT:0>)] * data.ndim<EOL>lengths[axis] = (lpad, int(size - n - lpad))<EOL>if lpad < <NUM_LIT:0>:<EOL><INDENT>raise ParameterError(('<STR_LIT>'<EOL>'<STR_LIT>').format(size, n))<EOL><DEDENT>return np.pad(data, lengths, **kwargs)<EOL>

Wrapper for np.pad to automatically center an array prior to padding.
    This is analogous to `str.center()`

    Examples
    --------
    >>> # Generate a vector
    >>> data = np.ones(5)
    >>> librosa.util.pad_center(data, 10, mode='constant')
    array([ 0.,  0.,  1.,  1.,  1.,  1.,  1.,  0.,  0.,  0.])

    >>> # Pad a matrix along its first dimension
    >>> data = np.ones((3, 5))
    >>> librosa.util.pad_center(data, 7, axis=0)
    array([[ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.],
           [ 1.,  1.,  1.,  1.,  1.],
           [ 1.,  1.,  1.,  1.,  1.],
           [ 1.,  1.,  1.,  1.,  1.],
           [ 0.,  0.,  0.,  0.,  0.],
           [ 0.,  0.,  0.,  0.,  0.]])
    >>> # Or its second dimension
    >>> librosa.util.pad_center(data, 7, axis=1)
    array([[ 0.,  1.,  1.,  1.,  1.,  1.,  0.],
           [ 0.,  1.,  1.,  1.,  1.,  1.,  0.],
           [ 0.,  1.,  1.,  1.,  1.,  1.,  0.]])

    Parameters
    ----------
    data : np.ndarray
        Vector to be padded and centered

    size : int >= len(data) [scalar]
        Length to pad `data`

    axis : int
        Axis along which to pad and center the data

    kwargs : additional keyword arguments
      arguments passed to `np.pad()`

    Returns
    -------
    data_padded : np.ndarray
        `data` centered and padded to length `size` along the
        specified axis

    Raises
    ------
    ParameterError
        If `size < data.shape[axis]`

    See Also
    --------
    numpy.pad


def fix_length(data, size, axis=-<NUM_LIT:1>, **kwargs):

kwargs.setdefault('<STR_LIT>', '<STR_LIT>')<EOL>n = data.shape[axis]<EOL>if n > size:<EOL><INDENT>slices = [slice(None)] * data.ndim<EOL>slices[axis] = slice(<NUM_LIT:0>, size)<EOL>return data[tuple(slices)]<EOL><DEDENT>elif n < size:<EOL><INDENT>lengths = [(<NUM_LIT:0>, <NUM_LIT:0>)] * data.ndim<EOL>lengths[axis] = (<NUM_LIT:0>, size - n)<EOL>return np.pad(data, lengths, **kwargs)<EOL><DEDENT>return data<EOL>

Fix the length an array `data` to exactly `size`.

    If `data.shape[axis] < n`, pad according to the provided kwargs.
    By default, `data` is padded with trailing zeros.

    Examples
    --------
    >>> y = np.arange(7)
    >>> # Default: pad with zeros
    >>> librosa.util.fix_length(y, 10)
    array([0, 1, 2, 3, 4, 5, 6, 0, 0, 0])
    >>> # Trim to a desired length
    >>> librosa.util.fix_length(y, 5)
    array([0, 1, 2, 3, 4])
    >>> # Use edge-padding instead of zeros
    >>> librosa.util.fix_length(y, 10, mode='edge')
    array([0, 1, 2, 3, 4, 5, 6, 6, 6, 6])

    Parameters
    ----------
    data : np.ndarray
      array to be length-adjusted

    size : int >= 0 [scalar]
      desired length of the array

    axis : int, <= data.ndim
      axis along which to fix length

    kwargs : additional keyword arguments
        Parameters to `np.pad()`

    Returns
    -------
    data_fixed : np.ndarray [shape=data.shape]
        `data` either trimmed or padded to length `size`
        along the specified axis.

    See Also
    --------
    numpy.pad


def fix_frames(frames, x_min=<NUM_LIT:0>, x_max=None, pad=True):

frames = np.asarray(frames)<EOL>if np.any(frames < <NUM_LIT:0>):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if pad and (x_min is not None or x_max is not None):<EOL><INDENT>frames = np.clip(frames, x_min, x_max)<EOL><DEDENT>if pad:<EOL><INDENT>pad_data = []<EOL>if x_min is not None:<EOL><INDENT>pad_data.append(x_min)<EOL><DEDENT>if x_max is not None:<EOL><INDENT>pad_data.append(x_max)<EOL><DEDENT>frames = np.concatenate((pad_data, frames))<EOL><DEDENT>if x_min is not None:<EOL><INDENT>frames = frames[frames >= x_min]<EOL><DEDENT>if x_max is not None:<EOL><INDENT>frames = frames[frames <= x_max]<EOL><DEDENT>return np.unique(frames).astype(int)<EOL>

Fix a list of frames to lie within [x_min, x_max]

    Examples
    --------
    >>> # Generate a list of frame indices
    >>> frames = np.arange(0, 1000.0, 50)
    >>> frames
    array([   0.,   50.,  100.,  150.,  200.,  250.,  300.,  350.,
            400.,  450.,  500.,  550.,  600.,  650.,  700.,  750.,
            800.,  850.,  900.,  950.])
    >>> # Clip to span at most 250
    >>> librosa.util.fix_frames(frames, x_max=250)
    array([  0,  50, 100, 150, 200, 250])
    >>> # Or pad to span up to 2500
    >>> librosa.util.fix_frames(frames, x_max=2500)
    array([   0,   50,  100,  150,  200,  250,  300,  350,  400,
            450,  500,  550,  600,  650,  700,  750,  800,  850,
            900,  950, 2500])
    >>> librosa.util.fix_frames(frames, x_max=2500, pad=False)
    array([  0,  50, 100, 150, 200, 250, 300, 350, 400, 450, 500,
           550, 600, 650, 700, 750, 800, 850, 900, 950])

    >>> # Or starting away from zero
    >>> frames = np.arange(200, 500, 33)
    >>> frames
    array([200, 233, 266, 299, 332, 365, 398, 431, 464, 497])
    >>> librosa.util.fix_frames(frames)
    array([  0, 200, 233, 266, 299, 332, 365, 398, 431, 464, 497])
    >>> librosa.util.fix_frames(frames, x_max=500)
    array([  0, 200, 233, 266, 299, 332, 365, 398, 431, 464, 497,
           500])

    Parameters
    ----------
    frames : np.ndarray [shape=(n_frames,)]
        List of non-negative frame indices

    x_min : int >= 0 or None
        Minimum allowed frame index

    x_max : int >= 0 or None
        Maximum allowed frame index

    pad : boolean
        If `True`, then `frames` is expanded to span the full range
        `[x_min, x_max]`

    Returns
    -------
    fixed_frames : np.ndarray [shape=(n_fixed_frames,), dtype=int]
        Fixed frame indices, flattened and sorted

    Raises
    ------
    ParameterError
        If `frames` contains negative values


def axis_sort(S, axis=-<NUM_LIT:1>, index=False, value=None):

if value is None:<EOL><INDENT>value = np.argmax<EOL><DEDENT>if S.ndim != <NUM_LIT:2>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>bin_idx = value(S, axis=np.mod(<NUM_LIT:1>-axis, S.ndim))<EOL>idx = np.argsort(bin_idx)<EOL>sort_slice = [slice(None)] * S.ndim<EOL>sort_slice[axis] = idx<EOL>if index:<EOL><INDENT>return S[tuple(sort_slice)], idx<EOL><DEDENT>else:<EOL><INDENT>return S[tuple(sort_slice)]<EOL><DEDENT>

Sort an array along its rows or columns.

    Examples
    --------
    Visualize NMF output for a spectrogram S

    >>> # Sort the columns of W by peak frequency bin
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> S = np.abs(librosa.stft(y))
    >>> W, H = librosa.decompose.decompose(S, n_components=32)
    >>> W_sort = librosa.util.axis_sort(W)

    Or sort by the lowest frequency bin

    >>> W_sort = librosa.util.axis_sort(W, value=np.argmin)

    Or sort the rows instead of the columns

    >>> W_sort_rows = librosa.util.axis_sort(W, axis=0)

    Get the sorting index also, and use it to permute the rows of H

    >>> W_sort, idx = librosa.util.axis_sort(W, index=True)
    >>> H_sort = H[idx, :]

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2, 2, 1)
    >>> librosa.display.specshow(librosa.amplitude_to_db(W, ref=np.max),
    ...                          y_axis='log')
    >>> plt.title('W')
    >>> plt.subplot(2, 2, 2)
    >>> librosa.display.specshow(H, x_axis='time')
    >>> plt.title('H')
    >>> plt.subplot(2, 2, 3)
    >>> librosa.display.specshow(librosa.amplitude_to_db(W_sort,
    ...                                                  ref=np.max),
    ...                          y_axis='log')
    >>> plt.title('W sorted')
    >>> plt.subplot(2, 2, 4)
    >>> librosa.display.specshow(H_sort, x_axis='time')
    >>> plt.title('H sorted')
    >>> plt.tight_layout()

    Parameters
    ----------
    S : np.ndarray [shape=(d, n)]
        Array to be sorted

    axis : int [scalar]
        The axis along which to compute the sorting values

        - `axis=0` to sort rows by peak column index
        - `axis=1` to sort columns by peak row index

    index : boolean [scalar]
        If true, returns the index array as well as the permuted data.

    value : function
        function to return the index corresponding to the sort order.
        Default: `np.argmax`.

    Returns
    -------
    S_sort : np.ndarray [shape=(d, n)]
        `S` with the columns or rows permuted in sorting order

    idx : np.ndarray (optional) [shape=(d,) or (n,)]
        If `index == True`, the sorting index used to permute `S`.
        Length of `idx` corresponds to the selected `axis`.

    Raises
    ------
    ParameterError
        If `S` does not have exactly 2 dimensions (`S.ndim != 2`)


@cache(level=<NUM_LIT>)<EOL>def normalize(S, norm=np.inf, axis=<NUM_LIT:0>, threshold=None, fill=None):

<EOL>if threshold is None:<EOL><INDENT>threshold = tiny(S)<EOL><DEDENT>elif threshold <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(threshold))<EOL><DEDENT>if fill not in [None, False, True]:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(fill))<EOL><DEDENT>if not np.all(np.isfinite(S)):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>mag = np.abs(S).astype(np.float)<EOL>fill_norm = <NUM_LIT:1><EOL>if norm == np.inf:<EOL><INDENT>length = np.max(mag, axis=axis, keepdims=True)<EOL><DEDENT>elif norm == -np.inf:<EOL><INDENT>length = np.min(mag, axis=axis, keepdims=True)<EOL><DEDENT>elif norm == <NUM_LIT:0>:<EOL><INDENT>if fill is True:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>length = np.sum(mag > <NUM_LIT:0>, axis=axis, keepdims=True, dtype=mag.dtype)<EOL><DEDENT>elif np.issubdtype(type(norm), np.number) and norm > <NUM_LIT:0>:<EOL><INDENT>length = np.sum(mag**norm, axis=axis, keepdims=True)**(<NUM_LIT:1.>/norm)<EOL>if axis is None:<EOL><INDENT>fill_norm = mag.size**(-<NUM_LIT:1.>/norm)<EOL><DEDENT>else:<EOL><INDENT>fill_norm = mag.shape[axis]**(-<NUM_LIT:1.>/norm)<EOL><DEDENT><DEDENT>elif norm is None:<EOL><INDENT>return S<EOL><DEDENT>else:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(repr(norm)))<EOL><DEDENT>small_idx = length < threshold<EOL>Snorm = np.empty_like(S)<EOL>if fill is None:<EOL><INDENT>length[small_idx] = <NUM_LIT:1.0><EOL>Snorm[:] = S / length<EOL><DEDENT>elif fill:<EOL><INDENT>length[small_idx] = np.nan<EOL>Snorm[:] = S / length<EOL>Snorm[np.isnan(Snorm)] = fill_norm<EOL><DEDENT>else:<EOL><INDENT>length[small_idx] = np.inf<EOL>Snorm[:] = S / length<EOL><DEDENT>return Snorm<EOL>

Normalize an array along a chosen axis.

    Given a norm (described below) and a target axis, the input
    array is scaled so that

        `norm(S, axis=axis) == 1`

    For example, `axis=0` normalizes each column of a 2-d array
    by aggregating over the rows (0-axis).
    Similarly, `axis=1` normalizes each row of a 2-d array.

    This function also supports thresholding small-norm slices:
    any slice (i.e., row or column) with norm below a specified
    `threshold` can be left un-normalized, set to all-zeros, or
    filled with uniform non-zero values that normalize to 1.

    Note: the semantics of this function differ from
    `scipy.linalg.norm` in two ways: multi-dimensional arrays
    are supported, but matrix-norms are not.

    Parameters
    ----------
    S : np.ndarray
        The matrix to normalize

    norm : {np.inf, -np.inf, 0, float > 0, None}
        - `np.inf`  : maximum absolute value
        - `-np.inf` : mininum absolute value
        - `0`    : number of non-zeros (the support)
        - float  : corresponding l_p norm
            See `scipy.linalg.norm` for details.
        - None : no normalization is performed

    axis : int [scalar]
        Axis along which to compute the norm.

    threshold : number > 0 [optional]
        Only the columns (or rows) with norm at least `threshold` are
        normalized.

        By default, the threshold is determined from
        the numerical precision of `S.dtype`.

    fill : None or bool
        If None, then columns (or rows) with norm below `threshold`
        are left as is.

        If False, then columns (rows) with norm below `threshold`
        are set to 0.

        If True, then columns (rows) with norm below `threshold`
        are filled uniformly such that the corresponding norm is 1.

        .. note:: `fill=True` is incompatible with `norm=0` because
            no uniform vector exists with l0 "norm" equal to 1.

    Returns
    -------
    S_norm : np.ndarray [shape=S.shape]
        Normalized array

    Raises
    ------
    ParameterError
        If `norm` is not among the valid types defined above

        If `S` is not finite

        If `fill=True` and `norm=0`

    See Also
    --------
    scipy.linalg.norm

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

    Examples
    --------
    >>> # Construct an example matrix
    >>> S = np.vander(np.arange(-2.0, 2.0))
    >>> S
    array([[-8.,  4., -2.,  1.],
           [-1.,  1., -1.,  1.],
           [ 0.,  0.,  0.,  1.],
           [ 1.,  1.,  1.,  1.]])
    >>> # Max (l-infinity)-normalize the columns
    >>> librosa.util.normalize(S)
    array([[-1.   ,  1.   , -1.   ,  1.   ],
           [-0.125,  0.25 , -0.5  ,  1.   ],
           [ 0.   ,  0.   ,  0.   ,  1.   ],
           [ 0.125,  0.25 ,  0.5  ,  1.   ]])
    >>> # Max (l-infinity)-normalize the rows
    >>> librosa.util.normalize(S, axis=1)
    array([[-1.   ,  0.5  , -0.25 ,  0.125],
           [-1.   ,  1.   , -1.   ,  1.   ],
           [ 0.   ,  0.   ,  0.   ,  1.   ],
           [ 1.   ,  1.   ,  1.   ,  1.   ]])
    >>> # l1-normalize the columns
    >>> librosa.util.normalize(S, norm=1)
    array([[-0.8  ,  0.667, -0.5  ,  0.25 ],
           [-0.1  ,  0.167, -0.25 ,  0.25 ],
           [ 0.   ,  0.   ,  0.   ,  0.25 ],
           [ 0.1  ,  0.167,  0.25 ,  0.25 ]])
    >>> # l2-normalize the columns
    >>> librosa.util.normalize(S, norm=2)
    array([[-0.985,  0.943, -0.816,  0.5  ],
           [-0.123,  0.236, -0.408,  0.5  ],
           [ 0.   ,  0.   ,  0.   ,  0.5  ],
           [ 0.123,  0.236,  0.408,  0.5  ]])

    >>> # Thresholding and filling
    >>> S[:, -1] = 1e-308
    >>> S
    array([[ -8.000e+000,   4.000e+000,  -2.000e+000,
              1.000e-308],
           [ -1.000e+000,   1.000e+000,  -1.000e+000,
              1.000e-308],
           [  0.000e+000,   0.000e+000,   0.000e+000,
              1.000e-308],
           [  1.000e+000,   1.000e+000,   1.000e+000,
              1.000e-308]])

    >>> # By default, small-norm columns are left untouched
    >>> librosa.util.normalize(S)
    array([[ -1.000e+000,   1.000e+000,  -1.000e+000,
              1.000e-308],
           [ -1.250e-001,   2.500e-001,  -5.000e-001,
              1.000e-308],
           [  0.000e+000,   0.000e+000,   0.000e+000,
              1.000e-308],
           [  1.250e-001,   2.500e-001,   5.000e-001,
              1.000e-308]])
    >>> # Small-norm columns can be zeroed out
    >>> librosa.util.normalize(S, fill=False)
    array([[-1.   ,  1.   , -1.   ,  0.   ],
           [-0.125,  0.25 , -0.5  ,  0.   ],
           [ 0.   ,  0.   ,  0.   ,  0.   ],
           [ 0.125,  0.25 ,  0.5  ,  0.   ]])
    >>> # Or set to constant with unit-norm
    >>> librosa.util.normalize(S, fill=True)
    array([[-1.   ,  1.   , -1.   ,  1.   ],
           [-0.125,  0.25 , -0.5  ,  1.   ],
           [ 0.   ,  0.   ,  0.   ,  1.   ],
           [ 0.125,  0.25 ,  0.5  ,  1.   ]])
    >>> # With an l1 norm instead of max-norm
    >>> librosa.util.normalize(S, norm=1, fill=True)
    array([[-0.8  ,  0.667, -0.5  ,  0.25 ],
           [-0.1  ,  0.167, -0.25 ,  0.25 ],
           [ 0.   ,  0.   ,  0.   ,  0.25 ],
           [ 0.1  ,  0.167,  0.25 ,  0.25 ]])


paddings = [(<NUM_LIT:0>, <NUM_LIT:0>)] * x.ndim<EOL>paddings[axis] = (<NUM_LIT:1>, <NUM_LIT:1>)<EOL>x_pad = np.pad(x, paddings, mode='<STR_LIT>')<EOL>inds1 = [slice(None)] * x.ndim<EOL>inds1[axis] = slice(<NUM_LIT:0>, -<NUM_LIT:2>)<EOL>inds2 = [slice(None)] * x.ndim<EOL>inds2[axis] = slice(<NUM_LIT:2>, x_pad.shape[axis])<EOL>return (x > x_pad[tuple(inds1)]) & (x >= x_pad[tuple(inds2)])<EOL>

Find local maxima in an array `x`.

    An element `x[i]` is considered a local maximum if the following
    conditions are met:

    - `x[i] > x[i-1]`
    - `x[i] >= x[i+1]`

    Note that the first condition is strict, and that the first element
    `x[0]` will never be considered as a local maximum.

    Examples
    --------
    >>> x = np.array([1, 0, 1, 2, -1, 0, -2, 1])
    >>> librosa.util.localmax(x)
    array([False, False, False,  True, False,  True, False,  True], dtype=bool)

    >>> # Two-dimensional example
    >>> x = np.array([[1,0,1], [2, -1, 0], [2, 1, 3]])
    >>> librosa.util.localmax(x, axis=0)
    array([[False, False, False],
           [ True, False, False],
           [False,  True,  True]], dtype=bool)
    >>> librosa.util.localmax(x, axis=1)
    array([[False, False,  True],
           [False, False,  True],
           [False, False,  True]], dtype=bool)

    Parameters
    ----------
    x     : np.ndarray [shape=(d1,d2,...)]
      input vector or array

    axis : int
      axis along which to compute local maximality

    Returns
    -------
    m     : np.ndarray [shape=x.shape, dtype=bool]
        indicator array of local maximality along `axis`


def peak_pick(x, pre_max, post_max, pre_avg, post_avg, delta, wait):

if pre_max < <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if pre_avg < <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if delta < <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if wait < <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if post_max <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if post_avg <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if x.ndim != <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>pre_max = valid_int(pre_max, cast=np.ceil)<EOL>post_max = valid_int(post_max, cast=np.ceil)<EOL>pre_avg = valid_int(pre_avg, cast=np.ceil)<EOL>post_avg = valid_int(post_avg, cast=np.ceil)<EOL>wait = valid_int(wait, cast=np.ceil)<EOL>max_length = pre_max + post_max<EOL>max_origin = np.ceil(<NUM_LIT:0.5> * (pre_max - post_max))<EOL>mov_max = scipy.ndimage.filters.maximum_filter1d(x, int(max_length),<EOL>mode='<STR_LIT>',<EOL>origin=int(max_origin),<EOL>cval=x.min())<EOL>avg_length = pre_avg + post_avg<EOL>avg_origin = np.ceil(<NUM_LIT:0.5> * (pre_avg - post_avg))<EOL>mov_avg = scipy.ndimage.filters.uniform_filter1d(x, int(avg_length),<EOL>mode='<STR_LIT>',<EOL>origin=int(avg_origin))<EOL>n = <NUM_LIT:0><EOL>while n - pre_avg < <NUM_LIT:0> and n < x.shape[<NUM_LIT:0>]:<EOL><INDENT>start = n - pre_avg<EOL>start = start if start > <NUM_LIT:0> else <NUM_LIT:0><EOL>mov_avg[n] = np.mean(x[start:n + post_avg])<EOL>n += <NUM_LIT:1><EOL><DEDENT>n = x.shape[<NUM_LIT:0>] - post_avg<EOL>n = n if n > <NUM_LIT:0> else <NUM_LIT:0><EOL>while n < x.shape[<NUM_LIT:0>]:<EOL><INDENT>start = n - pre_avg<EOL>start = start if start > <NUM_LIT:0> else <NUM_LIT:0><EOL>mov_avg[n] = np.mean(x[start:n + post_avg])<EOL>n += <NUM_LIT:1><EOL><DEDENT>detections = x * (x == mov_max)<EOL>detections = detections * (detections >= (mov_avg + delta))<EOL>peaks = []<EOL>last_onset = -np.inf<EOL>for i in np.nonzero(detections)[<NUM_LIT:0>]:<EOL><INDENT>if i > last_onset + wait:<EOL><INDENT>peaks.append(i)<EOL>last_onset = i<EOL><DEDENT><DEDENT>return np.array(peaks)<EOL>

Uses a flexible heuristic to pick peaks in a signal.

    A sample n is selected as an peak if the corresponding x[n]
    fulfills the following three conditions:

    1. `x[n] == max(x[n - pre_max:n + post_max])`
    2. `x[n] >= mean(x[n - pre_avg:n + post_avg]) + delta`
    3. `n - previous_n > wait`

    where `previous_n` is the last sample picked as a peak (greedily).

    This implementation is based on [1]_ and [2]_.

    .. [1] Boeck, Sebastian, Florian Krebs, and Markus Schedl.
        "Evaluating the Online Capabilities of Onset Detection Methods." ISMIR.
        2012.

    .. [2] https://github.com/CPJKU/onset_detection/blob/master/onset_program.py

    Parameters
    ----------
    x         : np.ndarray [shape=(n,)]
        input signal to peak picks from

    pre_max   : int >= 0 [scalar]
        number of samples before `n` over which max is computed

    post_max  : int >= 1 [scalar]
        number of samples after `n` over which max is computed

    pre_avg   : int >= 0 [scalar]
        number of samples before `n` over which mean is computed

    post_avg  : int >= 1 [scalar]
        number of samples after `n` over which mean is computed

    delta     : float >= 0 [scalar]
        threshold offset for mean

    wait      : int >= 0 [scalar]
        number of samples to wait after picking a peak

    Returns
    -------
    peaks     : np.ndarray [shape=(n_peaks,), dtype=int]
        indices of peaks in `x`

    Raises
    ------
    ParameterError
        If any input lies outside its defined range

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=15)
    >>> onset_env = librosa.onset.onset_strength(y=y, sr=sr,
    ...                                          hop_length=512,
    ...                                          aggregate=np.median)
    >>> peaks = librosa.util.peak_pick(onset_env, 3, 3, 3, 5, 0.5, 10)
    >>> peaks
    array([  4,  23,  73, 102, 142, 162, 182, 211, 261, 301, 320,
           331, 348, 368, 382, 396, 411, 431, 446, 461, 476, 491,
           510, 525, 536, 555, 570, 590, 609, 625, 639])

    >>> import matplotlib.pyplot as plt
    >>> times = librosa.frames_to_time(np.arange(len(onset_env)),
    ...                                sr=sr, hop_length=512)
    >>> plt.figure()
    >>> ax = plt.subplot(2, 1, 2)
    >>> D = librosa.stft(y)
    >>> librosa.display.specshow(librosa.amplitude_to_db(D, ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.subplot(2, 1, 1, sharex=ax)
    >>> plt.plot(times, onset_env, alpha=0.8, label='Onset strength')
    >>> plt.vlines(times[peaks], 0,
    ...            onset_env.max(), color='r', alpha=0.8,
    ...            label='Selected peaks')
    >>> plt.legend(frameon=True, framealpha=0.8)
    >>> plt.axis('tight')
    >>> plt.tight_layout()