
    }Kg#              (       .   d Z ddlZddl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 dd
lmZ ddlmZ ddlmZmZmZmZmZ ddlmZmZmZ g dZddddddddeej:                     dedeej:                     dee   dedededefdZ ddddedededefdZ! ed !      dddddd"d#d$dd%d&d'dd(deej:                     dedeej:                     dee   d)ee   d*ed+ed,ed-ee   d.ed/e"d0ed1eeeef      deej:                  ej:                  f   fd2       Z#d3ej:                  d4ed-ed5ed6edej:                  fd7Z$ejJ                  d8ej:                  dej:                  fd9       Z& ejN                  d:d;gd<d&d&=      d8ej:                  dej:                  ddfd>       Z(d?d@d8ej:                  dAedej:                  fdBZ)ddddd$d&d'dCdej:                  d*ed+eded4ed-ee   d)ee   dDed/e"d0edej:                  fdEZ*dddddFdGdd$dHddejV                  d&d'dIdej:                  d*ed+eded4ed-ee   d)ee   dJedKeeef   dLededMedNedOedPee   d/e"d0edeej:                  ej:                  ej:                  f   f$dQZ,dR Z-ded+ed*ed4ed-ef
dSZ.y)Tz$Pitch-tracking and tuning estimation    N   )_spectrogram)convert   )cache)util)sequence)ParameterError)	ArrayLike)AnyCallableOptionalTupleUnion)_WindowSpec_PadMode_PadModeSTFT)estimate_tuningpitch_tuningpiptrackyinpyini"V  i   g{Gz?   )ysrSn_fft
resolutionbins_per_octaver   r   r   r   r   r   kwargsreturnc                     t        d| |||d|\  }}|dkD  }	|	j                         rt        j                  ||	         }
nd}
t	        |||
k\  |	z     ||      S )a  Estimate the tuning of an audio time series or spectrogram input.

    Parameters
    ----------
    y : np.ndarray [shape=(..., n)] or None
        audio signal. Multi-channel is supported..
    sr : number > 0 [scalar]
        audio sampling rate of ``y``
    S : np.ndarray [shape=(..., d, t)] or None
        magnitude or power spectrogram
    n_fft : int > 0 [scalar] or None
        number of FFT bins to use, if ``y`` is provided.
    resolution : float in `(0, 1)`
        Resolution of the tuning as a fraction of a bin.
        0.01 corresponds to measurements in cents.
    bins_per_octave : int > 0 [scalar]
        How many frequency bins per octave
    **kwargs : additional keyword arguments
        Additional arguments passed to `piptrack`

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

        Note that if multichannel input is provided, a single tuning estimate is provided spanning all
        channels.

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

    Examples
    --------
    With time-series input

    >>> y, sr = librosa.load(librosa.ex('trumpet'))
    >>> librosa.estimate_tuning(y=y, sr=sr)
    -0.08000000000000002

    In tenths of a cent

    >>> librosa.estimate_tuning(y=y, sr=sr, resolution=1e-3)
    -0.016000000000000014

    Using spectrogram input

    >>> S = np.abs(librosa.stft(y))
    >>> librosa.estimate_tuning(S=S, sr=sr)
    -0.08000000000000002

    Using pass-through arguments to `librosa.piptrack`

    >>> librosa.estimate_tuning(y=y, sr=sr, n_fft=8192,
    ...                         fmax=librosa.note_to_hz('G#9'))
    -0.08000000000000002
    )r   r   r   r   r           r   r    )r   anynpmedianr   )r   r   r   r   r   r   r    pitchmag
pitch_mask	thresholds              V/home/alanp/www/video.onchill/myenv/lib/python3.12/site-packages/librosa/core/pitch.pyr   r      sr    F AA"A&AJE3 J~~IIc*o.		si:-.'     r$   frequenciesc          
         t        j                  |       } | | dkD     } t        j                  |       st        j                  dd       yt        j
                  |t        j                  |       z  d      }||dk\  xx   dz  cc<   t        j                  ddt        t        j                  d|z              d	z         }t        j                  ||      \  }}|t        j                  |         }|S )
