def viterbi_discriminative(prob, transition, p_state=None, p_init=None, return_logp=False):

n_states, n_steps = prob.shape<EOL>if transition.shape != (n_states, n_states):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(transition.shape,<EOL>(n_states, n_states)))<EOL><DEDENT>if np.any(transition < <NUM_LIT:0>) or not np.allclose(transition.sum(axis=<NUM_LIT:1>), <NUM_LIT:1>):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if np.any(prob < <NUM_LIT:0>) or not np.allclose(prob.sum(axis=<NUM_LIT:0>), <NUM_LIT:1>):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>states = np.zeros(n_steps, dtype=int)<EOL>values = np.zeros((n_steps, n_states), dtype=float)<EOL>ptr = np.zeros((n_steps, n_states), dtype=int)<EOL>epsilon = np.finfo(prob.dtype).tiny<EOL>if p_state is None:<EOL><INDENT>p_state = np.empty(n_states)<EOL>p_state.fill(<NUM_LIT:1.>/n_states)<EOL><DEDENT>elif p_state.shape != (n_states,):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(p_state.shape))<EOL><DEDENT>elif np.any(p_state < <NUM_LIT:0>) or not np.allclose(p_state.sum(axis=-<NUM_LIT:1>), <NUM_LIT:1>):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(p_state))<EOL><DEDENT>log_trans = np.log(transition + epsilon)<EOL>log_marginal = np.log(p_state + epsilon)<EOL>log_prob = np.log(prob.T + epsilon) - log_marginal<EOL>if p_init is None:<EOL><INDENT>p_init = np.empty(n_states)<EOL>p_init.fill(<NUM_LIT:1.>/n_states)<EOL><DEDENT>elif np.any(p_init < <NUM_LIT:0>) or not np.allclose(p_init.sum(), <NUM_LIT:1>):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(p_init))<EOL><DEDENT>log_p_init = np.log(p_init + epsilon)<EOL>_viterbi(log_prob, log_trans, log_p_init, states, values, ptr)<EOL>if return_logp:<EOL><INDENT>return states, values[-<NUM_LIT:1>, states[-<NUM_LIT:1>]]<EOL><DEDENT>return states<EOL>

