U
    5dv                     @   sR  d Z ddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZmZ ddlmZmZ dd	lmZ d
dlmZ d
dlmZ d
dlmZ d
dlmZ d
dlmZ ddddddgZeedddddddddddddd ddd!d"dZeedddddddddddddd ddd!d#dZeedddddddddddddd dd$d%dZeed&ddddddddddddd'dd(d)dZeeddddddddddddddd ddd*d+dZed,ddddej dfd-d.Z!d/d0 Z"dCd2d3Z#d4d5 Z$d6d7 Z%eddd8d9d: Z&ed;ddddddddddd d<ddd=d>dd?d@dZ'dAdB Z(dS )DzConstant-Q transforms    N)jit   )audio)
get_fftlib)cqt_frequencies
note_to_hz)stftistft)estimate_tuning   )cache)filters)util)ParameterError)deprecate_positional_argscqt
hybrid_cqt
pseudo_cqticqtgriffinlim_cqtvqt   )leveli"V  i   T              g{Gz?hannTZconstant)sr
hop_lengthfminn_binsbins_per_octavetuningfilter_scalenormsparsitywindowscalepad_moderes_typedtypec                C   s(   t | ||||d|||||	|
||||dS )a  Compute the constant-Q transform of an audio signal.

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

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

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

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

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

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

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

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

    tuning : None or float
        Tuning offset in fractions of a bin.

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

        The minimum frequency of the resulting CQT will be modified to
        ``fmin * 2**(tuning / bins_per_octave)``.

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

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

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

        Set ``sparsity=0`` to disable sparsification.

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

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

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

    pad_mode : string
        Padding mode for centered frame analysis.

        See also: `librosa.stft` and `numpy.pad`.

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

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

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

    dtype : np.dtype
        The (complex) data type of the output array.  By default, this is inferred to match
        the numerical precision of the input signal.

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

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

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

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

    >>> import matplotlib.pyplot as plt
    >>> y, sr = librosa.load(librosa.ex('trumpet'))
    >>> C = np.abs(librosa.cqt(y, sr=sr))
    >>> fig, ax = plt.subplots()
    >>> img = librosa.display.specshow(librosa.amplitude_to_db(C, ref=np.max),
    ...                                sr=sr, x_axis='time', y_axis='cqt_note', ax=ax)
    >>> ax.set_title('Constant-Q power spectrum')
    >>> fig.colorbar(img, ax=ax, format="%+2.0f dB")

    Limit the frequency range

    >>> C = np.abs(librosa.cqt(y, sr=sr, fmin=librosa.note_to_hz('C2'),
    ...                 n_bins=60))
    >>> C
    array([[6.830e-04, 6.361e-04, ..., 7.362e-09, 9.102e-09],
           [5.366e-04, 4.818e-04, ..., 8.953e-09, 1.067e-08],
           ...,
           [4.288e-02, 4.580e-01, ..., 1.529e-05, 5.572e-06],
           [2.965e-03, 1.508e-01, ..., 8.965e-06, 1.455e-05]])

    Using a higher frequency resolution

    >>> C = np.abs(librosa.cqt(y, sr=sr, fmin=librosa.note_to_hz('C2'),
    ...                 n_bins=60 * 2, bins_per_octave=12 * 2))
    >>> C
    array([[5.468e-04, 5.382e-04, ..., 5.911e-09, 6.105e-09],
           [4.118e-04, 4.014e-04, ..., 7.788e-09, 8.160e-09],
           ...,
           [2.780e-03, 1.424e-01, ..., 4.225e-06, 2.388e-05],
           [5.147e-02, 6.959e-02, ..., 1.694e-05, 5.811e-06]])
    r   )yr   r   r   r    gammar!   r"   r#   r$   r%   r&   r'   r(   r)   r*   )r   )r+   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*    r-   :/tmp/pip-unpacked-wheel-8l90aumz/librosa/core/constantq.pyr      s&     c                C   s$  |dkrt d}|dkr&t| ||d}|d||   }t|||d}t|}tj||||