a  Given a collection of pitches, estimate its tuning offset
    (in fractions of a bin) relative to A440=440.0Hz.

    Parameters
    ----------
    frequencies : array-like, float
        A collection of frequencies detected in the signal.
        See `piptrack`
    resolution : float in `(0, 1)`
        Resolution of the tuning as a fraction of a bin.
        0.01 corresponds to cents.
    bins_per_octave : int > 0 [scalar]
        How many frequency bins per octave

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

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

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

    >>> # Track frequencies from a real spectrogram
    >>> y, sr = librosa.load(librosa.ex('trumpet'))
    >>> freqs, times, mags = librosa.reassigned_spectrogram(y, sr=sr,
    ...                                                     fill_nan=True)
    >>> # Select out pitches with high energy
    >>> freqs = freqs[mags > np.median(mags)]
    >>> librosa.pitch_tuning(freqs)
    -0.07
    r   z3Trying to estimate tuning from empty frequency set.r   )
stacklevelr#         ?      ?g      r   )r'   
atleast_1dr&   warningswarnmodr   
hz_to_octslinspaceintceil	histogramargmax)r/   r   r   residualbinscountstuning
tuning_ests           r-   r   r   l   s    T --,K kAo.K66+Aa	
  vvo(:(:;(GGMH
 X_$;;tS#bggcJ.>&?"@1"DED\\(D1NFF ryy01Jr.      )levelg     b@g     @@g?hannTconstant)r   r   r   r   
hop_lengthfminfmaxr,   
win_lengthwindowcenterpad_moderefrG   rH   rI   r,   rJ   rK   rL   rM   rN   c           
      l   t        | |||||	|
|      \  }}t        j                  |      }t        j                  |d      }t        j                  |t        |      dz        }t        j                  ||      }t        j                  |d      }t        |d      }d|z  |z  }t        j                  |      }t        j                  |      }||k  ||k  z  }t        j                  ||j                  d      }|t        j                  }t        |      r$| ||d      z  }t        j                   |d      }nt        j                  |      }t        j"                  |t        j$                  |||kD  z  d      z        }|d   ||   z   t        |      z  |z  ||<   ||   ||   z   ||<   ||fS )	a  Pitch tracking on thresholded parabolically-interpolated STFT.

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

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

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

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

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

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

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

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

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

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

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

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

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

    window : string, tuple, number, function, or np.ndarray [shape=(n_fft,)]
        - a window specification (string, tuple, or number);
          see `scipy.signal.get_window`
        - a window function, such as `scipy.signal.windows.hann`
        - 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 zero-padding.

        See also: `np.pad`.

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

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

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

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

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

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

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

    One of ``S`` or ``y`` must be provided.
    If ``S`` is not given, it is computed from ``y`` using
    the default parameters of `librosa.stft`.

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

    >>> y, sr = librosa.load(librosa.ex('trumpet'))
    >>> pitches, magnitudes = librosa.piptrack(y=y, sr=sr)

    Or from a spectrogram input

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

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

    >>> pitches, magnitudes = librosa.piptrack(S=S, sr=sr, threshold=1,
    ...                                        ref=np.mean)
    )r   r   r   rG   rJ   rK   rL   rM   r   r   )r   r   axisr3   ndimaxes)r   r'   absmaximumminimumfloatr   fft_frequenciesgradient_parabolic_interpolation
zeros_liker   	expand_torT   maxcallableexpand_dimsnonzerolocalmax)r   r   r   r   rG   rH   rI   r,   rJ   rK   rL   rM   rN   	fft_freqsavgshiftdskewpitchesmags	freq_mask	ref_valueidxs                         r-   r   r      s   z 

	HAu 	q	A ::dAD::dE"IM*D''2U;I
 ++ab
!C$QR0E#IE mmAG==D "y4'78IyqvvB?I {ff}AB/	 NN9b1	FF3K	 **YqA	M/B!LL
MCGeCj(E"I5=GCL#s#DID=r.   y_framesframe_length
min_period
max_periodc                 2   t         j                  j                  | |d      }t         j                  j                  | d|ddddf   |d      }t         j                  j                  ||z  |d      d|dddf   }d|t        j                  |      dk  <   t        j
                  | dz  d      }|d|dddf   |dd| ddf   z
  }d|t        j                  |      dk  <   |ddd	ddf   |z   d|z  z
  }	|	d||d	z   ddf   }