Viterbi decoding from discriminative state predictions.

    Given a sequence of conditional state predictions `prob[s, t]`,
    indicating the conditional likelihood of state `s` given the
    observation at time `t`, and a transition matrix `transition[i, j]`
    which encodes the conditional probability of moving from state `i`
    to state `j`, the Viterbi algorithm computes the most likely sequence
    of states from the observations.

    This implementation uses the standard Viterbi decoding algorithm
    for observation likelihood sequences, under the assumption that
    `P[Obs(t) | State(t) = s]` is proportional to
    `P[State(t) = s | Obs(t)] / P[State(t) = s]`, where the denominator
    is the marginal probability of state `s` occurring as given by `p_state`.

    Parameters
    ----------
    prob : np.ndarray [shape=(n_states, n_steps), non-negative]
        `prob[s, t]` is the probability of state `s` conditional on
        the observation at time `t`.
        Must be non-negative and sum to 1 along each column.

    transition : np.ndarray [shape=(n_states, n_states), non-negative]
        `transition[i, j]` is the probability of a transition from i->j.
        Each row must sum to 1.

    p_state : np.ndarray [shape=(n_states,)]
        Optional: marginal probability distribution over states,
        must be non-negative and sum to 1.
        If not provided, a uniform distribution is assumed.

    p_init : np.ndarray [shape=(n_states,)]
        Optional: initial state distribution.
        If not provided, it is assumed to be uniform.

    return_logp : bool
        If `True`, return the log-likelihood of the state sequence.

    Returns
    -------
    Either `states` or `(states, logp)`:

    states : np.ndarray [shape=(n_steps,)]
        The most likely state sequence.

    logp : scalar [float]
        If `return_logp=True`, the log probability of `states` given
        the observations.

    See Also
    --------
    viterbi : Viterbi decoding from observation likelihoods
    viterbi_binary: Viterbi decoding for multi-label, conditional state likelihoods

    Examples
    --------
    This example constructs a simple, template-based discriminative chord estimator,
    using CENS chroma as input features.

    .. note:: this chord model is not accurate enough to use in practice. It is only
            intended to demonstrate how to use discriminative Viterbi decoding.

    >>> # Create templates for major, minor, and no-chord qualities
    >>> maj_template = np.array([1,0,0, 0,1,0, 0,1,0, 0,0,0])
    >>> min_template = np.array([1,0,0, 1,0,0, 0,1,0, 0,0,0])
    >>> N_template   = np.array([1,1,1, 1,1,1, 1,1,1, 1,1,1.]) / 4.
    >>> # Generate the weighting matrix that maps chroma to labels
    >>> weights = np.zeros((25, 12), dtype=float)
    >>> labels = ['C:maj', 'C#:maj', 'D:maj', 'D#:maj', 'E:maj', 'F:maj',
    ...           'F#:maj', 'G:maj', 'G#:maj', 'A:maj', 'A#:maj', 'B:maj',
    ...           'C:min', 'C#:min', 'D:min', 'D#:min', 'E:min', 'F:min',
    ...           'F#:min', 'G:min', 'G#:min', 'A:min', 'A#:min', 'B:min',
    ...           'N']
    >>> for c in range(12):
    ...     weights[c, :] = np.roll(maj_template, c) # c:maj
    ...     weights[c + 12, :] = np.roll(min_template, c)  # c:min
    >>> weights[-1] = N_template  # the last row is the no-chord class
    >>> # Make a self-loop transition matrix over 25 states
    >>> trans = librosa.sequence.transition_loop(25, 0.9)

    >>> # Load in audio and make features
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> chroma = librosa.feature.chroma_cens(y=y, sr=sr, bins_per_octave=36)
    >>> # Map chroma (observations) to class (state) likelihoods
    >>> probs = np.exp(weights.dot(chroma))  # P[class | chroma] proportional to exp(template' chroma)
    >>> probs /= probs.sum(axis=0, keepdims=True)  # probabilities must sum to 1 in each column
    >>> # Compute independent frame-wise estimates
    >>> chords_ind = np.argmax(probs, axis=0)
    >>> # And viterbi estimates
    >>> chords_vit = librosa.sequence.viterbi_discriminative(probs, trans)

    >>> # Plot the features and prediction map
    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(10, 6))
    >>> plt.subplot(2,1,1)
    >>> librosa.display.specshow(chroma, x_axis='time', y_axis='chroma')
    >>> plt.colorbar()
    >>> plt.subplot(2,1,2)
    >>> librosa.display.specshow(weights, x_axis='chroma')
    >>> plt.yticks(np.arange(25) + 0.5, labels)
    >>> plt.ylabel('Chord')
    >>> plt.colorbar()
    >>> plt.tight_layout()

    >>> # And plot the results
    >>> plt.figure(figsize=(10, 4))
    >>> librosa.display.specshow(probs, x_axis='time', cmap='gray')
    >>> plt.colorbar()
    >>> times = librosa.frames_to_time(np.arange(len(chords_vit)))
    >>> plt.scatter(times, chords_ind + 0.75, color='lime', alpha=0.5, marker='+', s=15, label='Independent')
    >>> plt.scatter(times, chords_vit + 0.25, color='deeppink', alpha=0.5, marker='o', s=15, label='Viterbi')
    >>> plt.yticks(0.5 + np.unique(chords_vit), [labels[i] for i in np.unique(chords_vit)], va='center')
    >>> plt.legend(loc='best')
    >>> plt.tight_layout()


if not isinstance(n_states, int) or n_states <= <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>transition = np.empty((n_states, n_states), dtype=np.float)<EOL>prob = np.asarray(prob, dtype=np.float)<EOL>if prob.ndim == <NUM_LIT:0>:<EOL><INDENT>prob = np.tile(prob, n_states)<EOL><DEDENT>if prob.shape != (n_states,):<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(prob, n_states))<EOL><DEDENT>if np.any(prob < <NUM_LIT:0>) or np.any(prob > <NUM_LIT:1>):<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(prob))<EOL><DEDENT>for i, prob_i in enumerate(prob):<EOL><INDENT>transition[i] = (<NUM_LIT:1.> - prob_i) / (n_states - <NUM_LIT:1>)<EOL>transition[i, i] = prob_i<EOL><DEDENT>return transition<EOL>

