o
    ۷iӰ                  +   @   s  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 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lmZmZmZm Z  ddl!m"Z"m#Z#m$Z$m%Z% g dZ&eddddddddddddddddd d!ej'd"e(d#e)d$ee$ d%e)d&e)d'ee( d(e(d)ee( d*e(d+e"d,e*d-e#d.ee+ d/ee d0ej'f d1d2Z,eddddddddddddddddd d!ej'd"e(d#e)d$ee$ d%e)d&e)d'ee( d(e(d)ee( d*e(d+e"d,e*d-e#d.e+d/ee d0ej'f d3d4Z-edddddddddddddddd5d!ej'd"e(d#e)d$ee$ d%e)d&e)d'ee( d(e(d)ee( d*e(d+e"d,e*d-e#d/ee d0ej'fd6d7Z.ed8ddddddddddddddd9d:ej'd"e(d#e)d$ee$ d&e)d'e(d(e(d)ee( d*e(d+e"d,e*d;ee) d.e+d/ee d0ej'fd<d=Z/eddddddd>dddddddddddd?d!ej'd"e(d#e)d$ee$ d%e)d@ee+ee( f dAee( d&e)d'ee( d(e(d)ee( d*e(d+e"d,e*d-e#d.ee+ d/ee d0ej'f$dBdCZ0edDddddej1dfdEdFZ2dGe ej' d%e)d/ed0ej'fdHdIZ3	d`dKdLZ4dMdN Z5dOdP Z6edddQdRdS Z7dTdddddddddddddddUdVddWd:ej'dXe)d"e(d#e)d$ee$ d&e)d'e(d(e(d)ee( d*e(d+e"d,e*d-e#d.e+d/ee d;ee) dYe(dZee+ d[eee)ej8j9ej8j:f  d0ej'f(d\d]Z;d&e)d0ej'fd^d_Z<dS )azConstant-Q transforms    N)jit   )audio)interval_frequencies)
get_fftlib)cqt_frequencies
note_to_hz)stftistft)estimate_tuning   )cache)filters)util)ParameterError)	DTypeLike)OptionalUnion
CollectionList)_WindowSpec_PadMode_FloatLike_co_ensure_not_reachable)cqt
hybrid_cqt
pseudo_cqticqtgriffinlim_cqtvqt   )leveli"V  i   T              g{Gz?hannTconstantsoxr_hq)sr
hop_lengthfminn_binsbins_per_octavetuningfilter_scalenormsparsitywindowscalepad_moderes_typedtypeyr(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   returnc                C   sp   t di d| d|d|d|d|dddd	d
|d|d|d|d|	d|
d|d|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
        The resampling mode for recursive downsampling.

    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]])
    r6   r(   r)   r*   r+   	intervalsequalgammar   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   N )r   )r6   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r;   r;   L/home/ubuntu/vllm_env/lib/python3.10/site-packages/librosa/core/constantq.pyr      sH    	
r   c                C   s8  |du rt d}|du rt| ||d}|d||   }t|||d}|dkr+t|}ntj|d}tj||||
|d\}}dtt	| d	| k }t
t|}|| }g }|d
krwt|| }|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r6   r(   r,          @)r*   r,   r   freqs)rA   r(   r.   r1   alphar   r   )r(   r)   r*   r+   r,   r.   r/   r0   r1   r2   r3   r5   )r(   r)   r*   r+   r,   r.   r/   r0   r1   r2   r3   r4   r5   )r   r   r   __et_relative_bwr   _relative_bandwidthwavelet_lengthsnpceillog2intsumminappendr   absr   __trim_stackr5   )r6   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   rA   rB   lengths_pseudo_filtersn_bins_pseudon_bins_fullcqt_respfmin_pseudor;   r;   r<   r      sr   h