t        j                  t        j                  d	|d	z         |	j                  d
      }t        j
                  |	dd	|d	z   ddf   d      |z  }|d|d	z
  |ddf   }|
|t        j                  |      z   z  }	|	S )ug  Cumulative mean normalized difference function (equation 8 in [#]_)

    .. [#] De Cheveigné, Alain, and Hideki Kawahara.
        "YIN, a fundamental frequency estimator for speech and music."
        The Journal of the Acoustical Society of America 111.4 (2002): 1917-1930.

    Parameters
    ----------
    y_frames : np.ndarray [shape=(frame_length, n_frames)]
        framed audio time series.
    frame_length : int > 0 [scalar]
        length of the frames in samples.
    win_length : int > 0 [scalar]
        length of the window for calculating autocorrelation in samples.
    min_period : int > 0 [scalar]
        minimum period.
    max_period : int > 0 [scalar]
        maximum period.

    Returns
    -------
    yin_frames : np.ndarray [shape=(max_period-min_period+1,n_frames)]
        Cumulative mean normalized difference function for each frame.
    rP   rQ   .r   Ngư>r   r   rS   )r'   fftrfftirfftrV   cumsumr   r^   arangerT   tiny)rm   rn   rJ   ro   rp   ab
acf_framesenergy_frames
yin_framesyin_numerator	tau_rangecumulative_meanyin_denominators                 r-   &_cumulative_mean_normalized_differencer   i  s   @ 	Hl4A
HS*Qr/145|"MAa!e\;Ca<OPJ,-Jrvvj!D() IIhk3Mc:;)*]3*a;O-PP  34M"&&'$./ sBQBz*]:Q^KJ sJa$?BCM
		!Z!^$:??I
 			*S!j1n"4a78rBYN  &c:>J+F&IJO*$))O44J r.   xc                     | d   | d   z   d| d   z  z
  }| d   | d   z
  dz  }t        j                  |      t        j                  |      k\  ry| |z  S )z0Stencil to compute local parabolic interpolationr   rr   r   r   )r'   rV   )r   ry   rz   s      r-   _pi_stencilr     s`     	
!quq1Q4xA	
1"A	vvayBFF1I 26Mr.   zvoid(float32[:], float32[:])zvoid(float64[:], float64[:])z(n)->(n))r   nopythonc                      t        |       |dd y)z:Vectorized wrapper for the parabolic interpolation stencilN)r   )r   r   s     r-   _pi_wrapperr     s     q>AaDr.   rP   rQ   rR   c                    | j                  d|      }t        j                  |       }|j                  d|      }t        ||       d|d<   d|d<   |S )a  Piecewise parabolic interpolation for yin and pyin.

    Parameters
    ----------
    x : np.ndarray
        array to interpolate
    axis : int
        axis along which to interpolate

    Returns
    -------
    parabolic_shifts : np.ndarray [shape=x.shape]
        position of the parabola optima (relative to bin indices)

        Note: the shift at bin `n` is determined as 0 if the estimated
        optimum is outside the range `[n-1, n+1]`.
    rr   r   ).rr   ).r   )swapaxesr'   
empty_liker   )r   rR   xishiftsshiftsis        r-   r\   r\     sZ    & 
B	B ]]1Foob$'G G GGGFOMr.   )r   rn   rJ   rG   trough_thresholdrL   rM   r   c       	         
   ||t        d      ||dz  }t        |||||       ||dz  }t        j                  | d       |r5dg| j                  z  }