Construct a self-loop transition matrix over `n_states`.

    The transition matrix will have the following properties:

        - `transition[i, i] = p` for all i
        - `transition[i, j] = (1 - p) / (n_states - 1)` for all `j != i`

    This type of transition matrix is appropriate when states tend to be
    locally stable, and there is no additional structure between different
    states.  This is primarily useful for de-noising frame-wise predictions.

    Parameters
    ----------
    n_states : int > 1
        The number of states

    prob : float in [0, 1] or iterable, length=n_states
        If a scalar, this is the probability of a self-transition.

        If a vector of length `n_states`, `p[i]` is the probability of state `i`'s self-transition.

    Returns
    -------
    transition : np.ndarray [shape=(n_states, n_states)]
        The transition matrix

    Examples
    --------
    >>> librosa.sequence.transition_loop(3, 0.5)
    array([[0.5 , 0.25, 0.25],
           [0.25, 0.5 , 0.25],
           [0.25, 0.25, 0.5 ]])

    >>> librosa.sequence.transition_loop(3, [0.8, 0.5, 0.25])
    array([[0.8  , 0.1  , 0.1  ],
           [0.25 , 0.5  , 0.25 ],
           [0.375, 0.375, 0.25 ]])


@jit(nopython=True, cache=True)<EOL>def _viterbi(log_prob, log_trans, log_p_init, state, value, ptr):

n_steps, n_states = log_prob.shape<EOL>value[<NUM_LIT:0>] = log_prob[<NUM_LIT:0>] + log_p_init<EOL>for t in range(<NUM_LIT:1>, n_steps):<EOL><INDENT>trans_out = value[t - <NUM_LIT:1>] + log_trans.T<EOL>for j in range(n_states):<EOL><INDENT>ptr[t, j] = np.argmax(trans_out[j])<EOL>value[t, j] = log_prob[t, j] + trans_out[j, ptr[t][j]]<EOL><DEDENT><DEDENT>state[-<NUM_LIT:1>] = np.argmax(value[-<NUM_LIT:1>])<EOL>for t in range(n_steps - <NUM_LIT:2>, -<NUM_LIT:1>, -<NUM_LIT:1>):<EOL><INDENT>state[t] = ptr[t+<NUM_LIT:1>, state[t+<NUM_LIT:1>]]<EOL><DEDENT>

Core Viterbi algorithm.

    This is intended for internal use only.

    Parameters
    ----------
    log_prob : np.ndarray [shape=(T, m)]
        `log_prob[t, s]` is the conditional log-likelihood
        log P[X = X(t) | State(t) = s]

    log_trans : np.ndarray [shape=(m, m)]
        The log transition matrix
        `log_trans[i, j]` = log P[State(t+1) = j | State(t) = i]

    log_p_init : np.ndarray [shape=(m,)]
        log of the initial state distribution

    state : np.ndarray [shape=(T,), dtype=int]
        Pre-allocated state index array

    value : np.ndarray [shape=(T, m)] float
        Pre-allocated value array

    ptr : np.ndarray [shape=(T, m), dtype=int]
        Pre-allocated pointer array

    Returns
    -------
    None
        All computations are performed in-place on `state, value, ptr`.


def dtw(X=None, Y=None, C=None, metric='<STR_LIT>', step_sizes_sigma=None,<EOL>weights_add=None, weights_mul=None, subseq=False, backtrack=True,<EOL>global_constraints=False, band_rad=<NUM_LIT>):

