if x.ndim == <NUM_LIT:1>:<EOL><INDENT>x = x.reshape((<NUM_LIT:1>, -<NUM_LIT:1>))<EOL><DEDENT>elif x.ndim > <NUM_LIT:2>:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(x.shape))<EOL><DEDENT>if not <NUM_LIT:0.0> <= quantile < <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(quantile))<EOL><DEDENT>x_sparse = scipy.sparse.lil_matrix(x.shape, dtype=x.dtype)<EOL>mags = np.abs(x)<EOL>norms = np.sum(mags, axis=<NUM_LIT:1>, keepdims=True)<EOL>mag_sort = np.sort(mags, axis=<NUM_LIT:1>)<EOL>cumulative_mag = np.cumsum(mag_sort / norms, axis=<NUM_LIT:1>)<EOL>threshold_idx = np.argmin(cumulative_mag < quantile, axis=<NUM_LIT:1>)<EOL>for i, j in enumerate(threshold_idx):<EOL><INDENT>idx = np.where(mags[i] >= mag_sort[i, j])<EOL>x_sparse[i, idx] = x[i, idx]<EOL><DEDENT>return x_sparse.tocsr()<EOL>

Return a row-sparse matrix approximating the input `x`.

Parameters
----------
x : np.ndarray [ndim <= 2]
    The input matrix to sparsify.

quantile : float in [0, 1.0)
    Percentage of magnitude to discard in each row of `x`

Returns
-------
x_sparse : `scipy.sparse.csr_matrix` [shape=x.shape]
    Row-sparsified approximation of `x`

    If `x.ndim == 1`, then `x` is interpreted as a row vector,
    and `x_sparse.shape == (1, len(x))`.

Raises
------
ParameterError
    If `x.ndim > 2`

    If `quantile` lies outside `[0, 1.0)`

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

Examples
--------
>>> # Construct a Hann window to sparsify
>>> x = scipy.signal.hann(32)
>>> x
array([ 0.   ,  0.01 ,  0.041,  0.09 ,  0.156,  0.236,  0.326,
        0.424,  0.525,  0.625,  0.72 ,  0.806,  0.879,  0.937,
        0.977,  0.997,  0.997,  0.977,  0.937,  0.879,  0.806,
        0.72 ,  0.625,  0.525,  0.424,  0.326,  0.236,  0.156,
        0.09 ,  0.041,  0.01 ,  0.   ])
>>> # Discard the bottom percentile
>>> x_sparse = librosa.util.sparsify_rows(x, quantile=0.01)
>>> x_sparse
<1x32 sparse matrix of type '<type 'numpy.float64'>'
    with 26 stored elements in Compressed Sparse Row format>
>>> x_sparse.todense()
matrix([[ 0.   ,  0.   ,  0.   ,  0.09 ,  0.156,  0.236,  0.326,
          0.424,  0.525,  0.625,  0.72 ,  0.806,  0.879,  0.937,
          0.977,  0.997,  0.997,  0.977,  0.937,  0.879,  0.806,
          0.72 ,  0.625,  0.525,  0.424,  0.326,  0.236,  0.156,
          0.09 ,  0.   ,  0.   ,  0.   ]])
>>> # Discard up to the bottom 10th percentile
>>> x_sparse = librosa.util.sparsify_rows(x, quantile=0.1)
>>> x_sparse
<1x32 sparse matrix of type '<type 'numpy.float64'>'
    with 20 stored elements in Compressed Sparse Row format>
>>> x_sparse.todense()
matrix([[ 0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.   ,  0.326,
          0.424,  0.525,  0.625,  0.72 ,  0.806,  0.879,  0.937,
          0.977,  0.997,  0.997,  0.977,  0.937,  0.879,  0.806,
          0.72 ,  0.625,  0.525,  0.424,  0.326,  0.   ,  0.   ,
          0.   ,  0.   ,  0.   ,  0.   ]])


def roll_sparse(x, shift, axis=<NUM_LIT:0>):

if not scipy.sparse.isspmatrix(x):<EOL><INDENT>return np.roll(x, shift, axis=axis)<EOL><DEDENT>if axis not in [<NUM_LIT:0>, <NUM_LIT:1>, -<NUM_LIT:1>]:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>shift = np.mod(shift, x.shape[axis])<EOL>if shift == <NUM_LIT:0>:<EOL><INDENT>return x.copy()<EOL><DEDENT>fmt = x.format<EOL>if axis == <NUM_LIT:0>:<EOL><INDENT>x = x.tocsc()<EOL><DEDENT>elif axis in (-<NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>x = x.tocsr()<EOL><DEDENT>x_r = scipy.sparse.lil_matrix(x.shape, dtype=x.dtype)<EOL>idx_in = [slice(None)] * x.ndim<EOL>idx_out = [slice(None)] * x_r.ndim<EOL>idx_in[axis] = slice(<NUM_LIT:0>, -shift)<EOL>idx_out[axis] = slice(shift, None)<EOL>x_r[tuple(idx_out)] = x[tuple(idx_in)]<EOL>idx_out[axis] = slice(<NUM_LIT:0>, shift)<EOL>idx_in[axis] = slice(-shift, None)<EOL>x_r[tuple(idx_out)] = x[tuple(idx_in)]<EOL>return x_r.asformat(fmt)<EOL>

Sparse matrix roll

    This operation is equivalent to ``numpy.roll``, but operates on sparse matrices.

    Parameters
    ----------
    x : scipy.sparse.spmatrix or np.ndarray
        The sparse matrix input

    shift : int
        The number of positions to roll the specified axis

    axis : (0, 1, -1)
        The axis along which to roll.

    Returns
    -------
    x_rolled : same type as `x`
        The rolled matrix, with the same format as `x`

    See Also
    --------
    numpy.roll

    Examples
    --------
    >>> # Generate a random sparse binary matrix
    >>> X = scipy.sparse.lil_matrix(np.random.randint(0, 2, size=(5,5)))
    >>> X_roll = roll_sparse(X, 2, axis=0)  # Roll by 2 on the first axis
    >>> X_dense_r = roll_sparse(X.toarray(), 2, axis=0)  # Equivalent dense roll
    >>> np.allclose(X_roll, X_dense_r.toarray())
    True


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


def index_to_slice(idx, idx_min=None, idx_max=None, step=None, pad=True):

<EOL>idx_fixed = fix_frames(idx, idx_min, idx_max, pad=pad)<EOL>return [slice(start, end, step) for (start, end) in zip(idx_fixed, idx_fixed[<NUM_LIT:1>:])]<EOL>

Generate a slice array from an index array.

    Parameters
    ----------
    idx : list-like
        Array of index boundaries

    idx_min : None or int
    idx_max : None or int
        Minimum and maximum allowed indices

    step : None or int
        Step size for each slice.  If `None`, then the default
        step of 1 is used.

    pad : boolean
        If `True`, pad `idx` to span the range `idx_min:idx_max`.

    Returns
    -------
    slices : list of slice
        ``slices[i] = slice(idx[i], idx[i+1], step)``
        Additional slice objects may be added at the beginning or end,
        depending on whether ``pad==True`` and the supplied values for
        `idx_min` and `idx_max`.

    See Also
    --------
    fix_frames

    Examples
    --------
    >>> # Generate slices from spaced indices
    >>> librosa.util.index_to_slice(np.arange(20, 100, 15))
    [slice(20, 35, None), slice(35, 50, None), slice(50, 65, None), slice(65, 80, None),
     slice(80, 95, None)]
    >>> # Pad to span the range (0, 100)
    >>> librosa.util.index_to_slice(np.arange(20, 100, 15),
    ...                             idx_min=0, idx_max=100)
    [slice(0, 20, None), slice(20, 35, None), slice(35, 50, None), slice(50, 65, None),
     slice(65, 80, None), slice(80, 95, None), slice(95, 100, None)]
    >>> # Use a step of 5 for each slice
    >>> librosa.util.index_to_slice(np.arange(20, 100, 15),
    ...                             idx_min=0, idx_max=100, step=5)
    [slice(0, 20, 5), slice(20, 35, 5), slice(35, 50, 5), slice(50, 65, 5), slice(65, 80, 5),
     slice(80, 95, 5), slice(95, 100, 5)]


@cache(level=<NUM_LIT>)<EOL>def sync(data, idx, aggregate=None, pad=True, axis=-<NUM_LIT:1>):

if aggregate is None:<EOL><INDENT>aggregate = np.mean<EOL><DEDENT>shape = list(data.shape)<EOL>if np.all([isinstance(_, slice) for _ in idx]):<EOL><INDENT>slices = idx<EOL><DEDENT>elif np.all([np.issubdtype(type(_), np.integer) for _ in idx]):<EOL><INDENT>slices = index_to_slice(np.asarray(idx), <NUM_LIT:0>, shape[axis], pad=pad)<EOL><DEDENT>else:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(idx))<EOL><DEDENT>agg_shape = list(shape)<EOL>agg_shape[axis] = len(slices)<EOL>data_agg = np.empty(agg_shape, order='<STR_LIT:F>' if np.isfortran(data) else '<STR_LIT:C>', dtype=data.dtype)<EOL>idx_in = [slice(None)] * data.ndim<EOL>idx_agg = [slice(None)] * data_agg.ndim<EOL>for (i, segment) in enumerate(slices):<EOL><INDENT>idx_in[axis] = segment<EOL>idx_agg[axis] = i<EOL>data_agg[tuple(idx_agg)] = aggregate(data[tuple(idx_in)], axis=axis)<EOL><DEDENT>return data_agg<EOL>

Synchronous aggregation of a multi-dimensional array between boundaries

    .. note::
        In order to ensure total coverage, boundary points may be added
        to `idx`.

        If synchronizing a feature matrix against beat tracker output, ensure
        that frame index numbers are properly aligned and use the same hop length.

    Parameters
    ----------
    data      : np.ndarray
        multi-dimensional array of features

    idx : iterable of ints or slices
        Either an ordered array of boundary indices, or
        an iterable collection of slice objects.

    aggregate : function
        aggregation function (default: `np.mean`)

    pad : boolean
        If `True`, `idx` is padded to span the full range `[0, data.shape[axis]]`

    axis : int
        The axis along which to aggregate data

    Returns
    -------
    data_sync : ndarray
        `data_sync` will have the same dimension as `data`, except that the `axis`
        coordinate will be reduced according to `idx`.

        For example, a 2-dimensional `data` with `axis=-1` should satisfy

        `data_sync[:, i] = aggregate(data[:, idx[i-1]:idx[i]], axis=-1)`

    Raises
    ------
    ParameterError
        If the index set is not of consistent type (all slices or all integers)

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

    Examples
    --------
    Beat-synchronous CQT spectra

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr, trim=False)
    >>> C = np.abs(librosa.cqt(y=y, sr=sr))
    >>> beats = librosa.util.fix_frames(beats, x_max=C.shape[1])

    By default, use mean aggregation

    >>> C_avg = librosa.util.sync(C, beats)

    Use median-aggregation instead of mean

    >>> C_med = librosa.util.sync(C, beats,
    ...                             aggregate=np.median)

    Or sub-beat synchronization

    >>> sub_beats = librosa.segment.subsegment(C, beats)
    >>> sub_beats = librosa.util.fix_frames(sub_beats, x_max=C.shape[1])
    >>> C_med_sub = librosa.util.sync(C, sub_beats, aggregate=np.median)

    Plot the results

    >>> import matplotlib.pyplot as plt
    >>> beat_t = librosa.frames_to_time(beats, sr=sr)
    >>> subbeat_t = librosa.frames_to_time(sub_beats, sr=sr)
    >>> plt.figure()
    >>> plt.subplot(3, 1, 1)
    >>> librosa.display.specshow(librosa.amplitude_to_db(C,
    ...                                                  ref=np.max),
    ...                          x_axis='time')
    >>> plt.title('CQT power, shape={}'.format(C.shape))
    >>> plt.subplot(3, 1, 2)
    >>> librosa.display.specshow(librosa.amplitude_to_db(C_med,
    ...                                                  ref=np.max),
    ...                          x_coords=beat_t, x_axis='time')
    >>> plt.title('Beat synchronous CQT power, '
    ...           'shape={}'.format(C_med.shape))
    >>> plt.subplot(3, 1, 3)
    >>> librosa.display.specshow(librosa.amplitude_to_db(C_med_sub,
    ...                                                  ref=np.max),
    ...                          x_coords=subbeat_t, x_axis='time')
    >>> plt.title('Sub-beat synchronous CQT power, '
    ...           'shape={}'.format(C_med_sub.shape))
    >>> plt.tight_layout()