|dz  |dz  f|
d	<   t        j                  | |
|	
      } t        j                  | ||      }t        t        j                  ||z              }t        t        t        j                  ||z              ||z
  dz
        }t        |||||      }t        |      }t        j                  |d      }|ddddf   |ddddf   k  |ddddf<   t        j                  |||k        }t!        |j"                        }d|d<   t        j$                  |d      }t        j&                  |d      }|j)                  |      }|j)                  |      }t        j*                  | dd      }||   ||<   ||z   t        j,                  ||d      z   ddddf   }||z  }|S )u  Fundamental frequency (F0) estimation using the YIN algorithm.

    YIN is an autocorrelation based method for fundamental frequency estimation [#]_.
    First, a normalized difference function is computed over short (overlapping) frames of audio.
    Next, the first minimum in the difference function below ``trough_threshold`` is selected as
    an estimate of the signal's period.
    Finally, the estimated period is refined using parabolic interpolation before converting
    into the corresponding frequency.

    .. [#] De Cheveigné, Alain, and Hideki Kawahara.
        "YIN, a fundamental frequency estimator for speech and music."
        The Journal of the Acoustical Society of America 111.4 (2002): 1917-1930.

    Parameters
    ----------
    y : np.ndarray [shape=(..., n)]
        audio time series. Multi-channel is supported..
    fmin : number > 0 [scalar]
        minimum frequency in Hertz.
        The recommended minimum is ``librosa.note_to_hz('C2')`` (~65 Hz)
        though lower values may be feasible.
    fmax : number > fmin, <= sr/2 [scalar]
        maximum frequency in Hertz.
        The recommended maximum is ``librosa.note_to_hz('C7')`` (~2093 Hz)
        though higher values may be feasible.
    sr : number > 0 [scalar]
        sampling rate of ``y`` in Hertz.
    frame_length : int > 0 [scalar]
        length of the frames in samples.
        By default, ``frame_length=2048`` corresponds to a time scale of about 93 ms at
        a sampling rate of 22050 Hz.
    win_length : None or int > 0 [scalar]
        length of the window for calculating autocorrelation in samples.
        If ``None``, defaults to ``frame_length // 2``
    hop_length : None or int > 0 [scalar]
        number of audio samples between adjacent YIN predictions.
        If ``None``, defaults to ``frame_length // 4``.
    trough_threshold : number > 0 [scalar]
        absolute threshold for peak estimation.
    center : boolean
        If ``True``, the signal `y` is padded so that frame
        ``D[:, t]`` is centered at `y[t * hop_length]`.
        If ``False``, then ``D[:, t]`` begins at ``y[t * hop_length]``.
        Defaults to ``True``,  which simplifies the alignment of ``D`` onto a
        time grid by means of ``librosa.core.frames_to_samples``.
    pad_mode : string or function
        If ``center=True``, this argument is passed to ``np.pad`` for padding
        the edges of the signal ``y``. By default (``pad_mode="constant"``),
        ``y`` is padded on both sides with zeros.
        If ``center=False``,  this argument is ignored.
        .. see also:: `np.pad`

    Returns
    -------
    f0: np.ndarray [shape=(..., n_frames)]
        time series of fundamental frequencies in Hertz.

        If multi-channel input is provided, f0 curves are estimated separately for each channel.

    See Also
    --------
    librosa.pyin :
        Fundamental frequency (F0) estimation using probabilistic YIN (pYIN).

    Examples
    --------
    Computing a fundamental frequency (F0) curve from an audio input

    >>> y = librosa.chirp(fmin=440, fmax=880, duration=5.0, sr=22050)
    >>> librosa.yin(y, fmin=440, fmax=880, sr=22050)
    array([442.66354675, 441.95299983, 441.58010963, ...,
        871.161732  , 873.99001454, 877.04297681])
    N'both "fmin" and "fmax" must be providedr   r   rI   rH   rn   rJ      Fmonor   r   rr   modern   rG   r   rP   rQ   .r   TrR   keepdims)r
   __check_yin_paramsr   valid_audiorT   r'   padframer:   floorminr;   r   r\   localminlogical_andlistshapeargminr=   reshapealltake_along_axis)r   rH   rI   r   rn   rJ   rG   r   rL   rM   paddingrm   ro   rp   r}   parabolic_shifts	is_troughis_threshold_troughtarget_shape
global_min
yin_periodno_trough_below_thresholdf0s                          r-   r   r     s>   l |t|FGG !Q&
Dt,:
 !Q&
 	QU# (QVV##q(,!*;<FF1gH- zz!,:NH RXXb4i()JSd+,lZ.G!.KLJ 8,
J
J
 0
; jr2I%c1ai0:c1ai3HHIc1ai ..JAQ4QR 
(()LL:B/J.R8J##L1J##L1J "(;';"t T,67P,QJ()
 	
	


-z
C	D 
1ai	J *_BIr.   d   )r      g(\A@)r   rn   rJ   rG   n_thresholdsbeta_parametersboltzmann_parameterr   max_transition_rateswitch_probno_trough_probfill_narL   rM   r   r   r   r   r   r   r   c          	        	%&'() |t        d      ||dz  }t        |||       ||dz  }t        j                  | d       |r>| j                  D cg c]  }d }}|dz  |dz  f|d	<   t        j                  | ||
      } t        j                  | ||      }t        t        j                  |z              &t        t        t        j                  z              ||z
  dz
        }t        |||&|      }t        |      }t        j                  dd|dz         )t        j                   j"                  j%                  )|d   |d         }t        j&                  |      %t        t        j                  d|