<EOL>if step_sizes_sigma is None:<EOL><INDENT>step_sizes_sigma = np.array([[<NUM_LIT:1>, <NUM_LIT:1>], [<NUM_LIT:0>, <NUM_LIT:1>], [<NUM_LIT:1>, <NUM_LIT:0>]])<EOL><DEDENT>if weights_add is None:<EOL><INDENT>weights_add = np.zeros(len(step_sizes_sigma))<EOL><DEDENT>if weights_mul is None:<EOL><INDENT>weights_mul = np.ones(len(step_sizes_sigma))<EOL><DEDENT>if len(step_sizes_sigma) != len(weights_add):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if len(step_sizes_sigma) != len(weights_mul):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if C is None and (X is None or Y is None):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if C is not None and (X is not None or Y is not None):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if C is None:<EOL><INDENT>X = np.atleast_2d(X)<EOL>Y = np.atleast_2d(Y)<EOL>try:<EOL><INDENT>C = cdist(X.T, Y.T, metric=metric)<EOL><DEDENT>except ValueError:<EOL><INDENT>msg = ('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL>six.reraise(ParameterError, ParameterError(msg))<EOL><DEDENT>if subseq and (X.shape[<NUM_LIT:1>] > Y.shape[<NUM_LIT:1>]):<EOL><INDENT>C = C.T<EOL><DEDENT><DEDENT>C = np.atleast_2d(C)<EOL>if np.array_equal(step_sizes_sigma, np.array([[<NUM_LIT:1>, <NUM_LIT:1>]])) and (C.shape[<NUM_LIT:0>] > C.shape[<NUM_LIT:1>]):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>max_0 = step_sizes_sigma[:, <NUM_LIT:0>].max()<EOL>max_1 = step_sizes_sigma[:, <NUM_LIT:1>].max()<EOL>if global_constraints:<EOL><INDENT>fill_off_diagonal(C, band_rad, value=np.inf)<EOL><DEDENT>D = np.ones(C.shape + np.array([max_0, max_1])) * np.inf<EOL>D[max_0, max_1] = C[<NUM_LIT:0>, <NUM_LIT:0>]<EOL>if subseq:<EOL><INDENT>D[max_0, max_1:] = C[<NUM_LIT:0>, :]<EOL><DEDENT>D_steps = -<NUM_LIT:1> * np.ones(D.shape, dtype=np.int)<EOL>D, D_steps = __dtw_calc_accu_cost(C, D, D_steps,<EOL>step_sizes_sigma,<EOL>weights_mul, weights_add,<EOL>max_0, max_1)<EOL>D = D[max_0:, max_1:]<EOL>D_steps = D_steps[max_0:, max_1:]<EOL>if backtrack:<EOL><INDENT>if subseq:<EOL><INDENT>wp_end_idx = np.argmin(D[-<NUM_LIT:1>, :]) + <NUM_LIT:1><EOL>wp = __dtw_backtracking(D_steps[:, :wp_end_idx], step_sizes_sigma)<EOL><DEDENT>else:<EOL><INDENT>wp = __dtw_backtracking(D_steps, step_sizes_sigma)<EOL><DEDENT>wp = np.asarray(wp, dtype=int)<EOL>if subseq and (X.shape[<NUM_LIT:1>] > Y.shape[<NUM_LIT:1>]):<EOL><INDENT>wp = np.fliplr(wp)<EOL><DEDENT>return D, wp<EOL><DEDENT>else:<EOL><INDENT>return D<EOL><DEDENT>

Dynamic time warping (DTW).

    This function performs a DTW and path backtracking on two sequences.
    We follow the nomenclature and algorithmic approach as described in [1]_.

    .. [1] Meinard Mueller
           Fundamentals of Music Processing — Audio, Analysis, Algorithms, Applications
           Springer Verlag, ISBN: 978-3-319-21944-8, 2015.

    Parameters
    ----------
    X : np.ndarray [shape=(K, N)]
        audio feature matrix (e.g., chroma features)

    Y : np.ndarray [shape=(K, M)]
        audio feature matrix (e.g., chroma features)

    C : np.ndarray [shape=(N, M)]
        Precomputed distance matrix. If supplied, X and Y must not be supplied and
        ``metric`` will be ignored.

    metric : str
        Identifier for the cost-function as documented
        in `scipy.spatial.cdist()`

    step_sizes_sigma : np.ndarray [shape=[n, 2]]
        Specifies allowed step sizes as used by the dtw.

    weights_add : np.ndarray [shape=[n, ]]
        Additive weights to penalize certain step sizes.

    weights_mul : np.ndarray [shape=[n, ]]
        Multiplicative weights to penalize certain step sizes.

    subseq : binary
        Enable subsequence DTW, e.g., for retrieval tasks.

    backtrack : binary
        Enable backtracking in accumulated cost matrix.

    global_constraints : binary
        Applies global constraints to the cost matrix ``C`` (Sakoe-Chiba band).

    band_rad : float
        The Sakoe-Chiba band radius (1/2 of the width) will be
        ``int(radius*min(C.shape))``.

    Returns
    -------
    D : np.ndarray [shape=(N,M)]
        accumulated cost matrix.
        D[N,M] is the total alignment cost.
        When doing subsequence DTW, D[N,:] indicates a matching function.

    wp : np.ndarray [shape=(N,2)]
        Warping path with index pairs.
        Each row of the array contains an index pair n,m).
        Only returned when ``backtrack`` is True.

    Raises
    ------
    ParameterError
        If you are doing diagonal matching and Y is shorter than X or if an incompatible
        combination of X, Y, and C are supplied.
        If your input dimensions are incompatible.

    Examples
    --------
    >>> import numpy as np
    >>> import matplotlib.pyplot as plt
    >>> y, sr = librosa.load(librosa.util.example_audio_file(), offset=10, duration=15)
    >>> X = librosa.feature.chroma_cens(y=y, sr=sr)
    >>> noise = np.random.rand(X.shape[0], 200)
    >>> Y = np.concatenate((noise, noise, X, noise), axis=1)
    >>> D, wp = librosa.sequence.dtw(X, Y, subseq=True)
    >>> plt.subplot(2, 1, 1)
    >>> librosa.display.specshow(D, x_axis='frames', y_axis='frames')
    >>> plt.title('Database excerpt')
    >>> plt.plot(wp[:, 1], wp[:, 0], label='Optimal path', color='y')
    >>> plt.legend()
    >>> plt.subplot(2, 1, 2)
    >>> plt.plot(D[-1, :] / wp.shape[0])
    >>> plt.xlim([0, Y.shape[1]])
    >>> plt.ylim([0, 2])
    >>> plt.title('Matching cost function')
    >>> plt.tight_layout()


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

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


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


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

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


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