def softmask(X, X_ref, power=<NUM_LIT:1>, split_zeros=False):

if X.shape != X_ref.shape:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(X.shape,<EOL>X_ref.shape))<EOL><DEDENT>if np.any(X < <NUM_LIT:0>) or np.any(X_ref < <NUM_LIT:0>):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if power <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>dtype = X.dtype<EOL>if not np.issubdtype(dtype, np.floating):<EOL><INDENT>dtype = np.float32<EOL><DEDENT>Z = np.maximum(X, X_ref).astype(dtype)<EOL>bad_idx = (Z < np.finfo(dtype).tiny)<EOL>Z[bad_idx] = <NUM_LIT:1><EOL>if np.isfinite(power):<EOL><INDENT>mask = (X / Z)**power<EOL>ref_mask = (X_ref / Z)**power<EOL>good_idx = ~bad_idx<EOL>mask[good_idx] /= mask[good_idx] + ref_mask[good_idx]<EOL>if split_zeros:<EOL><INDENT>mask[bad_idx] = <NUM_LIT:0.5><EOL><DEDENT>else:<EOL><INDENT>mask[bad_idx] = <NUM_LIT:0.0><EOL><DEDENT><DEDENT>else:<EOL><INDENT>mask = X > X_ref<EOL><DEDENT>return mask<EOL>

Robustly compute a softmask operation.

        `M = X**power / (X**power + X_ref**power)`

    Parameters
    ----------
    X : np.ndarray
        The (non-negative) input array corresponding to the positive mask elements

    X_ref : np.ndarray
        The (non-negative) array of reference or background elements.
        Must have the same shape as `X`.

    power : number > 0 or np.inf
        If finite, returns the soft mask computed in a numerically stable way

        If infinite, returns a hard (binary) mask equivalent to `X > X_ref`.
        Note: for hard masks, ties are always broken in favor of `X_ref` (`mask=0`).

    split_zeros : bool
        If `True`, entries where `X` and X`_ref` are both small (close to 0)
        will receive mask values of 0.5.

        Otherwise, the mask is set to 0 for these entries.

    Returns
    -------
    mask : np.ndarray, shape=`X.shape`
        The output mask array

    Raises
    ------
    ParameterError
        If `X` and `X_ref` have different shapes.

        If `X` or `X_ref` are negative anywhere

        If `power <= 0`

    Examples
    --------

    >>> X = 2 * np.ones((3, 3))
    >>> X_ref = np.vander(np.arange(3.0))
    >>> X
    array([[ 2.,  2.,  2.],
           [ 2.,  2.,  2.],
           [ 2.,  2.,  2.]])
    >>> X_ref
    array([[ 0.,  0.,  1.],
           [ 1.,  1.,  1.],
           [ 4.,  2.,  1.]])
    >>> librosa.util.softmask(X, X_ref, power=1)
    array([[ 1.   ,  1.   ,  0.667],
           [ 0.667,  0.667,  0.667],
           [ 0.333,  0.5  ,  0.667]])
    >>> librosa.util.softmask(X_ref, X, power=1)
    array([[ 0.   ,  0.   ,  0.333],
           [ 0.333,  0.333,  0.333],
           [ 0.667,  0.5  ,  0.333]])
    >>> librosa.util.softmask(X, X_ref, power=2)
    array([[ 1. ,  1. ,  0.8],
           [ 0.8,  0.8,  0.8],
           [ 0.2,  0.5,  0.8]])
    >>> librosa.util.softmask(X, X_ref, power=4)
    array([[ 1.   ,  1.   ,  0.941],
           [ 0.941,  0.941,  0.941],
           [ 0.059,  0.5  ,  0.941]])
    >>> librosa.util.softmask(X, X_ref, power=100)
    array([[  1.000e+00,   1.000e+00,   1.000e+00],
           [  1.000e+00,   1.000e+00,   1.000e+00],
           [  7.889e-31,   5.000e-01,   1.000e+00]])
    >>> librosa.util.softmask(X, X_ref, power=np.inf)
    array([[ True,  True,  True],
           [ True,  True,  True],
           [False, False,  True]], dtype=bool)


<EOL>x = np.asarray(x)<EOL>if np.issubdtype(x.dtype, np.floating) or np.issubdtype(x.dtype, np.complexfloating):<EOL><INDENT>dtype = x.dtype<EOL><DEDENT>else:<EOL><INDENT>dtype = np.float32<EOL><DEDENT>return np.finfo(dtype).tiny<EOL>

Compute the tiny-value corresponding to an input's data type.

    This is the smallest "usable" number representable in `x`'s
    data type (e.g., float32).

    This is primarily useful for determining a threshold for
    numerical underflow in division or multiplication operations.

    Parameters
    ----------
    x : number or np.ndarray
        The array to compute the tiny-value for.
        All that matters here is `x.dtype`.

    Returns
    -------
    tiny_value : float
        The smallest positive usable number for the type of `x`.
        If `x` is integer-typed, then the tiny value for `np.float32`
        is returned instead.

    See Also
    --------
    numpy.finfo

    Examples
    --------

    For a standard double-precision floating point number:

    >>> librosa.util.tiny(1.0)
    2.2250738585072014e-308

    Or explicitly as double-precision

    >>> librosa.util.tiny(np.asarray(1e-5, dtype=np.float64))
    2.2250738585072014e-308

    Or complex numbers

    >>> librosa.util.tiny(1j)
    2.2250738585072014e-308

    Single-precision floating point:

    >>> librosa.util.tiny(np.asarray(1e-5, dtype=np.float32))
    1.1754944e-38

    Integer

    >>> librosa.util.tiny(5)
    1.1754944e-38


def fill_off_diagonal(x, radius, value=<NUM_LIT:0>):

nx, ny = x.shape<EOL>radius = np.round(radius * np.min(x.shape))<EOL>nx, ny = x.shape<EOL>offset = np.abs((x.shape[<NUM_LIT:0>] - x.shape[<NUM_LIT:1>]))<EOL>if nx < ny:<EOL><INDENT>idx_u = np.triu_indices_from(x, k=radius + offset)<EOL>idx_l = np.tril_indices_from(x, k=-radius)<EOL><DEDENT>else:<EOL><INDENT>idx_u = np.triu_indices_from(x, k=radius)<EOL>idx_l = np.tril_indices_from(x, k=-radius - offset)<EOL><DEDENT>x[idx_u] = value<EOL>x[idx_l] = value<EOL>


def moved(moved_from, version, version_removed):