z              't        t        j                  d'z  t        j(                  |z        z              dz   (%	&'()f	d}t        j*                  |d      } |||      \  }}t-        |dz  |z  z        }|'z  dz   }t/        j0                  (|dd      }t/        j2                  dd|z
        }t        j4                  ||      }t        j6                  d(z        } d(z  | (d t/        j8                  |||       }!dt        j:                  (      d'z  z  z  z  }"|"|!(z     }#|!(k  }$|||#|$ <   |#ddddf   |$ddddf   |ddddf   fS c c}w )uM  Fundamental frequency (F0) estimation using probabilistic YIN (pYIN).

    pYIN [#]_ is a modificatin of the YIN algorithm [#]_ for fundamental frequency (F0) estimation.
    In the first step of pYIN, F0 candidates and their probabilities are computed using the YIN algorithm.
    In the second step, Viterbi decoding is used to estimate the most likely F0 sequence and voicing flags.

    .. [#] Mauch, Matthias, and Simon Dixon.
        "pYIN: A fundamental frequency estimator using probabilistic threshold distributions."
        2014 IEEE International Conference on Acoustics, Speech and Signal Processing (ICASSP). IEEE, 2014.

    .. [#] De Cheveigné, Alain, and Hideki Kawahara.
        "YIN, a fundamental frequency estimator for speech and music."
        The Journal of the Acoustical Society of America 111.4 (2002): 1917-1930.

    Parameters
    ----------
    y : np.ndarray [shape=(..., n)]
        audio time series. Multi-channel is supported.
    fmin : number > 0 [scalar]
        minimum frequency in Hertz.
        The recommended minimum is ``librosa.note_to_hz('C2')`` (~65 Hz)
        though lower values may be feasible.
    fmax : number > fmin, <= sr/2 [scalar]
        maximum frequency in Hertz.
        The recommended maximum is ``librosa.note_to_hz('C7')`` (~2093 Hz)
        though higher values may be feasible.
    sr : number > 0 [scalar]
        sampling rate of ``y`` in Hertz.
    frame_length : int > 0 [scalar]
        length of the frames in samples.
        By default, ``frame_length=2048`` corresponds to a time scale of about 93 ms at
        a sampling rate of 22050 Hz.
    win_length : None or int > 0 [scalar]
        length of the window for calculating autocorrelation in samples.
        If ``None``, defaults to ``frame_length // 2``
    hop_length : None or int > 0 [scalar]
        number of audio samples between adjacent pYIN predictions.
        If ``None``, defaults to ``frame_length // 4``.
    n_thresholds : int > 0 [scalar]
        number of thresholds for peak estimation.
    beta_parameters : tuple
        shape parameters for the beta distribution prior over thresholds.
    boltzmann_parameter : number > 0 [scalar]
        shape parameter for the Boltzmann distribution prior over troughs.
        Larger values will assign more mass to smaller periods.
    resolution : float in `(0, 1)`
        Resolution of the pitch bins.
        0.01 corresponds to cents.
    max_transition_rate : float > 0
        maximum pitch transition rate in octaves per second.
    switch_prob : float in ``(0, 1)``
        probability of switching from voiced to unvoiced or vice versa.
    no_trough_prob : float in ``(0, 1)``
        maximum probability to add to global minimum if no trough is below threshold.
    fill_na : None, float, or ``np.nan``
        default value for unvoiced frames of ``f0``.
        If ``None``, the unvoiced frames will contain a best guess value.
    center : boolean
        If ``True``, the signal ``y`` is padded so that frame
        ``D[:, t]`` is centered at ``y[t * hop_length]``.
        If ``False``, then ``D[:, t]`` begins at ``y[t * hop_length]``.
        Defaults to ``True``,  which simplifies the alignment of ``D`` onto a
        time grid by means of ``librosa.core.frames_to_samples``.
    pad_mode : string or function
        If ``center=True``, this argument is passed to ``np.pad`` for padding
        the edges of the signal ``y``. By default (``pad_mode="constant"``),
        ``y`` is padded on both sides with zeros.
        If ``center=False``,  this argument is ignored.
        .. see also:: `np.pad`

    Returns
    -------
    f0: np.ndarray [shape=(..., n_frames)]
        time series of fundamental frequencies in Hertz.
    voiced_flag: np.ndarray [shape=(..., n_frames)]
        time series containing boolean flags indicating whether a frame is voiced or not.
    voiced_prob: np.ndarray [shape=(..., n_frames)]
        time series containing the probability that a frame is voiced.
    .. note:: If multi-channel input is provided, f0 and voicing are estimated separately for each channel.

    See Also
    --------
    librosa.yin :
        Fundamental frequency (F0) estimation using the YIN algorithm.

    Examples
    --------
    Computing a fundamental frequency (F0) curve from an audio input

    >>> y, sr = librosa.load(librosa.ex('trumpet'))
    >>> f0, voiced_flag, voiced_probs = librosa.pyin(y,
    ...                                              sr=sr,
    ...                                              fmin=librosa.note_to_hz('C2'),
    ...                                              fmax=librosa.note_to_hz('C7'))
    >>> times = librosa.times_like(f0, sr=sr)

    Overlay F0 over a spectrogram

    >>> import matplotlib.pyplot as plt
    >>> D = librosa.amplitude_to_db(np.abs(librosa.stft(y)), ref=np.max)
    >>> fig, ax = plt.subplots()
    >>> img = librosa.display.specshow(D, x_axis='time', y_axis='log', ax=ax)
    >>> ax.set(title='pYIN fundamental frequency estimation')
    >>> fig.colorbar(img, ax=ax, format="%+2.f dB")
    >>> ax.plot(times, f0, label='f0', color='cyan', linewidth=3)
    >>> ax.legend(loc='upper right')
    Nr   r   r   r   Fr   r   rr   r   r   r   r   r2   r   c                 .   	 t        | |	
      S )N)__pyin_helper)ry   rz   
beta_probsr   rH   ro   n_bins_per_semitonen_pitch_binsr   r   
thresholdss     r-   _helperzpyin.<locals>._helper7  s1    
 	
r.   z(f,t),(k,t)->(1,d,t),(j,t))	signaturetriangle)rK   wrap)p_init.)r
   r   r   r   r   r'   r   r   r:   r   r   r;   r   r\   r9   scipystatsbetacdfdifflog2	vectorizeroundr	   transition_localtransition_loopkronzerosviterbirw   )*r   rH   rI   r   rn   rJ   rG   r   r   r   r   r   r   r   r   rL   rM   _r   rm   rp   r}   r   beta_cdfr   helperobservation_probsvoiced_probmax_semitones_per_frametransition_width