|d\}}dtt| d| k }t	t
|}|| }g }|dkrt|| }|t| ||||||||	|
|||d	 |dkr|tt| ||||||||	|
||||d
 t|||d jS )a	  Compute the hybrid constant-Q transform of an audio signal.

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

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

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

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

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

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

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

    tuning : None or float
        Tuning offset in fractions of a bin.

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

        The minimum frequency of the resulting CQT will be modified to
        ``fmin * 2**(tuning / bins_per_octave)``.

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

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

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

        Set ``sparsity=0`` to disable sparsification.

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

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

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

    pad_mode : string
        Padding mode for centered frame analysis.

        See also: `librosa.stft` and `numpy.pad`.

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

    dtype : np.dtype, optional
        The complex dtype to use for computing the CQT.
        By default, this is inferred to match the precision of
        the input signal.

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

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

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

    NC1r+   r   r!          @)r   r!   )freqsr   r#   r&   alphar   r   )r   r   r   r    r!   r#   r$   r%   r&   r'   r(   r*   )r   r   r   r    r!   r#   r$   r%   r&   r'   r(   r)   r*   )r   r
   r   __bpo_to_alphar   wavelet_lengthsnpceillog2intsumminappendr   absr   __trim_stackr*   )r+   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r2   r3   lengths_Zpseudo_filtersZn_bins_pseudoZn_bins_fullcqt_respZfmin_pseudor-   r-   r.   r      sv    k    

)r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r*   c                C   s   |dkrt d}|dkr&t| ||d}|dkr:t| j}|d||   }t|||d}t|}tj|||
||d\}}t	|||||	||
||d	\}}}t
|}t| ||||d|d	d
}|r|t
| }n$tj||jdd}|t
|| 9 }|S )aP	  Compute the pseudo constant-Q transform of an audio signal.

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

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

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

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

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

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

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

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

    tuning : None or float
        Tuning offset in fractions of a bin.

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

        The minimum frequency of the resulting CQT will be modified to
        ``fmin * 2**(tuning / bins_per_octave)``.

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

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

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

        Set ``sparsity=0`` to disable sparsification.

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

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

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

    pad_mode : string
        Padding mode for centered frame analysis.

        See also: `librosa.stft` and `numpy.pad`.

    dtype : np.dtype, optional
        The complex data type for CQT calculations.
        By default, this is inferred to match the precision of the input signal.

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

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

    Nr/   r0   r1   r   r    r!   r2   r   r&   r#   r3   )r   r&   r*   r3   r   F)r&   r*   phasendimZaxes)r   r
   r   	dtype_r2cr*   r   r5   r   r6   __vqt_filter_fftr7   r>   __cqt_responsesqrt	expand_torH   )r+   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r*   r2   r3   r@   rA   	fft_basisn_fftCr-   r-   r.   r   ~  sV    c    