def __wrapper(func, *args, **kwargs):<EOL><INDENT>'''<STR_LIT>'''<EOL>code = six.get_function_code(func)<EOL>warnings.warn_explicit(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>".format(moved_from, func.__module__,<EOL>func.__name__, version, version_removed),<EOL>category=DeprecationWarning,<EOL>filename=code.co_filename,<EOL>lineno=code.co_firstlineno + <NUM_LIT:1><EOL>)<EOL>return func(*args, **kwargs)<EOL><DEDENT>return decorator(__wrapper)<EOL>

This is a decorator which can be used to mark functions
    as moved/renamed.

    It will result in a warning being emitted when the function is used.


def __wrapper(func, *args, **kwargs):<EOL><INDENT>'''<STR_LIT>'''<EOL>code = six.get_function_code(func)<EOL>warnings.warn_explicit(<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>.format(func.__module__, func.__name__,<EOL>version, version_removed),<EOL>category=DeprecationWarning,<EOL>filename=code.co_filename,<EOL>lineno=code.co_firstlineno + <NUM_LIT:1><EOL>)<EOL>return func(*args, **kwargs)<EOL><DEDENT>return decorator(__wrapper)<EOL>

This is a decorator which can be used to mark functions
    as deprecated.

    It will result in a warning being emitted when the function is used.


@numba.jit(nopython=True, cache=True)<EOL>def __jaccard(int_a, int_b):

ends = [int_a[<NUM_LIT:1>], int_b[<NUM_LIT:1>]]<EOL>if ends[<NUM_LIT:1>] < ends[<NUM_LIT:0>]:<EOL><INDENT>ends.reverse()<EOL><DEDENT>starts = [int_a[<NUM_LIT:0>], int_b[<NUM_LIT:0>]]<EOL>if starts[<NUM_LIT:1>] < starts[<NUM_LIT:0>]:<EOL><INDENT>starts.reverse()<EOL><DEDENT>intersection = ends[<NUM_LIT:0>] - starts[<NUM_LIT:1>]<EOL>if intersection < <NUM_LIT:0>:<EOL><INDENT>intersection = <NUM_LIT:0.><EOL><DEDENT>union = ends[<NUM_LIT:1>] - starts[<NUM_LIT:0>]<EOL>if union > <NUM_LIT:0>:<EOL><INDENT>return intersection / union<EOL><DEDENT>return <NUM_LIT:0.0><EOL>

Jaccard similarity between two intervals

    Parameters
    ----------
    int_a, int_b : np.ndarrays, shape=(2,)

    Returns
    -------
    Jaccard similarity between intervals


@numba.jit(nopython=True, cache=True)<EOL>def __match_interval_overlaps(query, intervals_to, candidates):

best_score = -<NUM_LIT:1><EOL>best_idx = -<NUM_LIT:1><EOL>for idx in candidates:<EOL><INDENT>score = __jaccard(query, intervals_to[idx])<EOL>if score > best_score:<EOL><INDENT>best_score, best_idx = score, idx<EOL><DEDENT><DEDENT>return best_idx<EOL>

Find the best Jaccard match from query to candidates


@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.


def match_intervals(intervals_from, intervals_to, strict=True):

if len(intervals_from) == <NUM_LIT:0> or len(intervals_to) == <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>valid_intervals(intervals_from)<EOL>valid_intervals(intervals_to)<EOL>try:<EOL><INDENT>return __match_intervals(intervals_from, intervals_to, strict=strict)<EOL><DEDENT>except ParameterError:<EOL><INDENT>six.reraise(ParameterError,<EOL>ParameterError('<STR_LIT>'.format(strict)),<EOL>sys.exc_info()[<NUM_LIT:2>])<EOL><DEDENT>

Match one set of time intervals to another.

    This can be useful for tasks such as mapping beat timings
    to segments.

    Each element `[a, b]` of `intervals_from` is matched to the
    element `[c, d]` of `intervals_to` which maximizes the
    Jaccard similarity between the intervals:

        `max(0, |min(b, d) - max(a, c)|) / |max(d, b) - min(a, c)|`

    In `strict=True` mode, if there is no interval with positive
    intersection with `[a,b]`, an exception is thrown.

    In `strict=False` mode, any interval `[a, b]` that has no
    intersection with any element of `intervals_to` is instead
    matched to the interval `[c, d]` which minimizes

        `min(|b - c|, |a - d|)`

    that is, the disjoint interval `[c, d]` with a boundary closest
    to `[a, b]`.

    .. note:: An element of `intervals_to` may be matched to multiple
       entries of `intervals_from`.

    Parameters
    ----------
    intervals_from : np.ndarray [shape=(n, 2)]
        The time range for source intervals.
        The `i` th interval spans time `intervals_from[i, 0]`
        to `intervals_from[i, 1]`.
        `intervals_from[0, 0]` should be 0, `intervals_from[-1, 1]`
        should be the track duration.

    intervals_to : np.ndarray [shape=(m, 2)]
        Analogous to `intervals_from`.

    strict : bool
        If `True`, intervals can only match if they intersect.
        If `False`, disjoint intervals can match.

    Returns
    -------
    interval_mapping : np.ndarray [shape=(n,)]
        For each interval in `intervals_from`, the
        corresponding interval in `intervals_to`.

    See Also
    --------
    match_events

    Raises
    ------
    ParameterError
        If either array of input intervals is not the correct shape

        If `strict=True` and some element of `intervals_from` is disjoint from
        every element of `intervals_to`.

    Examples
    --------
    >>> ints_from = np.array([[3, 5], [1, 4], [4, 5]])
    >>> ints_to = np.array([[0, 2], [1, 3], [4, 5], [6, 7]])
    >>> librosa.util.match_intervals(ints_from, ints_to)
    array([2, 1, 2], dtype=uint32)
    >>> # [3, 5] => [4, 5]  (ints_to[2])
    >>> # [1, 4] => [1, 3]  (ints_to[1])
    >>> # [4, 5] => [4, 5]  (ints_to[2])

    The reverse matching of the above is not possible in `strict` mode
    because `[6, 7]` is disjoint from all intervals in `ints_from`.
    With `strict=False`, we get the following:
    >>> librosa.util.match_intervals(ints_to, ints_from, strict=False)
    array([1, 1, 2, 2], dtype=uint32)
    >>> # [0, 2] => [1, 4]  (ints_from[1])
    >>> # [1, 3] => [1, 4]  (ints_from[1])
    >>> # [4, 5] => [4, 5]  (ints_from[2])
    >>> # [6, 7] => [4, 5]  (ints_from[2])


def match_events(events_from, events_to, left=True, right=True):

if len(events_from) == <NUM_LIT:0> or len(events_to) == <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if not (left or right) and not np.all(np.in1d(events_from, events_to)):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if (not left) and max(events_to) < max(events_from):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if (not right) and min(events_to) > min(events_from):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>output = np.empty_like(events_from, dtype=np.int)<EOL>return __match_events_helper(output, events_from, events_to, left, right)<EOL>

Match one set of events to another.

    This is useful for tasks such as matching beats to the nearest
    detected onsets, or frame-aligned events to the nearest zero-crossing.

    .. note:: A target event may be matched to multiple source events.

    Examples
    --------
    >>> # Sources are multiples of 7
    >>> s_from = np.arange(0, 100, 7)
    >>> s_from
    array([ 0,  7, 14, 21, 28, 35, 42, 49, 56, 63, 70, 77, 84, 91,
           98])
    >>> # Targets are multiples of 10
    >>> s_to = np.arange(0, 100, 10)
    >>> s_to
    array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
    >>> # Find the matching
    >>> idx = librosa.util.match_events(s_from, s_to)
    >>> idx
    array([0, 1, 1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 8, 9, 9])
    >>> # Print each source value to its matching target
    >>> zip(s_from, s_to[idx])
    [(0, 0), (7, 10), (14, 10), (21, 20), (28, 30), (35, 30),
     (42, 40), (49, 50), (56, 60), (63, 60), (70, 70), (77, 80),
     (84, 80), (91, 90), (98, 90)]

    Parameters
    ----------
    events_from : ndarray [shape=(n,)]
      Array of events (eg, times, sample or frame indices) to match from.

    events_to : ndarray [shape=(m,)]
      Array of events (eg, times, sample or frame indices) to
      match against.

    left : bool
    right : bool
        If `False`, then matched events cannot be to the left (or right)
        of source events.

    Returns
    -------
    event_mapping : np.ndarray [shape=(n,)]
        For each event in `events_from`, the corresponding event
        index in `events_to`.

        `event_mapping[i] == arg min |events_from[i] - events_to[:]|`

    See Also
    --------
    match_intervals

    Raises
    ------
    ParameterError
        If either array of input events is not the correct shape


def wrapper(function):<EOL><INDENT>'''<STR_LIT>'''<EOL>from decorator import FunctionMaker<EOL>def decorator_apply(dec, func):<EOL><INDENT>"""<STR_LIT>"""<EOL>return FunctionMaker.create(<EOL>func, '<STR_LIT>',<EOL>dict(decorated=dec(func)), __wrapped__=func)<EOL><DEDENT>if self.memory.location is not None and self.level >= level:<EOL><INDENT>return decorator_apply(self.memory.cache, function)<EOL><DEDENT>else:<EOL><INDENT>return function<EOL><DEDENT><DEDENT>return wrapper<EOL>

Example usage:

        @cache(level=2)
        def semi_important_function(some_arguments):
            ...


<EOL>stft = core.stft(y)<EOL>stft_harm, stft_perc = decompose.hpss(stft, **kwargs)<EOL>y_harm = util.fix_length(core.istft(stft_harm, dtype=y.dtype), len(y))<EOL>y_perc = util.fix_length(core.istft(stft_perc, dtype=y.dtype), len(y))<EOL>return y_harm, y_perc<EOL>

Decompose an audio time series into harmonic and percussive components.

    This function automates the STFT->HPSS->ISTFT pipeline, and ensures that
    the output waveforms have equal length to the input waveform `y`.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)]
        audio time series
    kwargs : additional keyword arguments.
        See `librosa.decompose.hpss` for details.

    Returns
    -------
    y_harmonic : np.ndarray [shape=(n,)]
        audio time series of the harmonic elements

    y_percussive : np.ndarray [shape=(n,)]
        audio time series of the percussive elements

    See Also
    --------
    harmonic : Extract only the harmonic component
    percussive : Extract only the percussive component
    librosa.decompose.hpss : HPSS on spectrograms

    Examples
    --------
    >>> # Extract harmonic and percussive components
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> y_harmonic, y_percussive = librosa.effects.hpss(y)

    >>> # Get a more isolated percussive component by widening its margin
    >>> y_harmonic, y_percussive = librosa.effects.hpss(y, margin=(1.0,5.0))


<EOL>stft = core.stft(y)<EOL>stft_harm = decompose.hpss(stft, **kwargs)[<NUM_LIT:0>]<EOL>y_harm = util.fix_length(core.istft(stft_harm, dtype=y.dtype), len(y))<EOL>return y_harm<EOL>

Extract harmonic elements from an audio time-series.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)]
        audio time series
    kwargs : additional keyword arguments.
        See `librosa.decompose.hpss` for details.

    Returns
    -------
    y_harmonic : np.ndarray [shape=(n,)]
        audio time series of just the harmonic portion

    See Also
    --------
    hpss : Separate harmonic and percussive components
    percussive : Extract only the percussive component
    librosa.decompose.hpss : HPSS for spectrograms

    Examples
    --------
    >>> # Extract harmonic component
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> y_harmonic = librosa.effects.harmonic(y)

    >>> # Use a margin > 1.0 for greater harmonic separation
    >>> y_harmonic = librosa.effects.harmonic(y, margin=3.0)


<EOL>stft = core.stft(y)<EOL>stft_perc = decompose.hpss(stft, **kwargs)[<NUM_LIT:1>]<EOL>y_perc = util.fix_length(core.istft(stft_perc, dtype=y.dtype), len(y))<EOL>return y_perc<EOL>

Extract percussive elements from an audio time-series.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)]
        audio time series
    kwargs : additional keyword arguments.
        See `librosa.decompose.hpss` for details.

    Returns
    -------
    y_percussive : np.ndarray [shape=(n,)]
        audio time series of just the percussive portion

    See Also
    --------
    hpss : Separate harmonic and percussive components
    harmonic : Extract only the harmonic component
    librosa.decompose.hpss : HPSS for spectrograms

    Examples
    --------
    >>> # Extract percussive component
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> y_percussive = librosa.effects.percussive(y)

    >>> # Use a margin > 1.0 for greater percussive separation
    >>> y_percussive = librosa.effects.percussive(y, margin=3.0)


if rate <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>stft = core.stft(y)<EOL>stft_stretch = core.phase_vocoder(stft, rate)<EOL>y_stretch = core.istft(stft_stretch, dtype=y.dtype)<EOL>return y_stretch<EOL>

Time-stretch an audio series by a fixed rate.

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

    rate : float > 0 [scalar]
        Stretch factor.  If `rate > 1`, then the signal is sped up.

        If `rate < 1`, then the signal is slowed down.

    Returns
    -------
    y_stretch : np.ndarray [shape=(rate * n,)]
        audio time series stretched by the specified rate

    See Also
    --------
    pitch_shift : pitch shifting
    librosa.core.phase_vocoder : spectrogram phase vocoder

    Examples
    --------
    Compress to be twice as fast

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> y_fast = librosa.effects.time_stretch(y, 2.0)

    Or half the original speed

    >>> y_slow = librosa.effects.time_stretch(y, 0.5)


def pitch_shift(y, sr, n_steps, bins_per_octave=<NUM_LIT:12>, res_type='<STR_LIT>'):

if bins_per_octave < <NUM_LIT:1> or not np.issubdtype(type(bins_per_octave), np.integer):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>rate = <NUM_LIT> ** (-float(n_steps) / bins_per_octave)<EOL>y_shift = core.resample(time_stretch(y, rate), float(sr) / rate, sr,<EOL>res_type=res_type)<EOL>return util.fix_length(y_shift, len(y))<EOL>

Pitch-shift the waveform by `n_steps` half-steps.

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

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

    n_steps : float [scalar]
        how many (fractional) half-steps to shift `y`

    bins_per_octave : float > 0 [scalar]
        how many steps per octave

    res_type : string
        Resample type.
        Possible options: 'kaiser_best', 'kaiser_fast', and 'scipy', 'polyphase',
        'fft'.
        By default, 'kaiser_best' is used.

        See `core.resample` for more information.

    Returns
    -------
    y_shift : np.ndarray [shape=(n,)]
        The pitch-shifted audio time-series

    See Also
    --------
    time_stretch : time stretching
    librosa.core.phase_vocoder : spectrogram phase vocoder

    Examples
    --------
    Shift up by a major third (four half-steps)

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> y_third = librosa.effects.pitch_shift(y, sr, n_steps=4)

    Shift down by a tritone (six half-steps)

    >>> y_tritone = librosa.effects.pitch_shift(y, sr, n_steps=-6)

    Shift up by 3 quarter-tones

    >>> y_three_qt = librosa.effects.pitch_shift(y, sr, n_steps=3,
    ...                                          bins_per_octave=24)


def remix(y, intervals, align_zeros=True):

<EOL>util.valid_audio(y, mono=False)<EOL>y_out = []<EOL>if align_zeros:<EOL><INDENT>y_mono = core.to_mono(y)<EOL>zeros = np.nonzero(core.zero_crossings(y_mono))[-<NUM_LIT:1>]<EOL>zeros = np.append(zeros, [len(y_mono)])<EOL><DEDENT>clip = [slice(None)] * y.ndim<EOL>for interval in intervals:<EOL><INDENT>if align_zeros:<EOL><INDENT>interval = zeros[util.match_events(interval, zeros)]<EOL><DEDENT>clip[-<NUM_LIT:1>] = slice(interval[<NUM_LIT:0>], interval[<NUM_LIT:1>])<EOL>y_out.append(y[tuple(clip)])<EOL><DEDENT>return np.concatenate(y_out, axis=-<NUM_LIT:1>)<EOL>

Remix an audio signal by re-ordering time intervals.

    Parameters
    ----------
    y : np.ndarray [shape=(t,) or (2, t)]
        Audio time series

    intervals : iterable of tuples (start, end)
        An iterable (list-like or generator) where the `i`th item
        `intervals[i]` indicates the start and end (in samples)
        of a slice of `y`.

    align_zeros : boolean
        If `True`, interval boundaries are mapped to the closest
        zero-crossing in `y`.  If `y` is stereo, zero-crossings
        are computed after converting to mono.

    Returns
    -------
    y_remix : np.ndarray [shape=(d,) or (2, d)]
        `y` remixed in the order specified by `intervals`

    Examples
    --------
    Load in the example track and reverse the beats

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

    Compute beats

    >>> _, beat_frames = librosa.beat.beat_track(y=y, sr=sr,
    ...                                          hop_length=512)

    Convert from frames to sample indices

    >>> beat_samples = librosa.frames_to_samples(beat_frames)

    Generate intervals from consecutive events

    >>> intervals = librosa.util.frame(beat_samples, frame_length=2,
    ...                                hop_length=1).T

    Reverse the beat intervals

    >>> y_out = librosa.effects.remix(y, intervals[::-1])


def _signal_to_frame_nonsilent(y, frame_length=<NUM_LIT>, hop_length=<NUM_LIT>, top_db=<NUM_LIT>,<EOL>ref=np.max):