transitiont_switchr   statesfreqsr   voiced_flagr   ro   r   r   r   s*    ` `     `   `                       @@@@@r-   r   r     s   ~ |t|FGG !Q&
Dt,:
 !Q&
 	QU# #$77+7a67+#q(,!*;<FF1gH- zz!,:NH RXXb4i()JSd+,lZ.G!.KLJ 8,
J
J
 0
; Q<!#34J{{##J0BOTUDVWH"JbggcJ&678rxx%8 82774$;;O OPQTUUL
 
 \\'-IJF%+J8H%I"{ $$7"$<z$IB$NO.1DDqH**&zJ
 ''1{?;H:.JXXa,&'F,F<=/FKF 1<0B9L4LMNNE	v$	%B<'K"K<c1ai=+c1ai0+c1ai2HHHS ,s   	K/c           
         t        j                  |       }t        | j                        D ]I  \  }}t	        j
                  |      }|d   |d   k  |d<   t        j                  |      \  }t        |      dk(  rP||   }t         j                  j                  ||dd        }t        j                  |d      dz
  }t        j                  |d      }t        j                  j                  j                  |||      }d|| <   |j!                  |      }t        j"                  |      }t        j                  ||d d f          }||xx   |t        j$                  |d |       z  z  cc<   ||||f<   L t        j                  |      \  }}||z   }||||f   z   }||z  }d|