Helper to set the current image in pyplot mode.

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


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

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


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


def waveplot(y, sr=<NUM_LIT>, max_points=<NUM_LIT>, x_axis='<STR_LIT:time>', offset=<NUM_LIT:0.0>,<EOL>max_sr=<NUM_LIT:1000>, ax=None, **kwargs):

util.valid_audio(y, mono=False)<EOL>if not (isinstance(max_sr, int) and max_sr > <NUM_LIT:0>):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>target_sr = sr<EOL>hop_length = <NUM_LIT:1><EOL>if max_points is not None:<EOL><INDENT>if max_points <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if max_points < y.shape[-<NUM_LIT:1>]:<EOL><INDENT>target_sr = min(max_sr, (sr * y.shape[-<NUM_LIT:1>]) // max_points)<EOL><DEDENT>hop_length = sr // target_sr<EOL>if y.ndim == <NUM_LIT:1>:<EOL><INDENT>y = __envelope(y, hop_length)<EOL><DEDENT>else:<EOL><INDENT>y = np.vstack([__envelope(_, hop_length) for _ in y])<EOL><DEDENT><DEDENT>if y.ndim > <NUM_LIT:1>:<EOL><INDENT>y_top = y[<NUM_LIT:0>]<EOL>y_bottom = -y[<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>y_top = y<EOL>y_bottom = -y<EOL><DEDENT>axes = __check_axes(ax)<EOL>kwargs.setdefault('<STR_LIT>', next(axes._get_lines.prop_cycler)['<STR_LIT>'])<EOL>locs = offset + core.frames_to_time(np.arange(len(y_top)),<EOL>sr=sr,<EOL>hop_length=hop_length)<EOL>out = axes.fill_between(locs, y_bottom, y_top, **kwargs)<EOL>axes.set_xlim([locs.min(), locs.max()])<EOL>if x_axis == '<STR_LIT:time>':<EOL><INDENT>axes.xaxis.set_major_formatter(TimeFormatter(lag=False))<EOL>axes.xaxis.set_label_text('<STR_LIT>')<EOL><DEDENT>elif x_axis is None or x_axis in ['<STR_LIT>', '<STR_LIT:none>']:<EOL><INDENT>axes.set_xticks([])<EOL><DEDENT>else:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(x_axis))<EOL><DEDENT>return out<EOL>

Plot the amplitude envelope of a waveform.

    If `y` is monophonic, a filled curve is drawn between `[-abs(y), abs(y)]`.

    If `y` is stereo, the curve is drawn between `[-abs(y[1]), abs(y[0])]`,
    so that the left and right channels are drawn above and below the axis,
    respectively.

    Long signals (`duration >= max_points`) are down-sampled to at
    most `max_sr` before plotting.

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

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

    max_points : postive number or None
        Maximum number of time-points to plot: if `max_points` exceeds
        the duration of `y`, then `y` is downsampled.

        If `None`, no downsampling is performed.

    x_axis : str {'time', 'off', 'none'} or None
        If 'time', the x-axis is given time tick-marks.

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

    offset : float
        Horizontal offset (in seconds) to start the waveform plot

    max_sr : number > 0 [scalar]
        Maximum sampling rate for the visualization

    kwargs
        Additional keyword arguments to `matplotlib.pyplot.fill_between`

    Returns
    -------
    pc : matplotlib.collections.PolyCollection
        The PolyCollection created by `fill_between`.

    See also
    --------
    librosa.core.resample
    matplotlib.pyplot.fill_between

    Examples
    --------
    Plot a monophonic waveform

    >>> import matplotlib.pyplot as plt
    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=10)
    >>> plt.figure()
    >>> plt.subplot(3, 1, 1)
    >>> librosa.display.waveplot(y, sr=sr)
    >>> plt.title('Monophonic')

    Or a stereo waveform

    >>> y, sr = librosa.load(librosa.util.example_audio_file(),
    ...                      mono=False, duration=10)
    >>> plt.subplot(3, 1, 2)
    >>> librosa.display.waveplot(y, sr=sr)
    >>> plt.title('Stereo')

    Or harmonic and percussive components with transparency

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=10)
    >>> y_harm, y_perc = librosa.effects.hpss(y)
    >>> plt.subplot(3, 1, 3)
    >>> librosa.display.waveplot(y_harm, sr=sr, alpha=0.25)
    >>> librosa.display.waveplot(y_perc, sr=sr, color='r', alpha=0.5)
    >>> plt.title('Harmonic + Percussive')
    >>> plt.tight_layout()


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