<EOL>y_mono = core.to_mono(y)<EOL>mse = feature.rms(y=y_mono,<EOL>frame_length=frame_length,<EOL>hop_length=hop_length)**<NUM_LIT:2><EOL>return (core.power_to_db(mse.squeeze(),<EOL>ref=ref,<EOL>top_db=None) > - top_db)<EOL>

Frame-wise non-silent indicator for audio input.

    This is a helper function for `trim` and `split`.

    Parameters
    ----------
    y : np.ndarray, shape=(n,) or (2,n)
        Audio signal, mono or stereo

    frame_length : int > 0
        The number of samples per frame

    hop_length : int > 0
        The number of samples between frames

    top_db : number > 0
        The threshold (in decibels) below reference to consider as
        silence

    ref : callable or float
        The reference power

    Returns
    -------
    non_silent : np.ndarray, shape=(m,), dtype=bool
        Indicator of non-silent frames


def trim(y, top_db=<NUM_LIT>, ref=np.max, frame_length=<NUM_LIT>, hop_length=<NUM_LIT>):

non_silent = _signal_to_frame_nonsilent(y,<EOL>frame_length=frame_length,<EOL>hop_length=hop_length,<EOL>ref=ref,<EOL>top_db=top_db)<EOL>nonzero = np.flatnonzero(non_silent)<EOL>if nonzero.size > <NUM_LIT:0>:<EOL><INDENT>start = int(core.frames_to_samples(nonzero[<NUM_LIT:0>], hop_length))<EOL>end = min(y.shape[-<NUM_LIT:1>],<EOL>int(core.frames_to_samples(nonzero[-<NUM_LIT:1>] + <NUM_LIT:1>, hop_length)))<EOL><DEDENT>else:<EOL><INDENT>start, end = <NUM_LIT:0>, <NUM_LIT:0><EOL><DEDENT>full_index = [slice(None)] * y.ndim<EOL>full_index[-<NUM_LIT:1>] = slice(start, end)<EOL>return y[tuple(full_index)], np.asarray([start, end])<EOL>

Trim leading and trailing silence from an audio signal.

    Parameters
    ----------
    y : np.ndarray, shape=(n,) or (2,n)
        Audio signal, can be mono or stereo

    top_db : number > 0
        The threshold (in decibels) below reference to consider as
        silence

    ref : number or callable
        The reference power.  By default, it uses `np.max` and compares
        to the peak power in the signal.

    frame_length : int > 0
        The number of samples per analysis frame

    hop_length : int > 0
        The number of samples between analysis frames

    Returns
    -------
    y_trimmed : np.ndarray, shape=(m,) or (2, m)
        The trimmed signal

    index : np.ndarray, shape=(2,)
        the interval of `y` corresponding to the non-silent region:
        `y_trimmed = y[index[0]:index[1]]` (for mono) or
        `y_trimmed = y[:, index[0]:index[1]]` (for stereo).

    Examples
    --------
    >>> # Load some audio
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> # Trim the beginning and ending silence
    >>> yt, index = librosa.effects.trim(y)
    >>> # Print the durations
    >>> print(librosa.get_duration(y), librosa.get_duration(yt))
    61.45886621315193 60.58086167800454


def split(y, top_db=<NUM_LIT>, ref=np.max, frame_length=<NUM_LIT>, hop_length=<NUM_LIT>):

non_silent = _signal_to_frame_nonsilent(y,<EOL>frame_length=frame_length,<EOL>hop_length=hop_length,<EOL>ref=ref,<EOL>top_db=top_db)<EOL>edges = np.flatnonzero(np.diff(non_silent.astype(int)))<EOL>edges = [edges + <NUM_LIT:1>]<EOL>if non_silent[<NUM_LIT:0>]:<EOL><INDENT>edges.insert(<NUM_LIT:0>, [<NUM_LIT:0>])<EOL><DEDENT>if non_silent[-<NUM_LIT:1>]:<EOL><INDENT>edges.append([len(non_silent)])<EOL><DEDENT>edges = core.frames_to_samples(np.concatenate(edges),<EOL>hop_length=hop_length)<EOL>edges = np.minimum(edges, y.shape[-<NUM_LIT:1>])<EOL>return edges.reshape((-<NUM_LIT:1>, <NUM_LIT:2>))<EOL>

Split an audio signal into non-silent intervals.

    Parameters
    ----------
    y : np.ndarray, shape=(n,) or (2, n)
        An audio signal

    top_db : number > 0
        The threshold (in decibels) below reference to consider as
        silence

    ref : number or callable
        The reference power.  By default, it uses `np.max` and compares
        to the peak power in the signal.

    frame_length : int > 0
        The number of samples per analysis frame

    hop_length : int > 0
        The number of samples between analysis frames

    Returns
    -------
    intervals : np.ndarray, shape=(m, 2)
        `intervals[i] == (start_i, end_i)` are the start and end time
        (in samples) of non-silent interval `i`.


@cache(level=<NUM_LIT:30>)<EOL>def recurrence_matrix(data, k=None, width=<NUM_LIT:1>, metric='<STR_LIT>',<EOL>sym=False, sparse=False, mode='<STR_LIT>',<EOL>bandwidth=None, self=False, axis=-<NUM_LIT:1>):

data = np.atleast_2d(data)<EOL>data = np.swapaxes(data, axis, <NUM_LIT:0>)<EOL>t = data.shape[<NUM_LIT:0>]<EOL>data = data.reshape((t, -<NUM_LIT:1>))<EOL>if width < <NUM_LIT:1> or width > t:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(width, axis, t))<EOL><DEDENT>if mode not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ParameterError(("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>").format(mode))<EOL><DEDENT>if k is None:<EOL><INDENT>if t > <NUM_LIT:2> * width + <NUM_LIT:1>:<EOL><INDENT>k = <NUM_LIT:2> * np.ceil(np.sqrt(t - <NUM_LIT:2> * width + <NUM_LIT:1>))<EOL><DEDENT>else:<EOL><INDENT>k = <NUM_LIT:2><EOL><DEDENT><DEDENT>if bandwidth is not None:<EOL><INDENT>if bandwidth <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(bandwidth))<EOL><DEDENT><DEDENT>k = int(k)<EOL>try:<EOL><INDENT>knn = sklearn.neighbors.NearestNeighbors(n_neighbors=min(t-<NUM_LIT:1>, k + <NUM_LIT:2> * width),<EOL>metric=metric,<EOL>algorithm='<STR_LIT>')<EOL><DEDENT>except ValueError:<EOL><INDENT>knn = sklearn.neighbors.NearestNeighbors(n_neighbors=min(t-<NUM_LIT:1>, k + <NUM_LIT:2> * width),<EOL>metric=metric,<EOL>algorithm='<STR_LIT>')<EOL><DEDENT>knn.fit(data)<EOL>if mode == '<STR_LIT>':<EOL><INDENT>kng_mode = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>kng_mode = mode<EOL><DEDENT>rec = knn.kneighbors_graph(mode=kng_mode).tolil()<EOL>for diag in range(-width + <NUM_LIT:1>, width):<EOL><INDENT>rec.setdiag(<NUM_LIT:0>, diag)<EOL><DEDENT>for i in range(t):<EOL><INDENT>links = rec[i].nonzero()[<NUM_LIT:1>]<EOL>idx = links[np.argsort(rec[i, links].toarray())][<NUM_LIT:0>]<EOL>rec[i, idx[k:]] = <NUM_LIT:0><EOL><DEDENT>if self:<EOL><INDENT>if mode == '<STR_LIT>':<EOL><INDENT>rec.setdiag(<NUM_LIT:1>)<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>rec.setdiag(-<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if sym:<EOL><INDENT>rec = rec.minimum(rec.T)<EOL><DEDENT>rec = rec.tocsr()<EOL>rec.eliminate_zeros()<EOL>if mode == '<STR_LIT>':<EOL><INDENT>rec = rec.astype(np.bool)<EOL><DEDENT>elif mode == '<STR_LIT>':<EOL><INDENT>if bandwidth is None:<EOL><INDENT>bandwidth = np.nanmedian(rec.max(axis=<NUM_LIT:1>).data)<EOL><DEDENT>rec.data[rec.data < <NUM_LIT:0>] = <NUM_LIT:0.0><EOL>rec.data[:] = np.exp(rec.data / (-<NUM_LIT:1> * bandwidth))<EOL><DEDENT>if not sparse:<EOL><INDENT>rec = rec.toarray()<EOL><DEDENT>return rec<EOL>

Compute a recurrence matrix from a data matrix.

    `rec[i, j]` is non-zero if (`data[:, i]`, `data[:, j]`) are
    k-nearest-neighbors and `|i - j| >= width`

    The specific value of `rec[i, j]` can have several forms, governed
    by the `mode` parameter below:

        - Connectivity: `rec[i, j] = 1 or 0` indicates that frames `i` and `j` are repetitions

        - Affinity: `rec[i, j] > 0` measures how similar frames `i` and `j` are.  This is also
          known as a (sparse) self-similarity matrix.

        - Distance: `rec[, j] > 0` measures how distant frames `i` and `j` are.  This is also
          known as a (sparse) self-distance matrix.

    The general term *recurrence matrix* can refer to any of the three forms above.

    Parameters
    ----------
    data : np.ndarray
        A feature matrix

    k : int > 0 [scalar] or None
        the number of nearest-neighbors for each sample

        Default: `k = 2 * ceil(sqrt(t - 2 * width + 1))`,
        or `k = 2` if `t <= 2 * width + 1`

    width : int >= 1 [scalar]
        only link neighbors `(data[:, i], data[:, j])`
        if `|i - j| >= width`

        `width` cannot exceed the length of the data.

    metric : str
        Distance metric to use for nearest-neighbor calculation.

        See `sklearn.neighbors.NearestNeighbors` for details.

    sym : bool [scalar]
        set `sym=True` to only link mutual nearest-neighbors

    sparse : bool [scalar]
        if False, returns a dense type (ndarray)
        if True, returns a sparse type (scipy.sparse.csr_matrix)

    mode : str, {'connectivity', 'distance', 'affinity'}
        If 'connectivity', a binary connectivity matrix is produced.

        If 'distance', then a non-zero entry contains the distance between
        points.

        If 'affinity', then non-zero entries are mapped to
        `exp( - distance(i, j) / bandwidth)` where `bandwidth` is
        as specified below.

    bandwidth : None or float > 0
        If using ``mode='affinity'``, this can be used to set the
        bandwidth on the affinity kernel.

        If no value is provided, it is set automatically to the median
        distance between furthest nearest neighbors.

    self : bool
        If `True`, then the main diagonal is populated with self-links:
        0 if ``mode='distance'``, and 1 otherwise.

        If `False`, the main diagonal is left empty.

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

    Returns
    -------
    rec : np.ndarray or scipy.sparse.csr_matrix, [shape=(t, t)]
        Recurrence matrix

    See Also
    --------
    sklearn.neighbors.NearestNeighbors
    scipy.spatial.distance.cdist
    librosa.feature.stack_memory
    recurrence_to_lag

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

    Examples
    --------
    Find nearest neighbors in MFCC space

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> mfcc = librosa.feature.mfcc(y=y, sr=sr)
    >>> R = librosa.segment.recurrence_matrix(mfcc)

    Or fix the number of nearest neighbors to 5

    >>> R = librosa.segment.recurrence_matrix(mfcc, k=5)

    Suppress neighbors within +- 7 samples

    >>> R = librosa.segment.recurrence_matrix(mfcc, width=7)

    Use cosine similarity instead of Euclidean distance

    >>> R = librosa.segment.recurrence_matrix(mfcc, metric='cosine')

    Require mutual nearest neighbors

    >>> R = librosa.segment.recurrence_matrix(mfcc, sym=True)

    Use an affinity matrix instead of binary connectivity

    >>> R_aff = librosa.segment.recurrence_matrix(mfcc, mode='affinity')

    Plot the feature and recurrence matrices

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8, 4))
    >>> plt.subplot(1, 2, 1)
    >>> librosa.display.specshow(R, x_axis='time', y_axis='time')
    >>> plt.title('Binary recurrence (symmetric)')
    >>> plt.subplot(1, 2, 2)
    >>> librosa.display.specshow(R_aff, x_axis='time', y_axis='time',
    ...                          cmap='magma_r')
    >>> plt.title('Affinity recurrence')
    >>> plt.tight_layout()