z  t        j&                  ||z        z  }t        j(                  t        j*                  |      d|	      j-                  t.              }t        j0                  d|	z  | j2                  d   f      }|||f   |||f<   t        j(                  t        j$                  |d |	d d f   dd      dd      }d|z
  |	z  ||	d d d f<   |t         j4                     |fS )Nr   r   rQ   r   r   Tr   )r'   r]   	enumerateTr   r   rb   lenlessouterrv   count_nonzeror   r   	boltzmannpmfdotr   sumr   clipr   astyper:   r   r   newaxis)r}   r   r   r   r   r   r   ro   rH   r   r   	yin_probsi	yin_framer   trough_indextrough_heightstrough_thresholdstrough_positions	n_troughstrough_priorprobsr   n_thresholds_below_minr   frame_indexperiod_candidatesf0_candidates	bin_indexr   r   s                                  r-   r   r   e  s    j)I!*,,/9MM),	 |il2	!**Y/|! #<0GGMM.*QR.I 99%6Q?!C$$%6Q?	{{,,0019
 ,-''(
   ,YY~.
!#!1!13DZQR]3S2S!Tj^bff..//
 
 	
 &+	,/"K 0N !jj3J #Z/),<Z=T,UU**M ((277=43G+HHI+Q=DDSII !l"2J4D4DQ4G!HI09*k:Q0Ri,-''
 ,!12TJAqK ,-{?l*JlmQ&'RZZ(+55r.   c                    || dz  kD  rt        d|dd| dz         ||k\  rt        d|dd|d      |dk  rt        d|dd      ||k\  rt        d	| d
|       ||z
  dz
  | |z  k  rQ| ||z
  dz
  z  }t        t        j                  | |z        |z   dz         }t        d|dd| d| d|  d|dd|       y)zCheck the feasibility of yin/pyin parameters against
    the following conditions:

    1. 0 < fmin < fmax <= sr/2
    2. frame_length - win_length - 1 > sr/fmax
    r   zfmax=z.3fz! cannot exceed Nyquist frequency zfmin=z must be less than fmax=r   z must be strictly positivezwin_length=z  must be less than frame_length=r   z is too small for frame_length=z, win_length=z	, and sr=z. Either increase to fmax=z or frame_length=N)r
   r:   r'   r;   )r   rI   rH   rn   rJ   fmax_feasibleframe_length_feasibles          r-   r   r     s7    b1f}uT#J.OPRSTPTvVWWt|uT#J.FtCjQRRqyuT#J.HIJJ\!*%El^T
 	
 j 1$d
2lZ7!;< #BGGBtG$4z$AA$E FD:<\N-XbWcclmolp q''4S&99JK`Jac
 	
 3r.   )/__doc__r5   numpyr'   r   numbaspectrumr    r   _cacher   r   r	   util.exceptionsr
   numpy.typingr   typingr   r   r   r   r   _typingr   r   r   __all__ndarrayrY   r:   r   r   boolr   r   stencilr   guvectorizer   r\   r   nanr   r   r   r%   r.   r-   <module>r     s   +     #     , " 8 8 9 9
H
 #"Q

Q 	Q 

	Q
 C=Q Q Q Q Qj 48PRCC+0CJMC
CL R #" $ $ ',0s

s 	s 

	s
 C=s s s s s s s s s 
%x(	)s 2::rzz!"s sl=jj== = 	=
 = ZZ=@ 
2:: 
"** 
 
 #%CD
	2:: "**  
 <>  

  S  "**  P  $ $!#^	zz^ ^ 	^
 	^ ^ ^ ^ ^ ^ ^ ZZ^L  $ $+2!"!& !vv#%\I	zz\I \I 	\I
 	\I \I \I \I \I 5%<(\I \I \I \I \I \I  e_!\I" #\I$ %\I& 2::rzz2::-.'\I~J6Z


%*
:=
KN
r.   