r   )r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r5   c                C   s  |du rt d}|du rt| ||d}|du rt| j}|d||   }t|||d}|dkr5t|}ntj|d}tj	|||
||d\}}t
|||||	||
||d		\}}}t|}t| ||||d
|dd}|rs|t| }|S tj||jdd}|t|| 9 }|S )aO	  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=   r>   r?   r*   r+   r,   r   r@   rA   r(   r1   r.   rB   )r)   r1   r5   rB   r%   F)r1   r5   phasendimaxes)r   r   r   	dtype_r2cr5   r   rD   r   rE   rF   __vqt_filter_fftrG   rN   __cqt_responsesqrt	expand_tor\   )r6   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r5   rA   rB   rP   rQ   	fft_basisn_fftCr;   r;   r<   r   x  sT   `



r   (   )r(   r)   r*   r,   r-   r.   r/   r0   r1   r2   lengthr4   r5   re   rg   c          %      C   s  |du rt d}|d||   }| jd }ttt|| }t|||d}|dkr0t|}ntj	|d}tj
|||	||d\}}|dur[tt|t| | }| d	d|f } t|}d}|g}|g}t|d D ]/}|d
 d d
kr|d
|d
 d  |d
|d
 d  qn|d
|d
  |d
|d
  qntt||D ]\}\}}t||||  }t|| || | }t||| ||||	|| d\}}} | j }!dtjtt|!d
d }"|"|||  9 }"|
rt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u r5|$}q|d	d|$jd f  |$7  < q|dusLJ |rVtj||d}|S )af  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.
        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=   r?   rZ   rW   r   r@   rX   .r   r   g      ?)r1   rB   )axiszfc,c,c,...ct->...ftT)optimizezfc,c,...ct->...ftones)r1   r)   r5   F)orig_sr	target_srr4   r2   fixrC   size) r   shaperJ   rG   rH   floatr   rD   r   rE   rF   maxra   rangeinsert	enumerateziprL   slicer_   	conjugateTtodenserK   r   abs2asarrayeinsumr
   r   resample
fix_length)%re   r(   r)   r*   r,   r-   r.   r/   r0   r1   r2   rg   r4   r5   r+   	n_octavesrA   rB   rP   f_cutoffn_framesC_scaler6   srshopsimy_srmy_hop	n_filtersslrc   rd   rQ   	inv_basis
freq_powerD_octy_octr;   r;   r<   r     s   r




	
	 r   r9   )r(   r)   r*   r+   r8   r:   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r8   r:   c          &      C   sx  t |ts	t|}ttt|| }t||}|du r!td}|du r,t	| ||d}|du r6t
| j}|d||   }t||||dd}|| d }t|}|dkr\t|}ntj|d}tj||||	||d	\}}|d }||krtd
| d| d|du rtjdtdd d}t| |||||||\} }}g }| ||}}}t|D ]g}|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 |||}%|r:t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``

    intervals : str or array of floats in [1, 2)
        Either a string specification for an interval set, e.g.,
        `'equal'`, `'pythagorean'`, `'ji3'`, etc. or an array of
        intervals expressed as numbers between 1 and 2.
        .. see also:: librosa.interval_frequencies

    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
        The resampling mode for recursive downsampling.

    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=   r>   r?   T)r+   r*   r8   r,   sortr   r@   )rA   r(   r1   r.   r:   rB   z!Wavelet basis with max frequency=z$ would exceed the Nyquist frequency=z,. Try reducing the number of frequency bins.zdSupport for VQT with res_type=None is deprecated in librosa 0.10
and will be removed in version 1.0.r   )category
stacklevelr'   r   )r1   r:   r5   rB   r5   rk   rl   r4   r2   rZ   r[   )#
isinstancestrlenrJ   rG   rH   rq   rL   r   r   r   r^   r5   r   rr   rD   r   rE   rF   r   warningswarnFutureWarning__early_downsamplers   rw   r_   ra   rM   r`   r   r~   rO   rb   r\   )&r6   r(   r)   r*   r+   r8   r:   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r   r   rA   	freqs_topfmax_trB   rP   filter_cutoffnyquistvqt_respmy_yr   r   r   r   	freqs_oct	alpha_octrc   rd   rQ   Vr;   r;   r<   r     s    









r   
   c
              
   C   s   t j|| ||d|||	d\}
}|
jd }|dur4|ddtt|  k r4t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)rA   r(   r.   r/   pad_fftr1   r:   rB   r   Nr?   )nrh   r   )quantiler5   )r   waveletrp   rG   rH   rI   rJ   newaxisrq   r   fftr   sparsify_rows)r(   rA   r.   r/   r0   r)   r1   r:   r5   rB   basisrP   rd   r   rc   r;   r;   r<   r_     s$   