def recurrence_to_lag(rec, pad=True, axis=-<NUM_LIT:1>):

axis = np.abs(axis)<EOL>if rec.ndim != <NUM_LIT:2> or rec.shape[<NUM_LIT:0>] != rec.shape[<NUM_LIT:1>]:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT:{}>'.format(rec.shape))<EOL><DEDENT>sparse = scipy.sparse.issparse(rec)<EOL>roll_ax = None<EOL>if sparse:<EOL><INDENT>roll_ax = <NUM_LIT:1> - axis<EOL>lag_format = rec.format<EOL>if axis == <NUM_LIT:0>:<EOL><INDENT>rec = rec.tocsc()<EOL><DEDENT>elif axis in (-<NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>rec = rec.tocsr()<EOL><DEDENT><DEDENT>t = rec.shape[axis]<EOL>if sparse:<EOL><INDENT>if pad:<EOL><INDENT>kron = np.asarray([[<NUM_LIT:1>, <NUM_LIT:0>]]).swapaxes(axis, <NUM_LIT:0>)<EOL>lag = scipy.sparse.kron(kron.astype(rec.dtype), rec, format='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>lag = scipy.sparse.lil_matrix(rec)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if pad:<EOL><INDENT>padding = [(<NUM_LIT:0>, <NUM_LIT:0>), (<NUM_LIT:0>, <NUM_LIT:0>)]<EOL>padding[(<NUM_LIT:1>-axis)] = (<NUM_LIT:0>, t)<EOL>lag = np.pad(rec, padding, mode='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>lag = rec.copy()<EOL><DEDENT><DEDENT>idx_slice = [slice(None)] * lag.ndim<EOL>for i in range(<NUM_LIT:1>, t):<EOL><INDENT>idx_slice[axis] = i<EOL>lag[tuple(idx_slice)] = util.roll_sparse(lag[tuple(idx_slice)], -i, axis=roll_ax)<EOL><DEDENT>if sparse:<EOL><INDENT>return lag.asformat(lag_format)<EOL><DEDENT>return np.ascontiguousarray(lag.T).T<EOL>

Convert a recurrence matrix into a lag matrix.

        `lag[i, j] == rec[i+j, j]`

    Parameters
    ----------
    rec : np.ndarray, or scipy.sparse.spmatrix [shape=(n, n)]
        A (binary) recurrence matrix, as returned by `recurrence_matrix`

    pad : bool
        If False, `lag` matrix is square, which is equivalent to
        assuming that the signal repeats itself indefinitely.

        If True, `lag` is padded with `n` zeros, which eliminates
        the assumption of repetition.

    axis : int
        The axis to keep as the `time` axis.
        The alternate axis will be converted to lag coordinates.

    Returns
    -------
    lag : np.ndarray
        The recurrence matrix in (lag, time) (if `axis=1`)
        or (time, lag) (if `axis=0`) coordinates

    Raises
    ------
    ParameterError : if `rec` is non-square

    See Also
    --------
    recurrence_matrix
    lag_to_recurrence

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> mfccs = librosa.feature.mfcc(y=y, sr=sr)
    >>> recurrence = librosa.segment.recurrence_matrix(mfccs)
    >>> lag_pad = librosa.segment.recurrence_to_lag(recurrence, pad=True)
    >>> lag_nopad = librosa.segment.recurrence_to_lag(recurrence, pad=False)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8, 4))
    >>> plt.subplot(1, 2, 1)
    >>> librosa.display.specshow(lag_pad, x_axis='time', y_axis='lag')
    >>> plt.title('Lag (zero-padded)')
    >>> plt.subplot(1, 2, 2)
    >>> librosa.display.specshow(lag_nopad, x_axis='time')
    >>> plt.title('Lag (no padding)')
    >>> plt.tight_layout()


if axis not in [<NUM_LIT:0>, <NUM_LIT:1>, -<NUM_LIT:1>]:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(axis))<EOL><DEDENT>axis = np.abs(axis)<EOL>if lag.ndim != <NUM_LIT:2> or (lag.shape[<NUM_LIT:0>] != lag.shape[<NUM_LIT:1>] and<EOL>lag.shape[<NUM_LIT:1> - axis] != <NUM_LIT:2> * lag.shape[axis]):<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(lag.shape))<EOL><DEDENT>t = lag.shape[axis]<EOL>sparse = scipy.sparse.issparse(lag)<EOL>if sparse:<EOL><INDENT>rec = scipy.sparse.lil_matrix(lag)<EOL>roll_ax = <NUM_LIT:1> - axis<EOL><DEDENT>else:<EOL><INDENT>rec = lag.copy()<EOL>roll_ax = None<EOL><DEDENT>idx_slice = [slice(None)] * lag.ndim<EOL>for i in range(<NUM_LIT:1>, t):<EOL><INDENT>idx_slice[axis] = i<EOL>rec[tuple(idx_slice)] = util.roll_sparse(lag[tuple(idx_slice)], i, axis=roll_ax)<EOL><DEDENT>sub_slice = [slice(None)] * rec.ndim<EOL>sub_slice[<NUM_LIT:1> - axis] = slice(t)<EOL>rec = rec[tuple(sub_slice)]<EOL>if sparse:<EOL><INDENT>return rec.asformat(lag.format)<EOL><DEDENT>return np.ascontiguousarray(rec.T).T<EOL>

Convert a lag matrix into a recurrence matrix.

    Parameters
    ----------
    lag : np.ndarray or scipy.sparse.spmatrix
        A lag matrix, as produced by `recurrence_to_lag`

    axis : int
        The axis corresponding to the time dimension.
        The alternate axis will be interpreted in lag coordinates.

    Returns
    -------
    rec : np.ndarray or scipy.sparse.spmatrix [shape=(n, n)]
        A recurrence matrix in (time, time) coordinates
        For sparse matrices, format will match that of `lag`.

    Raises
    ------
    ParameterError : if `lag` does not have the correct shape

    See Also
    --------
    recurrence_to_lag

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> mfccs = librosa.feature.mfcc(y=y, sr=sr)
    >>> recurrence = librosa.segment.recurrence_matrix(mfccs)
    >>> lag_pad = librosa.segment.recurrence_to_lag(recurrence, pad=True)
    >>> lag_nopad = librosa.segment.recurrence_to_lag(recurrence, pad=False)
    >>> rec_pad = librosa.segment.lag_to_recurrence(lag_pad)
    >>> rec_nopad = librosa.segment.lag_to_recurrence(lag_nopad)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8, 4))
    >>> plt.subplot(2, 2, 1)
    >>> librosa.display.specshow(lag_pad, x_axis='time', y_axis='lag')
    >>> plt.title('Lag (zero-padded)')
    >>> plt.subplot(2, 2, 2)
    >>> librosa.display.specshow(lag_nopad, x_axis='time', y_axis='time')
    >>> plt.title('Lag (no padding)')
    >>> plt.subplot(2, 2, 3)
    >>> librosa.display.specshow(rec_pad, x_axis='time', y_axis='time')
    >>> plt.title('Recurrence (with padding)')
    >>> plt.subplot(2, 2, 4)
    >>> librosa.display.specshow(rec_nopad, x_axis='time', y_axis='time')
    >>> plt.title('Recurrence (without padding)')
    >>> plt.tight_layout()


def timelag_filter(function, pad=True, index=<NUM_LIT:0>):

def __my_filter(wrapped_f, *args, **kwargs):<EOL><INDENT>'''<STR_LIT>'''<EOL>args = list(args)<EOL>args[index] = recurrence_to_lag(args[index], pad=pad)<EOL>result = wrapped_f(*args, **kwargs)<EOL>return lag_to_recurrence(result)<EOL><DEDENT>return decorator(__my_filter, function)<EOL>

Filtering in the time-lag domain.

    This is primarily useful for adapting image filters to operate on
    `recurrence_to_lag` output.

    Using `timelag_filter` is equivalent to the following sequence of
    operations:

    >>> data_tl = librosa.segment.recurrence_to_lag(data)
    >>> data_filtered_tl = function(data_tl)
    >>> data_filtered = librosa.segment.lag_to_recurrence(data_filtered_tl)

    Parameters
    ----------
    function : callable
        The filtering function to wrap, e.g., `scipy.ndimage.median_filter`

    pad : bool
        Whether to zero-pad the structure feature matrix

    index : int >= 0
        If `function` accepts input data as a positional argument, it should be
        indexed by `index`

    Returns
    -------
    wrapped_function : callable
        A new filter function which applies in time-lag space rather than
        time-time space.

    Examples
    --------

    Apply a 5-bin median filter to the diagonal of a recurrence matrix

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
    >>> rec = librosa.segment.recurrence_matrix(chroma)
    >>> from scipy.ndimage import median_filter
    >>> diagonal_median = librosa.segment.timelag_filter(median_filter)
    >>> rec_filtered = diagonal_median(rec, size=(1, 3), mode='mirror')

    Or with affinity weights

    >>> rec_aff = librosa.segment.recurrence_matrix(chroma, mode='affinity')
    >>> rec_aff_fil = diagonal_median(rec_aff, size=(1, 3), mode='mirror')

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8,8))
    >>> plt.subplot(2, 2, 1)
    >>> librosa.display.specshow(rec, y_axis='time')
    >>> plt.title('Raw recurrence matrix')
    >>> plt.subplot(2, 2, 2)
    >>> librosa.display.specshow(rec_filtered)
    >>> plt.title('Filtered recurrence matrix')
    >>> plt.subplot(2, 2, 3)
    >>> librosa.display.specshow(rec_aff, x_axis='time', y_axis='time',
    ...                          cmap='magma_r')
    >>> plt.title('Raw affinity matrix')
    >>> plt.subplot(2, 2, 4)
    >>> librosa.display.specshow(rec_aff_fil, x_axis='time',
    ...                          cmap='magma_r')
    >>> plt.title('Filtered affinity matrix')
    >>> plt.tight_layout()


@cache(level=<NUM_LIT:30>)<EOL>def subsegment(data, frames, n_segments=<NUM_LIT:4>, axis=-<NUM_LIT:1>):

frames = util.fix_frames(frames, x_min=<NUM_LIT:0>, x_max=data.shape[axis], pad=True)<EOL>if n_segments < <NUM_LIT:1>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>boundaries = []<EOL>idx_slices = [slice(None)] * data.ndim<EOL>for seg_start, seg_end in zip(frames[:-<NUM_LIT:1>], frames[<NUM_LIT:1>:]):<EOL><INDENT>idx_slices[axis] = slice(seg_start, seg_end)<EOL>boundaries.extend(seg_start + agglomerative(data[tuple(idx_slices)],<EOL>min(seg_end - seg_start, n_segments),<EOL>axis=axis))<EOL><DEDENT>return np.ascontiguousarray(boundaries)<EOL>