Linear Prediction Coefficients via Burg's method

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

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

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

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

    order : int > 0
        Order of the linear filter

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

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

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

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

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

    Compute LP coefficients, and plot LP estimate of original series

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    Display click waveform next to the spectrogram

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

Load an audio buffer using audioread.

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


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

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

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

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

    fmax : float > 0
        final frequency

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

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

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

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

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

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

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

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

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

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

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

    Display spectrogram for both exponential and linear chirps

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


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

Force an audio signal down to mono.

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

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

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

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


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

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

Compute the energy at harmonics of time-frequency representation.

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

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

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

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

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

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

    axis : int
        The axis along which to compute harmonics

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

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

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

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

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

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

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

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


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

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

Populate a harmonic tensor from a time-frequency representation.

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

    X : np.ndarray
        The input energy

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

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

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

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

    axis : int
        The axis along which to compute harmonics

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Set `sparsity=0` to disable sparsification.

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

    pad_mode : string
        Padding mode for centered frame analysis.

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

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

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

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

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


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

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

Compute the filter response with a target STFT hop.


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

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

    Returns 0 for non-positive integers.


def 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])


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

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

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

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

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

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

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


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

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

Converts frame indices to audio sample indices.

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

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

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

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

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

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


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

Convert one or more note names to frequency (Hz)

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

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

    kwargs : additional keyword arguments
        Additional parameters to `note_to_midi`

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

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


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