$(
r_   rU   c           	      C   s   t dd | D }t| d j}||d< ||d< tj||dd}|}| D ]8}|jd }||k rE|d| d	d	|f |dd	|d	d	f< n|dd	|f |d|| |d	d	f< ||8 }q$|S )
z,Trim and stack a collection of CQT responsesc                 s   s    | ]}|j d  V  qdS )rC   N)rp   ).0c_ir;   r;   r<   	<genexpr>H  s    z__trim_stack.<locals>.<genexpr>r   rZ   rC   F)r5   order.N)rL   listrp   rG   empty)	rU   r+   r5   max_colrp   cqt_outendr   n_octr;   r;   r<   rO   D  s   
,&
rO   rj   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 ]}||	| |
|< q:t	|j}|jd |d< |
|S )z3Compute the filter response with a target STFT hop.)rd   r)   r1   r3   r5   rC   rZ   r   r   )
r	   rG   rN   reshaperp   r   r5   rs   dotr   )r6   rd   r)   rc   moder1   rY   r5   DDroutput_flatr   rp   r;   r;   r<   r`   `  s   


r`   c              	   C   sJ   t dttt| | d d }t|}t d|| d }t||S )z3Compute the number of early downsampling operationsr   r   )rr   rJ   rG   rH   rI   __num_two_factorsrL   )r   r   r)   r   downsample_count1num_twosdownsample_count2r;   r;   r<   __early_downsample_count}  s   &
r   c                 C   s   t ||||}|dkrDd| }	||	 }| jd |	k r)tdt| dd|dd|t|	 }
tj| |	d|d	d
} |sB| t|	9 } |
}| ||fS )z=Perform early downsampling on an audio signal, if it applies.r   r   rC   zInput signal length=dz is too short for z-octave CQTr   Tr   )	r   rp   r   r   rq   r   r~   rG   ra   )r6   r(   r)   r4   r   r   r   r2   downsample_countdownsample_factornew_srr;   r;   r<   r     s(   

r   )nopythonr   c                 C   s<   | dkrdS d}| d dkr|d7 }| d } | d dks|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       gGz?random)n_iterr(   r)   r*   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   rg   momentuminitrandom_stater   r   r   r   c                C   s  |du rt d}|du rtj }n&t|trtjj|d}nt|tjjtjjfr-|}nt| t	d||dkrHt
jd| ddd	 n|d
k rTt	d| dtj| jtjd}t|}|dkrztdtj |j| jd |dd< n|du rd|dd< nt	d| dtd}t|D ]J}|}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.

        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, np.random.RandomState, or np.random.Generator
        If int, random_state is the seed used by the random number generator
        for phase initialization.

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

        If ``None``, defaults to the `np.random.default_rng()` 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=   )seedzUnsupported random_state=r   zGriffin-Lim with momentum=z+ > 1 can be unstable. Proceed with caution!r   )r   r   z&griffinlim_cqt() called with momentum=z < 0r   r   rn   g      ?zinit=z must either None or 'random'r$   )r(   r)   r,   r*   r-   r.   r1   rg   r4   r/   r2   r0   r5   rZ   )r(   r,   r+   r)   r*   r-   r.   r1   r/   r2   r0   r3   r4   )r(   r)   r,   r-   r.   r*   r1   rg   r4   r/   r2   r0   r5   )r   rG   r   default_rngr   rJ   RandomState	Generatorr   r   r   r   r   rp   	complex64r   tinyphasorpiarrayrs   r   r   rN   )re   r   r(   r)   r*   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   rg   r   r   r   rnganglesepsrebuiltrQ   tprevinverser;   r;   r<   r     s    ,


(
 r   c                 C   s*   dd|   }t |d d |d d  S )a  Compute the relative bandwidth coefficient for equal
    (geometric) freuqency spacing and a give number of bins
    per octave.

    This is a special case of the more general `relative_bandwidth`
    calculation that can be used when only a single basis frequency
    is used.

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

    Returns
    -------
    alpha : np.ndarray > 0
        Value is cast up to a 1d array to allow slicing
    r   r   )rG   
atleast_1d)r,   rr;   r;   r<   rD     s   rD   )rj   TN)=__doc__r   numpyrG   numbar    r   r8   r   r   r   convertr   r   spectrumr	   r
   pitchr   _cacher   r   r   util.exceptionsr   numpy.typingr   typingr   r   r   r   _typingr   r   r   r   __all__ndarrayrq   rJ   boolr   r   r   r   r   r   r   r_   rO   r`   r   r   r   r   r   r   r   rD   r;   r;   r;   r<   <module>   s  	
 %	
 8	
 	
 b	
  "+



"
	

  