Sub-divide a segmentation by feature clustering.

    Given a set of frame boundaries (`frames`), and a data matrix (`data`),
    each successive interval defined by `frames` is partitioned into
    `n_segments` by constrained agglomerative clustering.

    .. note::
        If an interval spans fewer than `n_segments` frames, then each
        frame becomes a sub-segment.

    Parameters
    ----------
    data : np.ndarray
        Data matrix to use in clustering

    frames : np.ndarray [shape=(n_boundaries,)], dtype=int, non-negative]
        Array of beat or segment boundaries, as provided by
        `librosa.beat.beat_track`,
        `librosa.onset.onset_detect`,
        or `agglomerative`.

    n_segments : int > 0
        Maximum number of frames to sub-divide each interval.

    axis : int
        Axis along which to apply the segmentation.
        By default, the last index (-1) is taken.

    Returns
    -------
    boundaries : np.ndarray [shape=(n_subboundaries,)]
        List of sub-divided segment boundaries

    See Also
    --------
    agglomerative : Temporal segmentation
    librosa.onset.onset_detect : Onset detection
    librosa.beat.beat_track : Beat tracking

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

    Examples
    --------
    Load audio, detect beat frames, and subdivide in twos by CQT

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=8)
    >>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr, hop_length=512)
    >>> beat_times = librosa.frames_to_time(beats, sr=sr, hop_length=512)
    >>> cqt = np.abs(librosa.cqt(y, sr=sr, hop_length=512))
    >>> subseg = librosa.segment.subsegment(cqt, beats, n_segments=2)
    >>> subseg_t = librosa.frames_to_time(subseg, sr=sr, hop_length=512)
    >>> subseg
    array([  0,   2,   4,  21,  23,  26,  43,  55,  63,  72,  83,
            97, 102, 111, 122, 137, 142, 153, 162, 180, 182, 185,
           202, 210, 221, 231, 241, 256, 261, 271, 281, 296, 301,
           310, 320, 339, 341, 344, 361, 368, 382, 389, 401, 416,
           420, 430, 436, 451, 456, 465, 476, 489, 496, 503, 515,
           527, 535, 544, 553, 558, 571, 578, 590, 607, 609, 638])

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> librosa.display.specshow(librosa.amplitude_to_db(cqt,
    ...                                                  ref=np.max),
    ...                          y_axis='cqt_hz', x_axis='time')
    >>> lims = plt.gca().get_ylim()
    >>> plt.vlines(beat_times, lims[0], lims[1], color='lime', alpha=0.9,
    ...            linewidth=2, label='Beats')
    >>> plt.vlines(subseg_t, lims[0], lims[1], color='linen', linestyle='--',
    ...            linewidth=1.5, alpha=0.5, label='Sub-beats')
    >>> plt.legend(frameon=True, shadow=True)
    >>> plt.title('CQT + Beat and sub-beat markers')
    >>> plt.tight_layout()


def agglomerative(data, k, clusterer=None, axis=-<NUM_LIT:1>):

<EOL>data = np.atleast_2d(data)<EOL>data = np.swapaxes(data, axis, <NUM_LIT:0>)<EOL>n = data.shape[<NUM_LIT:0>]<EOL>data = data.reshape((n, -<NUM_LIT:1>))<EOL>if clusterer is None:<EOL><INDENT>grid = sklearn.feature_extraction.image.grid_to_graph(n_x=n,<EOL>n_y=<NUM_LIT:1>, n_z=<NUM_LIT:1>)<EOL>clusterer = sklearn.cluster.AgglomerativeClustering(n_clusters=k,<EOL>connectivity=grid,<EOL>memory=cache.memory)<EOL><DEDENT>clusterer.fit(data)<EOL>boundaries = [<NUM_LIT:0>]<EOL>boundaries.extend(<EOL>list(<NUM_LIT:1> + np.nonzero(np.diff(clusterer.labels_))[<NUM_LIT:0>].astype(int)))<EOL>return np.asarray(boundaries)<EOL>

Bottom-up temporal segmentation.

    Use a temporally-constrained agglomerative clustering routine to partition
    `data` into `k` contiguous segments.

    Parameters
    ----------
    data     : np.ndarray
        data to cluster

    k        : int > 0 [scalar]
        number of segments to produce

    clusterer : sklearn.cluster.AgglomerativeClustering, optional
        An optional AgglomerativeClustering object.
        If `None`, a constrained Ward object is instantiated.

    axis : int
        axis along which to cluster.
        By default, the last axis (-1) is chosen.

    Returns
    -------
    boundaries : np.ndarray [shape=(k,)]
        left-boundaries (frame numbers) of detected segments. This
        will always include `0` as the first left-boundary.

    See Also
    --------
    sklearn.cluster.AgglomerativeClustering

    Examples
    --------
    Cluster by chroma similarity, break into 20 segments

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=15)
    >>> chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
    >>> bounds = librosa.segment.agglomerative(chroma, 20)
    >>> bound_times = librosa.frames_to_time(bounds, sr=sr)
    >>> bound_times
    array([  0.   ,   1.672,   2.322,   2.624,   3.251,   3.506,
             4.18 ,   5.387,   6.014,   6.293,   6.943,   7.198,
             7.848,   9.033,   9.706,   9.961,  10.635,  10.89 ,
            11.54 ,  12.539])

    Plot the segmentation over the chromagram

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> librosa.display.specshow(chroma, y_axis='chroma', x_axis='time')
    >>> plt.vlines(bound_times, 0, chroma.shape[0], color='linen', linestyle='--',
    ...            linewidth=2, alpha=0.9, label='Segment boundaries')
    >>> plt.axis('tight')
    >>> plt.legend(frameon=True, shadow=True)
    >>> plt.title('Power spectrogram')
    >>> plt.tight_layout()


def path_enhance(R, n, window='<STR_LIT>', max_ratio=<NUM_LIT>, min_ratio=None, n_filters=<NUM_LIT:7>,<EOL>zero_mean=False, clip=True, **kwargs):

if min_ratio is None:<EOL><INDENT>min_ratio = <NUM_LIT:1.>/max_ratio<EOL><DEDENT>elif min_ratio > max_ratio:<EOL><INDENT>raise ParameterError('<STR_LIT>'.format(min_ratio, max_ratio))<EOL><DEDENT>R_smooth = None<EOL>for ratio in np.logspace(np.log2(min_ratio), np.log2(max_ratio), num=n_filters, base=<NUM_LIT:2>):<EOL><INDENT>kernel = diagonal_filter(window, n, slope=ratio, zero_mean=zero_mean)<EOL>if R_smooth is None:<EOL><INDENT>R_smooth = scipy.ndimage.convolve(R, kernel, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>np.maximum(R_smooth, scipy.ndimage.convolve(R, kernel, **kwargs),<EOL>out=R_smooth)<EOL><DEDENT><DEDENT>if clip:<EOL><INDENT>np.clip(R_smooth, <NUM_LIT:0>, None, out=R_smooth)<EOL><DEDENT>return R_smooth<EOL>

Multi-angle path enhancement for self- and cross-similarity matrices.

    This function convolves multiple diagonal smoothing filters with a self-similarity (or
    recurrence) matrix R, and aggregates the result by an element-wise maximum.

    Technically, the output is a matrix R_smooth such that

        `R_smooth[i, j] = max_theta (R * filter_theta)[i, j]`

    where `*` denotes 2-dimensional convolution, and `filter_theta` is a smoothing filter at
    orientation theta.

    This is intended to provide coherent temporal smoothing of self-similarity matrices
    when there are changes in tempo.

    Smoothing filters are generated at evenly spaced orientations between min_ratio and
    max_ratio.

    This function is inspired by the multi-angle path enhancement of [1]_, but differs by
    modeling tempo differences in the space of similarity matrices rather than re-sampling
    the underlying features prior to generating the self-similarity matrix.

    .. [1] Müller, Meinard and Frank Kurth.
            "Enhancing similarity matrices for music audio analysis."
            2006 IEEE International Conference on Acoustics Speech and Signal Processing Proceedings.
            Vol. 5. IEEE, 2006.

    .. note:: if using recurrence_matrix to construct the input similarity matrix, be sure to include the main
              diagonal by setting `self=True`.  Otherwise, the diagonal will be suppressed, and this is likely to
              produce discontinuities which will pollute the smoothing filter response.

    Parameters
    ----------
    R : np.ndarray
        The self- or cross-similarity matrix to be smoothed.
        Note: sparse inputs are not supported.

    n : int > 0
        The length of the smoothing filter

    window : window specification
        The type of smoothing filter to use.  See `filters.get_window` for more information
        on window specification formats.

    max_ratio : float > 0
        The maximum tempo ratio to support

    min_ratio : float > 0
        The minimum tempo ratio to support.
        If not provided, it will default to `1/max_ratio`

    n_filters : int >= 1
        The number of different smoothing filters to use, evenly spaced
        between `min_ratio` and `max_ratio`.

        If `min_ratio = 1/max_ratio` (the default), using an odd number
        of filters will ensure that the main diagonal (ratio=1) is included.

    zero_mean : bool
        By default, the smoothing filters are non-negative and sum to one (i.e. are averaging
        filters).

        If `zero_mean=True`, then the smoothing filters are made to sum to zero by subtracting
        a constant value from the non-diagonal coordinates of the filter.  This is primarily
        useful for suppressing blocks while enhancing diagonals.

    clip : bool
        If True, the smoothed similarity matrix will be thresholded at 0, and will not contain
        negative entries.

    kwargs : additional keyword arguments
        Additional arguments to pass to `scipy.ndimage.convolve`

    Returns
    -------
    R_smooth : np.ndarray, shape=R.shape
        The smoothed self- or cross-similarity matrix

    See Also
    --------
    filters.diagonal_filter
    recurrence_matrix

    Examples
    --------
    Use a 51-frame diagonal smoothing filter to enhance paths in a recurrence matrix

    >>> y, sr = librosa.load(librosa.util.example_audio_file(), duration=30)
    >>> chroma = librosa.feature.chroma_cqt(y=y, sr=sr)
    >>> rec = librosa.segment.recurrence_matrix(chroma, mode='affinity', self=True)
    >>> rec_smooth = librosa.segment.path_enhance(rec, 51, window='hann', n_filters=7)

    Plot the recurrence matrix before and after smoothing

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8, 4))
    >>> plt.subplot(1,2,1)
    >>> librosa.display.specshow(rec, x_axis='time', y_axis='time')
    >>> plt.title('Unfiltered recurrence')
    >>> plt.subplot(1,2,2)
    >>> librosa.display.specshow(rec_smooth, x_axis='time', y_axis='time')
    >>> plt.title('Multi-angle enhanced recurrence')
    >>> plt.tight_layout()


def spectral_centroid(y=None, sr=<NUM_LIT>, S=None, n_fft=<NUM_LIT>, hop_length=<NUM_LIT>,<EOL>freq=None, win_length=None, window='<STR_LIT>', center=True,<EOL>pad_mode='<STR_LIT>'):

S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length,<EOL>win_length=win_length, window=window, center=center,<EOL>pad_mode=pad_mode)<EOL>if not np.isrealobj(S):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>elif np.any(S < <NUM_LIT:0>):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if freq is None:<EOL><INDENT>freq = fft_frequencies(sr=sr, n_fft=n_fft)<EOL><DEDENT>if freq.ndim == <NUM_LIT:1>:<EOL><INDENT>freq = freq.reshape((-<NUM_LIT:1>, <NUM_LIT:1>))<EOL><DEDENT>return np.sum(freq * util.normalize(S, norm=<NUM_LIT:1>, axis=<NUM_LIT:0>),<EOL>axis=<NUM_LIT:0>, keepdims=True)<EOL>

Compute the spectral centroid.

    Each frame of a magnitude spectrogram is normalized and treated as a
    distribution over frequency bins, from which the mean (centroid) is
    extracted per frame.

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

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

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

    n_fft : int > 0 [scalar]
        FFT window size

    hop_length : int > 0 [scalar]
        hop length for STFT. See `librosa.core.stft` for details.

    freq : None or np.ndarray [shape=(d,) or shape=(d, t)]
        Center frequencies for spectrogram bins.
        If `None`, then FFT bin center frequencies are used.
        Otherwise, it can be a single array of `d` center frequencies,
        or a matrix of center frequencies as constructed by
        `librosa.core.ifgram`

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

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

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

        .. see also:: `filters.get_window`

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

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

    Returns
    -------
    centroid : np.ndarray [shape=(1, t)]
        centroid frequencies

    See Also
    --------
    librosa.core.stft
        Short-time Fourier Transform

    librosa.core.ifgram
        Instantaneous-frequency spectrogram

    Examples
    --------
    From time-series input:

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> cent = librosa.feature.spectral_centroid(y=y, sr=sr)
    >>> cent
    array([[ 4382.894,   626.588, ...,  5037.07 ,  5413.398]])

    From spectrogram input:

    >>> S, phase = librosa.magphase(librosa.stft(y=y))
    >>> librosa.feature.spectral_centroid(S=S)
    array([[ 4382.894,   626.588, ...,  5037.07 ,  5413.398]])

    Using variable bin center frequencies:

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> if_gram, D = librosa.ifgram(y)
    >>> librosa.feature.spectral_centroid(S=np.abs(D), freq=if_gram)
    array([[ 4420.719,   625.769, ...,  5011.86 ,  5221.492]])

    Plot the result

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2, 1, 1)
    >>> plt.semilogy(cent.T, label='Spectral centroid')
    >>> plt.ylabel('Hz')
    >>> plt.xticks([])
    >>> plt.xlim([0, cent.shape[-1]])
    >>> plt.legend()
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.title('log Power spectrogram')
    >>> plt.tight_layout()