Convert octaves numbers to frequencies.

    Octaves are counted relative to A.

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

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

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

    See Also
    --------
    hz_to_octs


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

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

Converts frame counts to time (seconds).

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

    sr         : number > 0 [scalar]
        audio sampling rate

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

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

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

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

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


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

Convert timestamps (in seconds) to sample indices.

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

    sr : number > 0
        Sampling rate

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

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

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


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

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

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

    The leading note name is case-insensitive.

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

    Get multiple notes with cent deviation

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

    Get multiple notes, but suppress octave labels

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


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: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()


@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()


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


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`


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 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()


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


@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 ]])


def buf_to_float(x, n_bytes=<NUM_LIT:2>, dtype=np.float32):

<EOL>scale = <NUM_LIT:1.>/float(<NUM_LIT:1> << ((<NUM_LIT:8> * n_bytes) - <NUM_LIT:1>))<EOL>fmt = '<STR_LIT>'.format(n_bytes)<EOL>return scale * np.frombuffer(x, fmt).astype(dtype)<EOL>

Convert an integer buffer to floating point values.
    This is primarily useful when loading integer-valued wav data
    into numpy arrays.

    See Also
    --------
    buf_to_float

    Parameters
    ----------
    x : np.ndarray [dtype=int]
        The integer-valued data buffer

    n_bytes : int [1, 2, 4]
        The number of bytes per sample in `x`

    dtype : numeric type
        The target output type (default: 32-bit float)

    Returns
    -------
    x_float : np.ndarray [dtype=float]
        The input data buffer cast to floating point


@numba.jit(nopython=True, cache=True)<EOL>def __match_intervals(intervals_from, intervals_to, strict=True):

<EOL>start_index = np.argsort(intervals_to[:, <NUM_LIT:0>])<EOL>end_index = np.argsort(intervals_to[:, <NUM_LIT:1>])<EOL>start_sorted = intervals_to[start_index, <NUM_LIT:0>]<EOL>end_sorted = intervals_to[end_index, <NUM_LIT:1>]<EOL>search_ends = np.searchsorted(start_sorted, intervals_from[:, <NUM_LIT:1>], side='<STR_LIT:right>')<EOL>search_starts = np.searchsorted(end_sorted, intervals_from[:, <NUM_LIT:0>], side='<STR_LIT:left>')<EOL>output = np.empty(len(intervals_from), dtype=numba.uint32)<EOL>for i in range(len(intervals_from)):<EOL><INDENT>query = intervals_from[i]<EOL>after_query = search_ends[i]<EOL>before_query = search_starts[i]<EOL>candidates = set(start_index[:after_query]) & set(end_index[before_query:])<EOL>if len(candidates) > <NUM_LIT:0>:<EOL><INDENT>output[i] = __match_interval_overlaps(query, intervals_to, candidates)<EOL><DEDENT>elif strict:<EOL><INDENT>raise ParameterError<EOL><DEDENT>else:<EOL><INDENT>dist_before = np.inf<EOL>dist_after = np.inf<EOL>if search_starts[i] > <NUM_LIT:0>:<EOL><INDENT>dist_before = query[<NUM_LIT:0>] - end_sorted[search_starts[i]-<NUM_LIT:1>]<EOL><DEDENT>if search_ends[i] + <NUM_LIT:1> < len(intervals_to):<EOL><INDENT>dist_after = start_sorted[search_ends[i]+<NUM_LIT:1>] - query[<NUM_LIT:1>]<EOL><DEDENT>if dist_before < dist_after:<EOL><INDENT>output[i] = end_index[search_starts[i]-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>output[i] = start_index[search_ends[i]+<NUM_LIT:1>]<EOL><DEDENT><DEDENT><DEDENT>return output<EOL>

Numba-accelerated interval matching algorithm.