(   fft)r   r   r   r!   r"   r#   r$   r%   r&   r'   lengthr)   r*   c          %      C   s  |dkrt d}|d||   }| jd }ttt|| }t|||d}t|}tj	|||	||d\}}|dk	rtt|t
| | }| dd|f } t|}d}|g}|g}t|d D ]`}|d	 d
 d	kr|d	|d	 d  |d	|d	 d
  q|d	|d	  |d	|d	  qtt||D ]>\}\}}t||||  }t|| || | }t||| ||||	||d\}}} |j }!dtjtt|!d
 d	d }"|"|||  9 }"|
rtjd|!|| |"| d|ddf dd}#n"tjd|!|"| d|ddf dd}#t|#d||d}$tj|$d|| |ddd}$|dkrV|$}n|dd|$jd f  |$7  < q6|rtj||d}|S )a  Compute the inverse constant-Q transform.

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

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

    sr : number > 0 [scalar]
        sampling rate of the signal

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

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

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

    tuning : float [scalar]
        Tuning offset in fractions of a bin.

        The minimum frequency of the CQT will be modified to
        ``fmin * 2**(tuning / bins_per_octave)``.

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

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

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

        Set ``sparsity=0`` to disable sparsification.

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

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

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

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

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

    dtype : numeric type
        Real numeric type for ``y``.  Default is inferred to match the numerical
        precision of the input CQT.

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

    See Also
    --------
    cqt
    librosa.resample

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

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

    >>> y, sr = librosa.load(librosa.ex('trumpet'))
    >>> C = librosa.cqt(y=y, sr=sr)
    >>> y_hat = librosa.icqt(C=C, sr=sr)

    Or with a different hop length and frequency resolution:

    >>> hop_length = 256
    >>> bins_per_octave = 12 * 3
    >>> C = librosa.cqt(y=y, sr=sr, hop_length=256, n_bins=7*bins_per_octave,
    ...                 bins_per_octave=bins_per_octave)
    >>> y_hat = librosa.icqt(C=C, sr=sr, hop_length=hop_length,
    ...                 bins_per_octave=bins_per_octave)
    Nr/   r1   rF   rC   rD   .r   r   r   g      ?)r&   r*   r3   )axiszfc,c,c,...ct->...ftT)optimizezfc,c,...ct->...ftones)r&   r   r*   F)orig_sr	target_srr)   r'   Zfixr4   )size)r   shaper:   r7   r8   floatr   r5   r   r6   maxrL   rangeinsert	enumeratezipr<   slicerJ   HZtodenser;   r>   ZasarrayZeinsumr	   r   resampler   Z
fix_length)%rP   r   r   r   r!   r"   r#   r$   r%   r&   r'   rS   r)   r*   r    	n_octavesr2   r3   r@   Zf_cutoffZn_framesZC_scaler+   ZsrsZhopsimy_srmy_hop	n_filtersslrN   rO   rA   Z	inv_basisZ
freq_powerZD_octZy_octr-   r-   r.   r     s    t
    


"	    	
")r   r   r   r    r,   r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   c          &      C   s  t tt|| }t||}|dkr0td}|dkrFt| ||d}|dkrZt| j	}|d||   }t
|||d}|| d }t|}t|}tj||||||d\}}|d }||krtd| d| d	d
}|sd}|tj| k rd}nd}t| |||||||\} }}g }d}|r|dkr|| d }t||||	|
||||d	\}}}|t| |||||d d}d}| ||  }} }!t||D ]}"|"dkrt| d}#nt| |"d  | |" }#||# }$t| |$||	|
||||d	\}}}|dd  t||  9  < |t|||!|||d |!d dkr|!d }!| d } tj|dd|dd}qt|||}%|rtj||||||d\}}tj||%jdd}|%t| }%|%S )u  Compute the variable-Q transform of an audio signal.

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

    .. [#] Schörkhuber, Christian, Anssi Klapuri, Nicki Holighaus, and Monika Dörfler.
        "A Matlab toolbox for efficient perfect reconstruction time-frequency
        transforms with log-frequency resolution."
        In Audio Engineering Society Conference: 53rd International Conference: Semantic Audio.
        Audio Engineering Society, 2014.

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

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

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

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

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

    gamma : number > 0 [scalar]
        Bandwidth offset for determining filter lengths.

        If ``gamma=0``, produces the constant-Q transform.

        If 'gamma=None', gamma will be calculated such that filter bandwidths are equal to a
        constant fraction of the equivalent rectangular bandwidths (ERB). This is accomplished
        by solving for the gamma which gives::

            B_k = alpha * f_k + gamma = C * ERB(f_k),

        where ``B_k`` is the bandwidth of filter ``k`` with center frequency ``f_k``, alpha
        is the inverse of what would be the constant Q-factor, and ``C = alpha / 0.108`` is the
        constant fraction across all filters.

        Here we use ``ERB(f_k) = 24.7 + 0.108 * f_k``, the best-fit curve derived
        from experimental data in [#]_.

        .. [#] Glasberg, Brian R., and Brian CJ Moore.
            "Derivation of auditory filter shapes from notched-noise data."
            Hearing research 47.1-2 (1990): 103-138.

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

    tuning : None or float
        Tuning offset in fractions of a bin.

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

        The minimum frequency of the resulting VQT will be modified to
        ``fmin * 2**(tuning / bins_per_octave)``.

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

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

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

        Set ``sparsity=0`` to disable sparsification.

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

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

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

    pad_mode : string
        Padding mode for centered frame analysis.

        See also: `librosa.stft` and `numpy.pad`.

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

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

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

    dtype : np.dtype
        The dtype of the output array.  By default, this is inferred to match the
        numerical precision of the input signal.

    Returns
    -------
    VQT : np.ndarray [shape=(..., n_bins, t), dtype=np.complex]
        Variable-Q value each frequency at each time.

    See Also
    --------
    cqt

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

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

    >>> import matplotlib.pyplot as plt
    >>> y, sr = librosa.load(librosa.ex('choice'), duration=5)
    >>> C = np.abs(librosa.cqt(y, sr=sr))
    >>> V = np.abs(librosa.vqt(y, sr=sr))
    >>> fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True)
    >>> librosa.display.specshow(librosa.amplitude_to_db(C, ref=np.max),
    ...                          sr=sr, x_axis='time', y_axis='cqt_note', ax=ax[0])
    >>> ax[0].set(title='Constant-Q power spectrum', xlabel=None)
    >>> ax[0].label_outer()
    >>> img = librosa.display.specshow(librosa.amplitude_to_db(V, ref=np.max),
    ...                                sr=sr, x_axis='time', y_axis='cqt_note', ax=ax[1])
    >>> ax[1].set_title('Variable-Q power spectrum')
    >>> fig.colorbar(img, ax=ax, format="%+2.0f dB")
    Nr/   r0   r1   )r    r   r!   )r2   r   r&   r#   r,   r3   z!Wavelet basis with max frequency=z$ would exceed the Nyquist frequency=z,. Try reducing the number of frequency bins.FTkaiser_fastZkaiser_bestr   )r&   r,   r*   r3   r*   r   r   rW   rX   r)   r'   rF   rG   )r:   r7   r8   r[   r<   r   r
   r   rI   r*   r   r\   r5   r   r6   r   r   
BW_FASTEST__early_downsamplerJ   r=   rK   r]   ra   rL   rc   r?   rM   rH   )&r+   r   r   r   r    r,   r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   rd   rh   r2   Z	freqs_topZfmax_tr3   r@   filter_cutoffnyquistZauto_resampleZvqt_respZ	oct_startrN   rO   rA   Zmy_yrf   rg   re   ri   Z	freqs_octVr-   r-   r.   r     s     !



       

    



   c
              
   C   s   t j|| ||d|||	d\}
}|
jd }|dk	rh|ddtt|  k rhtddtt|  }|
|ddtjf t| 9 }
t	 }|j
|
|ddddd|d d f }tj|||d}|||fS )	z6Generate the frequency domain variable-Q filter basis.T)r2   r   r#   r$   Zpad_fftr&   r,   r3   r   Nr1   )nrT   r   )Zquantiler*   )r   ZwaveletrZ   r7   r8   r9   r:   Znewaxisr[   r   rR   r   Zsparsify_rows)r   r2   r#   r$   r%   r   r&   r,   r*   r3   Zbasisr@   rO   rR   rN   r-   r-   r.   rJ   .  s$    

$(rJ   c           	      C   s   t dd | D }t| d j}||d< ||d< tj||dd}|}| D ]p}|jd }||k r|d| d	d	|f |dd	|d	d	f< n&|dd	|f |d|| |d	d	f< ||8 }qH|S )
z?Helper function to trim and stack a collection of CQT responsesc                 s   s   | ]}|j d  V  qdS )r4   N)rZ   ).0c_ir-   r-   r.   	<genexpr>^  s     z__trim_stack.<locals>.<genexpr>r   rF   r4   F)r*   order.N)r<   listrZ   r7   empty)	rB   r    r*   Zmax_colrZ   Zcqt_outendru   Zn_octr-   r-   r.   r?   [  s    
,&
r?   rV   c                 C   s   t | |||||d}|s"t|}|d|jd |jd f}	tj|	jd |jd |	jd f|jd}
t|	jd D ]}||	| |
|< qtt	|j}|jd |d< |
|S )z3Compute the filter response with a target STFT hop.)rO   r   r&   r(   r*   r4   rF   r   rk   )
r   r7   r>   ZreshaperZ   rz   r*   r]   dotry   )r+   rO   r   rN   moder&   rE   r*   DZDrZoutput_flatre   rZ   r-   r-   r.   rK   v  s(         
 
rK   c              	   C   sP   t dttttj|  | d d }t|}t d|| d }t||S )z3Compute the number of early downsampling operationsr   r   )	r\   r:   r7   r8   r9   r   rm   __num_two_factorsr<   )rp   ro   r   rd   Zdownsample_count1num_twosZdownsample_count2r-   r-   r.   __early_downsample_count  s     $r   c                 C   s   t ||||}|dkr|dkrd| }	||	 }| jd |	k rPtdt| ||t|	 }
tj| ||
|dd} |s| t	|	9 } |
}| ||fS )z=Perform early downsampling on an audio signal, if it applies.r   rj   r   r4   z9Input signal length={:d} is too short for {:d}-octave CQTTrl   )
r   rZ   r   formatlenr[   r   rc   r7   rL   )r+   r   r   r)   rd   rp   ro   r'   Zdownsample_countZdownsample_factorZnew_srr-   r-   r.   rn     s8            rn   )Znopythonr   c                 C   s2   | dkrdS d}| d dkr.|d7 }| d } q|S )zjReturn how many times integer x can be evenly divided by 2.

    Returns 0 for non-positive integers.
    r   r   r   r-   )xr   r-   r-   r.   r     s    
r       rj   gGz?random)n_iterr   r   r   r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   rS   momentuminitrandom_statec                C   s  |dkrt d}|dkr tj}n,t|tr:tjj|d}nt|tjjrL|}|dkrjtjd|dd n|dk rt	d	|tj
| jtjd
}t|}|dkrtdtj |j| j  |dd< n$|dkrd|dd< nt	d|d}t|D ]}|}t| | |||||||
|||||	|d}t|||| jd |||||
|||	||d}||d|  |  |dd< |dd  t||   < qt| | |||||||
|||||	|dS )u  Approximate constant-Q magnitude spectrogram inversion using the "fast" Griffin-Lim
    algorithm.

    Given the magnitude of a constant-Q spectrogram (``C``), the algorithm randomly initializes
    phase estimates, and then alternates forward- and inverse-CQT operations. [#]_

    This implementation is based on the (fast) Griffin-Lim method for Short-time Fourier Transforms, [#]_
    but adapted for use with constant-Q spectrograms.

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

    .. [#] Perraudin, N., Balazs, P., & Søndergaard, P. L.
        "A fast Griffin-Lim algorithm,"
        IEEE Workshop on Applications of Signal Processing to Audio and Acoustics (pp. 1-4),
        Oct. 2013.

    Parameters
    ----------
    C : np.ndarray [shape=(..., n_bins, n_frames)]
        The constant-Q magnitude spectrogram

    n_iter : int > 0
        The number of iterations to run

    sr : number > 0
        Audio sampling rate

    hop_length : int > 0
        The hop length of the CQT

    fmin : number > 0
        Minimum frequency for the CQT.

        If not provided, it defaults to `C1`.

    bins_per_octave : int > 0
        Number of bins per octave

    tuning : float
        Tuning deviation from A440, in fractions of a bin

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

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

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

        Set ``sparsity=0`` to disable sparsification.

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

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

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

    pad_mode : string
        Padding mode for centered frame analysis.

        See also: `librosa.stft` and `numpy.pad`.

    res_type : string
        The resampling mode for recursive downsampling.

        By default, CQT uses an adaptive mode selection to
        trade accuracy at high frequencies for efficiency at low
        frequencies.

        Griffin-Lim uses the efficient (fast) resampling mode by default.

        See ``librosa.resample`` for a list of available options.

    dtype : numeric type
        Real numeric type for ``y``.  Default is inferred to match the precision
        of the input CQT.

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

    momentum : float > 0
        The momentum parameter for fast Griffin-Lim.
        Setting this to 0 recovers the original Griffin-Lim method.
        Values near 1 can lead to faster convergence, but above 1 may not converge.

    init : None or 'random' [default]
        If 'random' (the default), then phase values are initialized randomly
        according to ``random_state``.  This is recommended when the input ``C`` is
        a magnitude spectrogram with no initial phase estimates.

        If ``None``, then the phase is initialized from ``C``.  This is useful when
        an initial guess for phase can be provided, or when you want to resume
        Griffin-Lim from a previous output.

    random_state : None, int, or np.random.RandomState
        If int, random_state is the seed used by the random number generator
        for phase initialization.

        If `np.random.RandomState` instance, the random number generator itself.

        If ``None``, defaults to the current `np.random` object.

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

    See Also
    --------
    cqt
    icqt
    griffinlim
    filters.get_window
    resample

    Examples
    --------
    A basis CQT inverse example

    >>> y, sr = librosa.load(librosa.ex('trumpet', hq=True), sr=None)
    >>> # Get the CQT magnitude, 7 octaves at 36 bins per octave
    >>> C = np.abs(librosa.cqt(y=y, sr=sr, bins_per_octave=36, n_bins=7*36))
    >>> # Invert using Griffin-Lim
    >>> y_inv = librosa.griffinlim_cqt(C, sr=sr, bins_per_octave=36)
    >>> # And invert without estimating phase
    >>> y_icqt = librosa.icqt(C, sr=sr, bins_per_octave=36)

    Wave-plot the results

    >>> import matplotlib.pyplot as plt
    >>> fig, ax = plt.subplots(nrows=3, sharex=True, sharey=True)
    >>> librosa.display.waveshow(y, sr=sr, color='b', ax=ax[0])
    >>> ax[0].set(title='Original', xlabel=None)
    >>> ax[0].label_outer()
    >>> librosa.display.waveshow(y_inv, sr=sr, color='g', ax=ax[1])
    >>> ax[1].set(title='Griffin-Lim reconstruction', xlabel=None)
    >>> ax[1].label_outer()
    >>> librosa.display.waveshow(y_icqt, sr=sr, color='r', ax=ax[2])
    >>> ax[2].set(title='Magnitude-only icqt reconstruction')
    Nr/   )seedr   zGGriffin-Lim with momentum={} > 1 can be unstable. Proceed with caution!r   )
stacklevelr   z,griffinlim_cqt() called with momentum={} < 0rk   r   y               @g      ?z$init={} must either None or 'random'r   )r   r   r!   r   r"   r#   r&   rS   r)   r$   r'   r%   r*   rF   )r   r!   r    r   r   r"   r#   r&   r$   r'   r%   r(   r)   )r   r   r!   r"   r#   r   r&   rS   r)   r$   r'   r%   r*   )r   r7   r   
isinstancer:   ZRandomStatewarningswarnr   r   rz   rZ   	complex64r   ZtinyexppiZrandr]   r   r   r>   )rP   r   r   r   r   r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   rS   r   r   r   rngZanglesZepsZrebuiltrA   ZtprevZinverser-   r-   r.   r     s     1

& c                 C   s$   dd|   }|d d |d d  S )zCompute the alpha coefficient for a given number of bins per octave

    Parameters
    ----------
    bins_per_octave : int

    Returns
    -------
    alpha : number > 0
    r   r   r-   )r!   rr-   r-   r.   r5     s    r5   )rV   TN))__doc__r   Znumpyr7   Znumbar    r   rR   r   convertr   r   Zspectrumr   r	   Zpitchr
   _cacher   r   r   Zutil.exceptionsr   Zutil.decoratorsr   __all__r   r   r   r   r   r   rJ   r?   rK   r   rn   r   r   r5   r-   r-   r-   r.   <module>   s   - 7  `  2,     
#

  