def spectral_bandwidth(y=None, sr=<NUM_LIT>, S=None, n_fft=<NUM_LIT>, hop_length=<NUM_LIT>,<EOL>win_length=None, window='<STR_LIT>', center=True, pad_mode='<STR_LIT>',<EOL>freq=None, centroid=None, norm=True, p=<NUM_LIT:2>):

S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length,<EOL>win_length=win_length, window=window, center=center,<EOL>pad_mode=pad_mode)<EOL>if not np.isrealobj(S):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>elif np.any(S < <NUM_LIT:0>):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if centroid is None:<EOL><INDENT>centroid = spectral_centroid(y=y, sr=sr, S=S,<EOL>n_fft=n_fft,<EOL>hop_length=hop_length,<EOL>freq=freq)<EOL><DEDENT>if freq is None:<EOL><INDENT>freq = fft_frequencies(sr=sr, n_fft=n_fft)<EOL><DEDENT>if freq.ndim == <NUM_LIT:1>:<EOL><INDENT>deviation = np.abs(np.subtract.outer(freq, centroid[<NUM_LIT:0>]))<EOL><DEDENT>else:<EOL><INDENT>deviation = np.abs(freq - centroid[<NUM_LIT:0>])<EOL><DEDENT>if norm:<EOL><INDENT>S = util.normalize(S, norm=<NUM_LIT:1>, axis=<NUM_LIT:0>)<EOL><DEDENT>return np.sum(S * deviation**p, axis=<NUM_LIT:0>, keepdims=True)**(<NUM_LIT:1.>/p)<EOL>

Compute p'th-order spectral bandwidth:

        (sum_k S[k] * (freq[k] - centroid)**p)**(1/p)

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

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

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

    n_fft : int > 0 [scalar]
        FFT window size

    hop_length : int > 0 [scalar]
        hop length for STFT. See `librosa.core.stft` for details.

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

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

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

        .. see also:: `filters.get_window`

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

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

    freq : None or np.ndarray [shape=(d,) or shape=(d, t)]
        Center frequencies for spectrogram bins.
        If `None`, then FFT bin center frequencies are used.
        Otherwise, it can be a single array of `d` center frequencies,
        or a matrix of center frequencies as constructed by
        `librosa.core.ifgram`

    centroid : None or np.ndarray [shape=(1, t)]
        pre-computed centroid frequencies

    norm : bool
        Normalize per-frame spectral energy (sum to one)

    p : float > 0
        Power to raise deviation from spectral centroid.

    Returns
    -------
    bandwidth : np.ndarray [shape=(1, t)]
        frequency bandwidth for each frame

    Examples
    --------
    From time-series input

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> spec_bw = librosa.feature.spectral_bandwidth(y=y, sr=sr)
    >>> spec_bw
    array([[ 3379.878,  1429.486, ...,  3235.214,  3080.148]])

    From spectrogram input

    >>> S, phase = librosa.magphase(librosa.stft(y=y))
    >>> librosa.feature.spectral_bandwidth(S=S)
    array([[ 3379.878,  1429.486, ...,  3235.214,  3080.148]])

    Using variable bin center frequencies

    >>> if_gram, D = librosa.ifgram(y)
    >>> librosa.feature.spectral_bandwidth(S=np.abs(D), freq=if_gram)
    array([[ 3380.011,  1429.11 , ...,  3235.22 ,  3080.148]])

    Plot the result

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2, 1, 1)
    >>> plt.semilogy(spec_bw.T, label='Spectral bandwidth')
    >>> plt.ylabel('Hz')
    >>> plt.xticks([])
    >>> plt.xlim([0, spec_bw.shape[-1]])
    >>> plt.legend()
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.title('log Power spectrogram')
    >>> plt.tight_layout()


def spectral_contrast(y=None, sr=<NUM_LIT>, S=None, n_fft=<NUM_LIT>, hop_length=<NUM_LIT>,<EOL>win_length=None, window='<STR_LIT>', center=True, pad_mode='<STR_LIT>',<EOL>freq=None, fmin=<NUM_LIT>, n_bands=<NUM_LIT:6>, quantile=<NUM_LIT>,<EOL>linear=False):

S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length,<EOL>win_length=win_length, window=window, center=center,<EOL>pad_mode=pad_mode)<EOL>if freq is None:<EOL><INDENT>freq = fft_frequencies(sr=sr, n_fft=n_fft)<EOL><DEDENT>freq = np.atleast_1d(freq)<EOL>if freq.ndim != <NUM_LIT:1> or len(freq) != S.shape[<NUM_LIT:0>]:<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>'.format(S.shape[<NUM_LIT:0>]))<EOL><DEDENT>if n_bands < <NUM_LIT:1> or not isinstance(n_bands, int):<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if not <NUM_LIT:0.0> < quantile < <NUM_LIT:1.0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>if fmin <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>octa = np.zeros(n_bands + <NUM_LIT:2>)<EOL>octa[<NUM_LIT:1>:] = fmin * (<NUM_LIT>**np.arange(<NUM_LIT:0>, n_bands + <NUM_LIT:1>))<EOL>if np.any(octa[:-<NUM_LIT:1>] >= <NUM_LIT:0.5> * sr):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>valley = np.zeros((n_bands + <NUM_LIT:1>, S.shape[<NUM_LIT:1>]))<EOL>peak = np.zeros_like(valley)<EOL>for k, (f_low, f_high) in enumerate(zip(octa[:-<NUM_LIT:1>], octa[<NUM_LIT:1>:])):<EOL><INDENT>current_band = np.logical_and(freq >= f_low, freq <= f_high)<EOL>idx = np.flatnonzero(current_band)<EOL>if k > <NUM_LIT:0>:<EOL><INDENT>current_band[idx[<NUM_LIT:0>] - <NUM_LIT:1>] = True<EOL><DEDENT>if k == n_bands:<EOL><INDENT>current_band[idx[-<NUM_LIT:1>] + <NUM_LIT:1>:] = True<EOL><DEDENT>sub_band = S[current_band]<EOL>if k < n_bands:<EOL><INDENT>sub_band = sub_band[:-<NUM_LIT:1>]<EOL><DEDENT>idx = np.rint(quantile * np.sum(current_band))<EOL>idx = int(np.maximum(idx, <NUM_LIT:1>))<EOL>sortedr = np.sort(sub_band, axis=<NUM_LIT:0>)<EOL>valley[k] = np.mean(sortedr[:idx], axis=<NUM_LIT:0>)<EOL>peak[k] = np.mean(sortedr[-idx:], axis=<NUM_LIT:0>)<EOL><DEDENT>if linear:<EOL><INDENT>return peak - valley<EOL><DEDENT>else:<EOL><INDENT>return power_to_db(peak) - power_to_db(valley)<EOL><DEDENT>

Compute spectral contrast [1]_

    .. [1] Jiang, Dan-Ning, Lie Lu, Hong-Jiang Zhang, Jian-Hua Tao,
           and Lian-Hong Cai.
           "Music type classification by spectral contrast feature."
           In Multimedia and Expo, 2002. ICME'02. Proceedings.
           2002 IEEE International Conference on, vol. 1, pp. 113-116.
           IEEE, 2002.

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

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

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

    n_fft : int > 0 [scalar]
        FFT window size

    hop_length : int > 0 [scalar]
        hop length for STFT. See `librosa.core.stft` for details.

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

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

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

        .. see also:: `filters.get_window`

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

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

    freq : None or np.ndarray [shape=(d,)]
        Center frequencies for spectrogram bins.
        If `None`, then FFT bin center frequencies are used.
        Otherwise, it can be a single array of `d` center frequencies.

    fmin : float > 0
        Frequency cutoff for the first bin `[0, fmin]`
        Subsequent bins will cover `[fmin, 2*fmin]`, `[2*fmin, 4*fmin]`, etc.

    n_bands : int > 1
        number of frequency bands

    quantile : float in (0, 1)
        quantile for determining peaks and valleys

    linear : bool
        If `True`, return the linear difference of magnitudes:
        `peaks - valleys`.

        If `False`, return the logarithmic difference:
        `log(peaks) - log(valleys)`.

    Returns
    -------
    contrast : np.ndarray [shape=(n_bands + 1, t)]
        each row of spectral contrast values corresponds to a given
        octave-based frequency

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> S = np.abs(librosa.stft(y))
    >>> contrast = librosa.feature.spectral_contrast(S=S, sr=sr)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2, 1, 1)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S,
    ...                                                  ref=np.max),
    ...                          y_axis='log')
    >>> plt.colorbar(format='%+2.0f dB')
    >>> plt.title('Power spectrogram')
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(contrast, x_axis='time')
    >>> plt.colorbar()
    >>> plt.ylabel('Frequency bands')
    >>> plt.title('Spectral contrast')
    >>> plt.tight_layout()


def spectral_rolloff(y=None, sr=<NUM_LIT>, S=None, n_fft=<NUM_LIT>, hop_length=<NUM_LIT>,<EOL>win_length=None, window='<STR_LIT>', center=True, pad_mode='<STR_LIT>',<EOL>freq=None, roll_percent=<NUM_LIT>):

if not <NUM_LIT:0.0> < roll_percent < <NUM_LIT:1.0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length,<EOL>win_length=win_length, window=window, center=center,<EOL>pad_mode=pad_mode)<EOL>if not np.isrealobj(S):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>elif np.any(S < <NUM_LIT:0>):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>if freq is None:<EOL><INDENT>freq = fft_frequencies(sr=sr, n_fft=n_fft)<EOL><DEDENT>if freq.ndim == <NUM_LIT:1>:<EOL><INDENT>freq = freq.reshape((-<NUM_LIT:1>, <NUM_LIT:1>))<EOL><DEDENT>total_energy = np.cumsum(S, axis=<NUM_LIT:0>)<EOL>threshold = roll_percent * total_energy[-<NUM_LIT:1>]<EOL>ind = np.where(total_energy < threshold, np.nan, <NUM_LIT:1>)<EOL>return np.nanmin(ind * freq, axis=<NUM_LIT:0>, keepdims=True)<EOL>

Compute roll-off frequency.

    The roll-off frequency is defined for each frame as the center frequency
    for a spectrogram bin such that at least roll_percent (0.85 by default)
    of the energy of the spectrum in this frame is contained in this bin and
    the bins below. This can be used to, e.g., approximate the maximum (or
    minimum) frequency by setting roll_percent to a value close to 1 (or 0).

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

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

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

    n_fft : int > 0 [scalar]
        FFT window size

    hop_length : int > 0 [scalar]
        hop length for STFT. See `librosa.core.stft` for details.

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

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

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

        .. see also:: `filters.get_window`

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

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

    freq : None or np.ndarray [shape=(d,) or shape=(d, t)]
        Center frequencies for spectrogram bins.
        If `None`, then FFT bin center frequencies are used.
        Otherwise, it can be a single array of `d` center frequencies,

        .. note:: `freq` is assumed to be sorted in increasing order

    roll_percent : float [0 < roll_percent < 1]
        Roll-off percentage.

    Returns
    -------
    rolloff : np.ndarray [shape=(1, t)]
        roll-off frequency for each frame

    Examples
    --------
    From time-series input

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> # Approximate maximum frequencies with roll_percent=0.85 (default)
    >>> rolloff = librosa.feature.spectral_rolloff(y=y, sr=sr)
    >>> rolloff
    array([[ 8376.416,   968.994, ...,  8925.513,  9108.545]])
    >>> # Approximate minimum frequencies with roll_percent=0.1
    >>> rolloff = librosa.feature.spectral_rolloff(y=y, sr=sr, roll_percent=0.1)
    >>> rolloff
    array([[ 75.36621094,  64.59960938,  64.59960938, ...,  75.36621094,
         75.36621094,  64.59960938]])

    From spectrogram input

    >>> S, phase = librosa.magphase(librosa.stft(y))
    >>> librosa.feature.spectral_rolloff(S=S, sr=sr)
    array([[ 8376.416,   968.994, ...,  8925.513,  9108.545]])

    >>> # With a higher roll percentage:
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.feature.spectral_rolloff(y=y, sr=sr, roll_percent=0.95)
    array([[ 10012.939,   3003.882, ...,  10034.473,  10077.539]])

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2, 1, 1)
    >>> plt.semilogy(rolloff.T, label='Roll-off frequency')
    >>> plt.ylabel('Hz')
    >>> plt.xticks([])
    >>> plt.xlim([0, rolloff.shape[-1]])
    >>> plt.legend()
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.title('log Power spectrogram')
    >>> plt.tight_layout()


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

if amin <= <NUM_LIT:0>:<EOL><INDENT>raise ParameterError('<STR_LIT>')<EOL><DEDENT>S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length,<EOL>power=<NUM_LIT:1.>, win_length=win_length, window=window,<EOL>center=center, pad_mode=pad_mode)<EOL>if not np.isrealobj(S):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>elif np.any(S < <NUM_LIT:0>):<EOL><INDENT>raise ParameterError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>S_thresh = np.maximum(amin, S ** power)<EOL>gmean = np.exp(np.mean(np.log(S_thresh), axis=<NUM_LIT:0>, keepdims=True))<EOL>amean = np.mean(S_thresh, axis=<NUM_LIT:0>, keepdims=True)<EOL>return gmean / amean<EOL>

Compute spectral flatness

    Spectral flatness (or tonality coefficient) is a measure to
    quantify how much noise-like a sound is, as opposed to being
    tone-like [1]_. A high spectral flatness (closer to 1.0)
    indicates the spectrum is similar to white noise.
    It is often converted to decibel.

    .. [1] Dubnov, Shlomo  "Generalization of spectral flatness
           measure for non-gaussian linear processes"
           IEEE Signal Processing Letters, 2004, Vol. 11.

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

    S : np.ndarray [shape=(d, t)] or None
        (optional) pre-computed spectrogram magnitude

    n_fft : int > 0 [scalar]
        FFT window size

    hop_length : int > 0 [scalar]
        hop length for STFT. See `librosa.core.stft` for details.

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

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

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

        .. see also:: `filters.get_window`

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

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

    amin : float > 0 [scalar]
        minimum threshold for `S` (=added noise floor for numerical stability)

    power : float > 0 [scalar]
        Exponent for the magnitude spectrogram.
        e.g., 1 for energy, 2 for power, etc.
        Power spectrogram is usually used for computing spectral flatness.

    Returns
    -------
    flatness : np.ndarray [shape=(1, t)]
        spectral flatness for each frame.
        The returned value is in [0, 1] and often converted to dB scale.

    Examples
    --------
    From time-series input

    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> flatness = librosa.feature.spectral_flatness(y=y)
    >>> flatness
    array([[  1.00000e+00,   5.82299e-03,   5.64624e-04, ...,   9.99063e-01,
          1.00000e+00,   1.00000e+00]], dtype=float32)

    From spectrogram input

    >>> S, phase = librosa.magphase(librosa.stft(y))
    >>> librosa.feature.spectral_flatness(S=S)
    array([[  1.00000e+00,   5.82299e-03,   5.64624e-04, ...,   9.99063e-01,
          1.00000e+00,   1.00000e+00]], dtype=float32)

    From power spectrogram input

    >>> S, phase = librosa.magphase(librosa.stft(y))
    >>> S_power = S ** 2
    >>> librosa.feature.spectral_flatness(S=S_power, power=1.0)
    array([[  1.00000e+00,   5.82299e-03,   5.64624e-04, ...,   9.99063e-01,
          1.00000e+00,   1.00000e+00]], dtype=float32)


def rms(y=None, S=None, frame_length=<NUM_LIT>, hop_length=<NUM_LIT>,<EOL>center=True, pad_mode='<STR_LIT>'):

if y is not None and S is not None:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if y is not None:<EOL><INDENT>y = to_mono(y)<EOL>if center:<EOL><INDENT>y = np.pad(y, int(frame_length // <NUM_LIT:2>), mode=pad_mode)<EOL><DEDENT>x = util.frame(y,<EOL>frame_length=frame_length,<EOL>hop_length=hop_length)<EOL><DEDENT>elif S is not None:<EOL><INDENT>x, _ = _spectrogram(y=y, S=S,<EOL>n_fft=frame_length,<EOL>hop_length=hop_length)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>return np.sqrt(np.mean(np.abs(x)**<NUM_LIT:2>, axis=<NUM_LIT:0>, keepdims=True))<EOL>

Compute root-mean-square (RMS) value for each frame, either from the
    audio samples `y` or from a spectrogram `S`.

    Computing the RMS value from audio samples is faster as it doesn't require
    a STFT calculation. However, using a spectrogram will give a more accurate
    representation of energy over time because its frames can be windowed,
    thus prefer using `S` if it's already available.

    Parameters
    ----------
    y : np.ndarray [shape=(n,)] or None
        (optional) audio time series. Required if `S` is not input.

    S : np.ndarray [shape=(d, t)] or None
        (optional) spectrogram magnitude. Required if `y` is not input.

    frame_length : int > 0 [scalar]
        length of analysis frame (in samples) for energy calculation

    hop_length : int > 0 [scalar]
        hop length for STFT. See `librosa.core.stft` for details.

    center : bool
        If `True` and operating on time-domain input (`y`), pad the signal
        by `frame_length//2` on either side.

        If operating on spectrogram input, this has no effect.

    pad_mode : str
        Padding mode for centered analysis.  See `np.pad` for valid
        values.

    Returns
    -------
    rms : np.ndarray [shape=(1, t)]
        RMS value for each frame

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.feature.rms(y=y)
    array([[ 0.   ,  0.056, ...,  0.   ,  0.   ]], dtype=float32)

    Or from spectrogram input

    >>> S, phase = librosa.magphase(librosa.stft(y))
    >>> rms = librosa.feature.rms(S=S)

    >>> import matplotlib.pyplot as plt
    >>> plt.figure()
    >>> plt.subplot(2, 1, 1)
    >>> plt.semilogy(rms.T, label='RMS Energy')
    >>> plt.xticks([])
    >>> plt.xlim([0, rms.shape[-1]])
    >>> plt.legend(loc='best')
    >>> plt.subplot(2, 1, 2)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max),
    ...                          y_axis='log', x_axis='time')
    >>> plt.title('log Power spectrogram')
    >>> plt.tight_layout()

    Use a STFT window of constant ones and no frame centering to get consistent
    results with the RMS computed from the audio samples `y`

    >>> S = librosa.magphase(librosa.stft(y, window=np.ones, center=False))[0]
    >>> librosa.feature.rms(S=S)


def poly_features(y=None, sr=<NUM_LIT>, S=None, n_fft=<NUM_LIT>, hop_length=<NUM_LIT>,<EOL>win_length=None, window='<STR_LIT>', center=True, pad_mode='<STR_LIT>',<EOL>order=<NUM_LIT:1>, freq=None):

S, n_fft = _spectrogram(y=y, S=S, n_fft=n_fft, hop_length=hop_length,<EOL>win_length=win_length, window=window, center=center,<EOL>pad_mode=pad_mode)<EOL>if freq is None:<EOL><INDENT>freq = fft_frequencies(sr=sr, n_fft=n_fft)<EOL><DEDENT>if freq.ndim == <NUM_LIT:1>:<EOL><INDENT>coefficients = np.polyfit(freq, S, order)<EOL><DEDENT>else:<EOL><INDENT>coefficients = np.concatenate([[np.polyfit(freq[:, i], S[:, i], order)]<EOL>for i in range(S.shape[<NUM_LIT:1>])], axis=<NUM_LIT:0>).T<EOL><DEDENT>return coefficients<EOL>

Get coefficients of fitting an nth-order polynomial to the columns
    of a spectrogram.

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

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

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

    n_fft : int > 0 [scalar]
        FFT window size

    hop_length : int > 0 [scalar]
        hop length for STFT. See `librosa.core.stft` for details.

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

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

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

        .. see also:: `filters.get_window`

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

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

    order : int > 0
        order of the polynomial to fit

    freq : None or np.ndarray [shape=(d,) or shape=(d, t)]
        Center frequencies for spectrogram bins.
        If `None`, then FFT bin center frequencies are used.
        Otherwise, it can be a single array of `d` center frequencies,
        or a matrix of center frequencies as constructed by
        `librosa.core.ifgram`

    Returns
    -------
    coefficients : np.ndarray [shape=(order+1, t)]
        polynomial coefficients for each frame.

        `coeffecients[0]` corresponds to the highest degree (`order`),

        `coefficients[1]` corresponds to the next highest degree (`order-1`),

        down to the constant term `coefficients[order]`.

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> S = np.abs(librosa.stft(y))

    Fit a degree-0 polynomial (constant) to each frame

    >>> p0 = librosa.feature.poly_features(S=S, order=0)

    Fit a linear polynomial to each frame

    >>> p1 = librosa.feature.poly_features(S=S, order=1)

    Fit a quadratic to each frame

    >>> p2 = librosa.feature.poly_features(S=S, order=2)

    Plot the results for comparison

    >>> import matplotlib.pyplot as plt
    >>> plt.figure(figsize=(8, 8))
    >>> ax = plt.subplot(4,1,1)
    >>> plt.plot(p2[2], label='order=2', alpha=0.8)
    >>> plt.plot(p1[1], label='order=1', alpha=0.8)
    >>> plt.plot(p0[0], label='order=0', alpha=0.8)
    >>> plt.xticks([])
    >>> plt.ylabel('Constant')
    >>> plt.legend()
    >>> plt.subplot(4,1,2, sharex=ax)
    >>> plt.plot(p2[1], label='order=2', alpha=0.8)
    >>> plt.plot(p1[0], label='order=1', alpha=0.8)
    >>> plt.xticks([])
    >>> plt.ylabel('Linear')
    >>> plt.subplot(4,1,3, sharex=ax)
    >>> plt.plot(p2[0], label='order=2', alpha=0.8)
    >>> plt.xticks([])
    >>> plt.ylabel('Quadratic')
    >>> plt.subplot(4,1,4, sharex=ax)
    >>> librosa.display.specshow(librosa.amplitude_to_db(S, ref=np.max),
    ...                          y_axis='log')
    >>> plt.tight_layout()


def zero_crossing_rate(y, frame_length=<NUM_LIT>, hop_length=<NUM_LIT>, center=True,<EOL>**kwargs):

util.valid_audio(y)<EOL>if center:<EOL><INDENT>y = np.pad(y, int(frame_length // <NUM_LIT:2>), mode='<STR_LIT>')<EOL><DEDENT>y_framed = util.frame(y, frame_length, hop_length)<EOL>kwargs['<STR_LIT>'] = <NUM_LIT:0><EOL>kwargs.setdefault('<STR_LIT>', False)<EOL>crossings = zero_crossings(y_framed, **kwargs)<EOL>return np.mean(crossings, axis=<NUM_LIT:0>, keepdims=True)<EOL>

Compute the zero-crossing rate of an audio time series.

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

    frame_length : int > 0
        Length of the frame over which to compute zero crossing rates

    hop_length : int > 0
        Number of samples to advance for each frame

    center : bool
        If `True`, frames are centered by padding the edges of `y`.
        This is similar to the padding in `librosa.core.stft`,
        but uses edge-value copies instead of reflection.

    kwargs : additional keyword arguments
        See `librosa.core.zero_crossings`

        .. note:: By default, the `pad` parameter is set to `False`, which
            differs from the default specified by
            `librosa.core.zero_crossings`.

    Returns
    -------
    zcr : np.ndarray [shape=(1, t)]
        `zcr[0, i]` is the fraction of zero crossings in the
        `i` th frame

    See Also
    --------
    librosa.core.zero_crossings
        Compute zero-crossings in a time-series

    Examples
    --------
    >>> y, sr = librosa.load(librosa.util.example_audio_file())
    >>> librosa.feature.zero_crossing_rate(y)
    array([[ 0.134,  0.139, ...,  0.387,  0.322]])