U
    5d                     @   s0  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	m
Z
 ddlmZmZmZ ddlm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dddddddg	ZG dd de	ZG dd de	ZG dd de	ZG dd de	ZG dd de	ZG dd de	Z G dd de	Z!G d d dZ"ed!d"d#d$d%d&dZ#d'd( Z$eddddd)d*ddddd+d,d-dddd!d.d!dd/d0dZ%d1d2 Z&d3d4 Z'd5d6 Z(d7d8 Z)dSd9d:Z*dTd;d<Z+dUd=d>Z,dVd?d@Z-dWdAdBZ.dXdCdDZ/dYdEdFZ0dGdH Z1dZdIdJZ2dKdL Z3ed)dMdNd+dOdPdddQdRdZ4dS )[a  
Display
=======

Data visualization
------------------
.. autosummary::
    :toctree: generated/

    specshow
    waveshow

Axis formatting
---------------
.. autosummary::
    :toctree: generated/

    TimeFormatter
    NoteFormatter
    SvaraFormatter
    LogHzFormatter
    ChromaFormatter
    ChromaSvaraFormatter
    TonnetzFormatter

Miscellaneous
-------------
.. autosummary::
    :toctree: generated/

    cmap
    AdaptiveWaveplot

    N)get_cmap)Axes)	FormatterScalarFormatter)
LogLocatorFixedLocatorMaxNLocator)SymmetricalLogLocator)parse   )core)util)ParameterError)deprecate_positional_argsspecshowwaveshowcmapTimeFormatterNoteFormatterLogHzFormatterChromaFormatterTonnetzFormatterAdaptiveWaveplotc                   @   s$   e Zd ZdZdddZd	ddZdS )
r   a  A tick formatter for time axes.

    Automatically switches between seconds, minutes:seconds,
    or hours:minutes:seconds.

    Parameters
    ----------
    lag : bool
        If ``True``, then the time axis is interpreted in lag coordinates.
        Anything past the midpoint will be converted to negative time.

    unit : str or None
        Abbreviation of the physical unit for axis labels and ticks.
        Either equal to `s` (seconds) or `ms` (milliseconds) or None (default).
        If set to None, the resulting TimeFormatter object adapts its string
        representation to the duration of the underlying time range:
        `hh:mm:ss` above 3600 seconds; `mm:ss` between 60 and 3600 seconds;
        and `ss` below 60 seconds.


    See also
    --------
    matplotlib.ticker.Formatter


    Examples
    --------

    For normal time

    >>> import matplotlib.pyplot as plt
    >>> times = np.arange(30)
    >>> values = np.random.randn(len(times))
    >>> fig, ax = plt.subplots()
    >>> ax.plot(times, values)
    >>> ax.xaxis.set_major_formatter(librosa.display.TimeFormatter())
    >>> ax.set(xlabel='Time')

    Manually set the physical time unit of the x-axis to milliseconds

    >>> times = np.arange(100)
    >>> values = np.random.randn(len(times))
    >>> fig, ax = plt.subplots()
    >>> ax.plot(times, values)
    >>> ax.xaxis.set_major_formatter(librosa.display.TimeFormatter(unit='ms'))
    >>> ax.set(xlabel='Time (ms)')

    For lag plots

    >>> times = np.arange(60)
    >>> values = np.random.randn(len(times))
    >>> fig, ax = plt.subplots()
    >>> ax.plot(times, values)
    >>> ax.xaxis.set_major_formatter(librosa.display.TimeFormatter(lag=True))
    >>> ax.set(xlabel='Lag')
    FNc                 C   s&   |dkrt d||| _|| _d S )N)smsNzUnknown time unit: {})r   formatunitlag)selfr   r    r   3/tmp/pip-unpacked-wheel-8l90aumz/librosa/display.py__init__~   s    zTimeFormatter.__init__c           
   	   C   s$  | j  \}}| j  \}}| jrN||d krN||kr:dS t|| }d}n|}d}| jdkrld|}	n| jdkrd|d }	n|| dkrd	t|d
 tt	|d dtt	|d}	nR|| dkrdt|d tt	|d}	n$|| dkrd|}	n
d|}	d||	S )zReturn the time format as pos      ? -r   z{:.3g}r   i  i  z{:d}:{:02d}:{:02d}g      @g      N@<   z{:d}:{:02d}r   z{:.2g}z{:.3f}z{:s}{:s})
axisZget_data_intervalget_view_intervalr   npabsr   r   intmod)
r   xpos_Zdmaxvminvmaxvaluesignr   r   r   r    __call__   s2    


"
zTimeFormatter.__call__)FN)N__name__
__module____qualname____doc__r!   r3   r   r   r   r    r   D   s   9
c                   @   s$   e Zd ZdZd	ddZd
ddZdS )r   a  Ticker formatter for Notes

    Parameters
    ----------
    octave : bool
        If ``True``, display the octave number along with the note name.

        Otherwise, only show the note name (and cent deviation)

    major : bool
        If ``True``, ticks are always labeled.

        If ``False``, ticks are only labeled if the span is less than 2 octaves

    key : str
        Key for determining pitch spelling.

    unicode : bool
        If ``True``, use unicode symbols for accidentals.

        If ``False``, use ASCII symbols for accidentals.

    See also
    --------
    LogHzFormatter
    matplotlib.ticker.Formatter

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> values = librosa.midi_to_hz(np.arange(48, 72))
    >>> fig, ax = plt.subplots(nrows=2)
    >>> ax[0].bar(np.arange(len(values)), values)
    >>> ax[0].set(ylabel='Hz')
    >>> ax[1].bar(np.arange(len(values)), values)
    >>> ax[1].yaxis.set_major_formatter(librosa.display.NoteFormatter())
    >>> ax[1].set(ylabel='Note')
    TC:majc                 C   s   || _ || _|| _|| _d S N)octavemajorkeyunicode)r   r;   r<   r=   r>   r   r   r    r!      s    zNoteFormatter.__init__Nc                 C   sb   |dkrdS | j  \}}| js6|dtd| kr6dS |dtd| k}tj|| j|| j| jdS )Nr   r#      r      r;   centsr=   r>   )	r&   r'   r<   maxr   Z
hz_to_noter;   r=   r>   )r   r,   r-   r/   r0   rB   r   r   r    r3      s        zNoteFormatter.__call__)TTr9   T)Nr4   r   r   r   r    r      s   '
c                   @   s$   e Zd ZdZd	ddZd
ddZdS )SvaraFormattera  Ticker formatter for Svara

    Parameters
    ----------
    octave : bool
        If ``True``, display the octave number along with the note name.

        Otherwise, only show the note name (and cent deviation)

    major : bool
        If ``True``, ticks are always labeled.

        If ``False``, ticks are only labeled if the span is less than 2 octaves

    Sa : number > 0
        Frequency (in Hz) of Sa

    mela : str or int
        For Carnatic svara, the index or name of the melakarta raga in question

        To use Hindustani svara, set ``mela=None``

    unicode : bool
        If ``True``, use unicode symbols for accidentals.

        If ``False``, use ASCII symbols for accidentals.

    See also
    --------
    NoteFormatter
    matplotlib.ticker.Formatter
    librosa.hz_to_svara_c
    librosa.hz_to_svara_h


    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> values = librosa.midi_to_hz(np.arange(48, 72))
    >>> fig, ax = plt.subplots(nrows=2)
    >>> ax[0].bar(np.arange(len(values)), values)
    >>> ax[0].set(ylabel='Hz')
    >>> ax[1].bar(np.arange(len(values)), values)
    >>> ax[1].yaxis.set_major_formatter(librosa.display.SvaraFormatter(261))
    >>> ax[1].set(ylabel='Note')
    TFNc                 C   s8   |d krt d|| _|| _|| _|| _|| _|| _d S )Nz5Sa frequency is required for svara display formatting)r   Sar;   r<   abbrmelar>   )r   rE   r;   r<   rF   rG   r>   r   r   r    r!   "  s    zSvaraFormatter.__init__c                 C   s   |dkrdS | j  \}}| js6|dtd| kr6dS | jd kr\tj|| j| j| j	| j
dS tj|| j| j| j| j	| j
dS d S )Nr   r#   r?   r   rE   r;   rF   r>   rE   rG   r;   rF   r>   )r&   r'   r<   rC   rG   r   Zhz_to_svara_hrE   r;   rF   r>   Zhz_to_svara_cr   r,   r-   r/   r0   r   r   r    r3   2  s*    
    zSvaraFormatter.__call__)TTFNT)Nr4   r   r   r   r    rD      s   0         
rD   c                   @   s$   e Zd ZdZdddZd	ddZdS )
r   a  Ticker formatter for logarithmic frequency

    Parameters
    ----------
    major : bool
        If ``True``, ticks are always labeled.

        If ``False``, ticks are only labeled if the span is less than 2 octaves

    See also
    --------
    NoteFormatter
    matplotlib.ticker.Formatter

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> values = librosa.midi_to_hz(np.arange(48, 72))
    >>> fig, ax = plt.subplots(nrows=2)
    >>> ax[0].bar(np.arange(len(values)), values)
    >>> ax[0].yaxis.set_major_formatter(librosa.display.LogHzFormatter())
    >>> ax[0].set(ylabel='Hz')
    >>> ax[1].bar(np.arange(len(values)), values)
    >>> ax[1].yaxis.set_major_formatter(librosa.display.NoteFormatter())
    >>> ax[1].set(ylabel='Note')
    Tc                 C   s
   || _ d S r:   r<   )r   r<   r   r   r    r!   h  s    zLogHzFormatter.__init__Nc                 C   s@   |dkrdS | j  \}}| js6|dtd| kr6dS d|S )Nr   r#   r?   r   z{:g})r&   r'   r<   rC   r   rJ   r   r   r    r3   l  s    zLogHzFormatter.__call__)T)Nr4   r   r   r   r    r   L  s   
c                   @   s$   e Zd ZdZd	ddZd
ddZdS )r   ac  A formatter for chroma axes

    See also
    --------
    matplotlib.ticker.Formatter

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> values = np.arange(12)
    >>> fig, ax = plt.subplots()
    >>> ax.plot(values)
    >>> ax.yaxis.set_major_formatter(librosa.display.ChromaFormatter())
    >>> ax.set(ylabel='Pitch class')
    r9   Tc                 C   s   || _ || _d S r:   r=   r>   )r   r=   r>   r   r   r    r!     s    zChromaFormatter.__init__Nc                 C   s   t jt|dd| j| jdS )Format for chroma positionsFrA   )r   Zmidi_to_noter*   r=   r>   r   r,   r-   r   r   r    r3     s        zChromaFormatter.__call__)r9   T)Nr4   r   r   r   r    r   y  s   
c                   @   s$   e Zd ZdZdddZd	ddZdS )
ChromaSvaraFormattera!  A formatter for chroma axes with svara instead of notes.

    If mela is given, Carnatic svara names will be used.

    Otherwise, Hindustani svara names will be used.

    If `Sa` is not given, it will default to 0 (equivalent to `C`).

    See Also
    --------
    ChromaFormatter

    NTc                 C   s(   |d krd}|| _ || _|| _|| _d S )Nr   )rE   rG   rF   r>   )r   rE   rG   rF   r>   r   r   r    r!     s    zChromaSvaraFormatter.__init__c                 C   sN   | j dk	r,tjt|| j| j d| j| jdS tjt|| jd| j| jdS dS )rM   NFrI   rH   )rG   r   Zmidi_to_svara_cr*   rE   rF   r>   Zmidi_to_svara_hrN   r   r   r    r3     s     
	    zChromaSvaraFormatter.__call__)NNTT)Nr4   r   r   r   r    rO     s   
rO   c                   @   s   e Zd ZdZdddZdS )r   a`  A formatter for tonnetz axes

    See also
    --------
    matplotlib.ticker.Formatter

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> values = np.arange(6)
    >>> fig, ax = plt.subplots()
    >>> ax.plot(values)
    >>> ax.yaxis.set_major_formatter(librosa.display.TonnetzFormatter())
    >>> ax.set(ylabel='Tonnetz')
    Nc                 C   s   ddddddgt | S )zFormat for tonnetz positionsz5$_x$z5$_y$zm3$_x$zm3$_y$zM3$_x$zM3$_y$)r*   rN   r   r   r    r3     s    zTonnetzFormatter.__call__)N)r5   r6   r7   r8   r3   r   r   r   r    r     s   c                   @   s"   e Zd ZdZd	ddZdd ZdS )
r   a  A helper class for managing adaptive wave visualizations.

    This object is used to dynamically switch between sample-based and envelope-based
    visualizations of waveforms.
    When the display is zoomed in such that no more than `max_samples` would be
    visible, the sample-based display is used.
    When displaying the raw samples would require more than `max_samples`, an
    envelope-based plot is used instead.

    You should never need to instantiate this object directly, as it is constructed
    automatically by `waveshow`.

    Parameters
    ----------
    times : np.ndarray
        An array containing the time index (in seconds) for each sample.

    y : np.ndarray
        An array containing the (monophonic) wave samples.

    steps : matplotlib.lines.Lines2D
        The matplotlib artist used for the sample-based visualization.
        This is constructed by `matplotlib.pyplot.step`.

    envelope : matplotlib.collections.PolyCollection
        The matplotlib artist used for the envelope-based visualization.
        This is constructed by `matplotlib.pyplot.fill_between`.

    sr : number > 0
        The sampling rate of the audio

    max_samples : int > 0
        The maximum number of samples to use for sample-based display.

    See Also
    --------
    waveshow
    "V  +  c                 C   s(   || _ || _|| _|| _|| _|| _d S r:   )timessamplesstepsenvelopesrmax_samples)r   rR   yrT   rU   rV   rW   r   r   r    r!     s    zAdaptiveWaveplot.__init__c                 C   s   |j }|j| j | jkr| jd | jd | j }|j|d ksV|j	|d kr|j	|j d }t
| j|d| j | j  }| j| j||| j  | j||| j   n| jd | jd |jj  dS )a  Update the matplotlib display according to the current viewport limits.

        This is a callback function, and should not be used directly.

        Parameters
        ----------
        ax : matplotlib axes object
            The axes object to update
        FTr   r@   r"   N)ZviewLimwidthrV   rW   rU   Zset_visiblerT   Z	get_xdataZx0x1r(   ZsearchsortedrR   set_datarS   figureZcanvasZ	draw_idle)r   axZlimsZxdataZmidpoint_timeZ	idx_startr   r   r    update  s$    

 zAdaptiveWaveplot.updateN)rP   rQ   )r5   r6   r7   r8   r!   r_   r   r   r   r    r     s   '
TZmagmaZgray_rZcoolwarm)robustcmap_seq	cmap_boolcmap_divc          	      C   sx   t | } | jdkr t|ddS | t |  } |r<d\}}nd\}}t | ||g\}}|dksh|dkrpt|S t|S )a  Get a default colormap from the given data.

    If the data is boolean, use a black and white colormap.

    If the data has both positive and negative values,
    use a diverging colormap.

    Otherwise, use a sequential colormap.

    Parameters
    ----------
    data : np.ndarray
        Input data
    robust : bool
        If True, discard the top and bottom 2% of data when calculating
        range.
    cmap_seq : str
        The sequential colormap name
    cmap_bool : str
        The boolean colormap name
    cmap_div : str
        The diverging colormap name

    Returns
    -------
    cmap : matplotlib.colors.Colormap
        The colormap to use for ``data``

    See Also
    --------
    matplotlib.pyplot.colormaps
    boolr@   )Zlut)r@   b   )r   d   r   )r(   Z
atleast_1ddtyper   isfiniteZ
percentile)	datar`   ra   rb   rc   Zmin_pZmax_pZmin_valZmax_valr   r   r    r   *  s    %


c                 C   s"   t tj| ||d}|jddS )zCompute the max-envelope of non-overlapping frames of x at length hop

    x is assumed to be multi-channel, of shape (n_channels, n_samples).
    )Zframe_length
hop_lengthr   )r&   )r(   r)   r   framerC   )r,   ZhopZx_framer   r   r    
__envelopec  s    rl   rP                 r9   F)x_coordsy_coordsx_axisy_axisrV   rj   n_fft
win_lengthfminfmaxtuningbins_per_octaver=   rE   rG   thaatauto_aspecthtkr>   r^   c                K   s@  t | jt jr(tjddd t | } |dt|  |dd |dd |d	d
 t	|||	|
||||||||d}t
||| jd f|}t
||| jd f|}t|}|j||| f|}t|| t||d t||d t|j||||||d t|j||||||d t||| | r<|r<|d |S )ac  Display a spectrogram/chromagram/cqt/etc.

    For a detailed overview of this function, see :ref:`sphx_glr_auto_examples_plot_display.py`

    Parameters
    ----------
    data : np.ndarray [shape=(d, n)]
        Matrix to display (e.g., spectrogram)

    sr : number > 0 [scalar]
        Sample rate used to determine time scale in x-axis.

    hop_length : int > 0 [scalar]
        Hop length, also used to determine time scale in x-axis

    n_fft : int > 0 or None
        Number of samples per frame in STFT/spectrogram displays.
        By default, this will be inferred from the shape of ``data``
        as ``2 * (d - 1)``.
        If ``data`` was generated using an odd frame length, the correct
        value can be specified here.

    win_length : int > 0 or None
        The number of samples per window.
        By default, this will be inferred to match ``n_fft``.
        This is primarily useful for specifying odd window lengths in
        Fourier tempogram displays.

    x_axis, y_axis : None or str
        Range for the x- and y-axes.

        Valid types are:

        - None, 'none', or 'off' : no axis decoration is displayed.

        Frequency types:

        - 'linear', 'fft', 'hz' : frequency range is determined by
          the FFT window and sampling rate.
        - 'log' : the spectrum is displayed on a log scale.
        - 'fft_note': the spectrum is displayed on a log scale with pitches marked.
        - 'fft_svara': the spectrum is displayed on a log scale with svara marked.
        - 'mel' : frequencies are determined by the mel scale.
        - 'cqt_hz' : frequencies are determined by the CQT scale.
        - 'cqt_note' : pitches are determined by the CQT scale.
        - 'cqt_svara' : like `cqt_note` but using Hindustani or Carnatic svara

        All frequency types are plotted in units of Hz.

        Any spectrogram parameters (hop_length, sr, bins_per_octave, etc.)
        used to generate the input data should also be provided when
        calling `specshow`.

        Categorical types:

        - 'chroma' : pitches are determined by the chroma filters.
          Pitch classes are arranged at integer locations (0-11) according to
          a given key.

        - `chroma_h`, `chroma_c`: pitches are determined by chroma filters,
          and labeled as svara in the Hindustani (`chroma_h`) or Carnatic (`chroma_c`)
          according to a given thaat (Hindustani) or melakarta raga (Carnatic).

        - 'tonnetz' : axes are labeled by Tonnetz dimensions (0-5)
        - 'frames' : markers are shown as frame counts.

        Time types:

        - 'time' : markers are shown as milliseconds, seconds, minutes, or hours.
                Values are plotted in units of seconds.
        - 's' : markers are shown as seconds.
        - 'ms' : markers are shown as milliseconds.
        - 'lag' : like time, but past the halfway point counts as negative values.
        - 'lag_s' : same as lag, but in seconds.
        - 'lag_ms' : same as lag, but in milliseconds.

        Rhythm:

        - 'tempo' : markers are shown as beats-per-minute (BPM)
            using a logarithmic scale.  This is useful for
            visualizing the outputs of `feature.tempogram`.

        - 'fourier_tempo' : same as `'tempo'`, but used when
            tempograms are calculated in the Frequency domain
            using `feature.fourier_tempogram`.

    x_coords, y_coords : np.ndarray [shape=data.shape[0 or 1]]
        Optional positioning coordinates of the input data.
        These can be use to explicitly set the location of each
        element ``data[i, j]``, e.g., for displaying beat-synchronous
        features in natural time coordinates.

        If not provided, they are inferred from ``x_axis`` and ``y_axis``.

    fmin : float > 0 [scalar] or None
        Frequency of the lowest spectrogram bin.  Used for Mel and CQT
        scales.

        If ``y_axis`` is `cqt_hz` or `cqt_note` and ``fmin`` is not given,
        it is set by default to ``note_to_hz('C1')``.

    fmax : float > 0 [scalar] or None
        Used for setting the Mel frequency scales

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

        This is used for CQT frequency scales, so that ``fmin`` is adjusted
        to ``fmin * 2**(tuning / bins_per_octave)``.

    bins_per_octave : int > 0 [scalar]
        Number of bins per octave.  Used for CQT frequency scale.

    key : str
        The reference key to use when using note axes (`cqt_note`, `chroma`).

    Sa : float or int
        If using Hindustani or Carnatic svara axis decorations, specify Sa.

        For `cqt_svara`, ``Sa`` should be specified as a frequency in Hz.

        For `chroma_c` or `chroma_h`, ``Sa`` should correspond to the position
        of Sa within the chromagram.
        If not provided, Sa will default to 0 (equivalent to `C`)

    mela : str or int, optional
        If using `chroma_c` or `cqt_svara` display mode, specify the melakarta raga.

    thaat : str, optional
        If using `chroma_h` display mode, specify the parent thaat.

    auto_aspect : bool
        Axes will have 'equal' aspect if the horizontal and vertical dimensions
        cover the same extent and their types match.

        To override, set to `False`.

    htk : bool
        If plotting on a mel frequency axis, specify which version of the mel
        scale to use.

            - `False`: use Slaney formula (default)
            - `True`: use HTK formula

        See `core.mel_frequencies` for more information.

    unicode : bool
        If using note or svara decorations, setting `unicode=True`
        will use unicode glyphs for accidentals and octave encoding.

        Setting `unicode=False` will use ASCII glyphs.  This can be helpful
        if your font does not support musical notation symbols.

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

    **kwargs : additional keyword arguments
        Arguments passed through to `matplotlib.pyplot.pcolormesh`.

        By default, the following options are set:

            - ``rasterized=True``
            - ``shading='auto'``
            - ``edgecolors='None'``

    Returns
    -------
    colormesh : `matplotlib.collections.QuadMesh`
        The color mesh object produced by `matplotlib.pyplot.pcolormesh`

    See Also
    --------
    cmap : Automatic colormap detection
    matplotlib.pyplot.pcolormesh

    Examples
    --------
    Visualize an STFT power spectrum using default parameters

    >>> import matplotlib.pyplot as plt
    >>> y, sr = librosa.load(librosa.ex('choice'), duration=15)
    >>> fig, ax = plt.subplots(nrows=2, ncols=1, sharex=True)
    >>> D = librosa.amplitude_to_db(np.abs(librosa.stft(y)), ref=np.max)
    >>> img = librosa.display.specshow(D, y_axis='linear', x_axis='time',
    ...                                sr=sr, ax=ax[0])
    >>> ax[0].set(title='Linear-frequency power spectrogram')
    >>> ax[0].label_outer()

    Or on a logarithmic scale, and using a larger hop

    >>> hop_length = 1024
    >>> D = librosa.amplitude_to_db(np.abs(librosa.stft(y, hop_length=hop_length)),
    ...                             ref=np.max)
    >>> librosa.display.specshow(D, y_axis='log', sr=sr, hop_length=hop_length,
    ...                          x_axis='time', ax=ax[1])
    >>> ax[1].set(title='Log-frequency power spectrogram')
    >>> ax[1].label_outer()
    >>> fig.colorbar(img, ax=ax, format="%+2.f dB")
    zBTrying to display complex-valued input. Showing magnitude instead.r@   
stacklevelr   Z
rasterizedTZ
edgecolorsNoneZshadingauto)kwargsrV   rv   rw   rx   ry   rj   rt   ru   r=   r|   r>   r   r   r,   rX   )r=   rE   rG   rz   r>   equal)r(   Z
issubdtyperg   Zcomplexfloatingwarningswarnr)   
setdefaultr   dict__mesh_coordsshape__check_axesZ
pcolormesh__set_current_image__scale_axes__decorate_axisxaxisZyaxis__same_axesZget_xlimZget_ylimZ
set_aspect)ri   rp   rq   rr   rs   rV   rj   rt   ru   rv   rw   rx   ry   r=   rE   rG   rz   r{   r|   r>   r^   r   
all_paramsaxesoutr   r   r    r   l  sj     c

            
c                 C   s"   | dkrddl m} || dS )zHelper to set the current image in pyplot mode.

    If the provided ``ax`` is not `None`, then we assume that the user is using the object API.
    In this case, the pyplot current image is not set.
    Nr   )matplotlib.pyplotpyplotZsci)r^   imgpltr   r   r    r     s    r   c                 K   s   |dk	r@t |||d fkr<tdt | d| d| d|S tttttttttttttttttttttttt	ttd}| |krtd
| ||  |f|S )	zCompute axis coordinatesNr   zCoordinate shape mismatch: z!=z or z+1)linearfftfft_note	fft_svarahzlogmelcqtcqt_hzcqt_note	cqt_svarachromachroma_cchroma_htimer   r   r   lag_slag_mstonnetzofftempofourier_tempoframesNzUnknown axis type: {})lenr   __coord_fft_hz__coord_mel_hz__coord_cqt_hz__coord_chroma__coord_time	__coord_n__coord_tempo__coord_fourier_tempor   )ax_typeZcoordsnr   Z	coord_mapr   r   r    r     sH    r   c                 C   s>   | dkrddl m} | } nt| ts:tdt| | S )zDCheck if "axes" is an instance of an axis object. If not, use `gca`.Nr   zG`axes` must be an instance of matplotlib.axes.Axes. Found type(axes)={})r   r   Zgca
isinstancer   r   r   type)r   r   r   r   r    r     s    

r   c           
      C   s  t  }|dkrHttjtdk r.d}d}d}nd}d}d}| j}| j}n8ttjtdk rhd	}d
}d}nd}d}d}| j}| j}|dkrd}	d||< d||< nh|dkrd}	d||< nR|dkrd}	d||< t	d||< d||< n&|dkrd}	d||< |dd ndS ||	f| dS )zSet the axis scalingr,   z3.3.0Z
linthreshxZbasexZ	linscalexZ	linthreshbaseZlinscaleZ
linthreshyZbaseyZ	linscaleyr   Zsymlogg     @@r@   )r   r   r   r   r   )r   r   r   ZC2r"   r   r      i  N)
r   version_parse
matplotlib__version__Z
set_xscaleZset_xlimZ
set_yscaleZset_ylimr   
note_to_hz)
r   r   whichr   Zthreshr   ZscaleZscalerlimitmoder   r   r    r     sL    



r   c              
   C   s  |dkr6|  t  | ttd | d n|dkr|  t||d t	|}| ttj
dtd |  | d nz|d	kr|d
krd}|  t||d |d
krtd}n
t|}t|| d}| ttj
dtd |  | d n|dkr|d
kr0d}|  t|||d t|}t|| d}| ttj
dtd |  | d nv|dkr|  t  | tdd | d nB|dkr|  td
dd | td
dddddgd | d n|dkrR|  tddd | td
dddddgd | d n|dkr|  tddd | td
dddddgd | d np|d kr|  td
d!d | td
dddddgd | d" n*|d#kr$|  tdd!d | td
dddddgd | d$ n|d%krj|  tdd!d | td
dddddgd | d& n|d'kr|  t||d ttd(}d|t|  }	| td|	fd) | t|d|d* | td|	dtddd+   d) | d, n|d-kr|  t|||d dt|tt|  }
| td|
fd) | t||d|d. | td|
dtddd+   d) | d nj|d/kr>|  t  ttd(}d|t|  }	| td|	fd) | tdd | tdd0 | td|	dtddd+   d) | d1 n|d2kr|  t||d ttd(}d|t|  }	| t|   | t|d|d* | tddtddd+  d) | d, n6|d3krn|  t|||d t|}d|t|  }
| t|  d|
gd) | t||d|d. | td|
dtddd+   d) | d n|d4kr|  t  | t|   | d1 nf|d5kr|  t  | d1 nD|d6kr| d7 n.|d8kr| d9 | g  nt d:!|d
S );z,Configure axis tickers, locators, and labelsr      ZTonnetzr   rL   ro   
   zPitch classr   Nr   )rE   r>   ZSvarar   )rE   rG   r>   r          @)r   ZBPMr   F)r   r   r   g      ?   )ZprunerT   ZTimer   zTime (s)r   z	Time (ms)r   TZLagr   zLag (s)r   zLag (ms)r   C1)r   subs)r=   r<   r>         (@ZNoter   )rE   rG   r<   r>   )r   rK   ZHzr   r   )r   r   )r   r   r   )r   ZFrames)r   noneNr#   zUnsupported axis type: {})"Zset_major_formatterr   Zset_major_locatorr   r(   arangeZset_label_textr   r   Zkey_to_degreesaddouterZravelrO   Zthaat_to_degreesr+   Zmela_to_degreesr   r   r   r   r   log2r   floorZset_minor_formatterZset_minor_locatorrD   r   r	   Zget_transformZ	set_ticksr   r   )r&   r   r=   rE   rG   rz   r>   degreesZlog_C1ZC_offsetZ	sa_offsetZlog_Sar   r   r    r     s   























r   c                 K   s&   |dkrd| d  }t j||d}|S )z Get the frequencies for FFT binsNr@   r   )rV   rt   )r   Zfft_frequencies)r   rV   rt   _kwargsbasisr   r   r    r     s    r   c                 K   s2   |dkrd}|dkrd| }t j| |||d}|S )z Get the frequencies for Mel binsNr   r"   )rv   rw   r|   )r   Zmel_frequencies)r   rv   rw   rV   r|   r   r   r   r   r    r     s    r   c                 K   s^   |dkrt d}|d|dd|   }t j| ||d}t|d| krZtjdd	d
 |S )zGet CQT bin frequenciesNr   r   rx   rn   )rv   ry   r"   z_Frequency axis exceeds Nyquist. Did you remember to set all spectrogram parameters in specshow?r?   r}   )r   r   getZcqt_frequenciesr(   anyr   r   )r   rv   ry   rV   r   Zfreqsr   r   r    r     s    
r   c                 K   s   t jdd|  | | ddS )zGet chroma bin numbersr   r   F)numZendpoint)r(   Zlinspace)r   ry   r   r   r   r    r     s    r   c                 K   s    t j| d ||ddd }|S )zTempo coordinatesr   rV   rj   N)r   Ztempo_frequencies)r   rV   rj   r   r   r   r   r    r     s    r   c                 K   s(   |dkrd| d  }t j|||d}|S )zFourier tempogram coordinatesNr@   r   )rV   rj   ru   )r   Zfourier_tempo_frequencies)r   rV   rj   ru   r   r   r   r   r    r     s      r   c                 K   s
   t | S )zGet bare positions)r(   r   )r   r   r   r   r    r     s    r   c                 K   s   t jt| ||dS )z Get time coordinates from framesr   )r   Zframes_to_timer(   r   )r   rV   rj   r   r   r   r    r     s    r   c                 C   s    | |ko| dk	}||k}|o|S )z?Check if two axes are the same, used to determine squared plotsNr   )rr   rs   ZxlimZylimZaxes_same_and_not_noneZaxes_same_limr   r   r    r     s    r   rQ   r   r#   post)rV   
max_pointsrr   offsetmarkerwherelabelr^   c                K   sN  t j| dd | jdkr*| tjddf } |dkr@td|t|}
d|	krh|	dt	|
j
jd  td| jd | }t| |}|d  |d  }}|tj| |dd	 }|
j|d| | dd|f f||d
|	\}|
j|dt|| | ||f||d|	}t|| d ||||d}|
jd|j ||
 t|
j| |S )a  Visualize a waveform in the time domain.

    This function constructs a plot which adaptively switches between a raw
    samples-based view of the signal (`matplotlib.pyplot.step`) and an
    amplitude-envelope view of the signal (`matplotlib.pyplot.fill_between`)
    depending on the time extent of the plot's viewport.

    More specifically, when the plot spans a time interval of less than ``max_points /
    sr`` (by default, 1/2 second), the samples-based view is used, and otherwise a
    downsampled amplitude envelope is used.
    This is done to limit the complexity of the visual elements to guarantee an
    efficient, visually interpretable plot.

    When using interactive rendering (e.g., in a Jupyter notebook or IPython
    console), the plot will automatically update as the view-port is changed, either
    through widget controls or programmatic updates.

    .. note:: When visualizing stereo waveforms, the amplitude envelope will be generated
        so that the upper limits derive from the left channel, and the lower limits derive
        from the right channel, which can produce a vertically asymmetric plot.

        When zoomed in to the sample view, only the first channel will be shown.
        If you want to visualize both channels at the sample level, it is recommended to
        plot each signal independently.

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

    sr : number > 0 [scalar]
        sampling rate of ``y`` (samples per second)

    max_points : positive integer
        Maximum number of samples to draw.  When the plot covers a time extent
        smaller than ``max_points / sr`` (default: 1/2 second), samples are drawn.

        If drawing raw samples would exceed `max_points`, then a downsampled
        amplitude envelope extracted from non-overlapping windows of `y` is
        visualized instead.  The parameters of the amplitude envelope are defined so
        that the resulting plot cannot produce more than `max_points` frames.

    x_axis : str or None
        Display of the x-axis ticks and tick markers. Accepted values are:

        - 'time' : markers are shown as milliseconds, seconds, minutes, or hours.
                    Values are plotted in units of seconds.

        - 's' : markers are shown as seconds.

        - 'ms' : markers are shown as milliseconds.

        - 'lag' : like time, but past the halfway point counts as negative values.

        - 'lag_s' : same as lag, but in seconds.

        - 'lag_ms' : same as lag, but in milliseconds.

        - `None`, 'none', or 'off': ticks and tick markers are hidden.

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

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

    marker : string
        Marker symbol to use for sample values. (default: no markers)

        See also: `matplotlib.markers`.

    where : string, {'pre', 'mid', 'post'}
        This setting determines how both waveform and envelope plots interpolate
        between observations.

        See `matplotlib.pyplot.step` for details.

        Default: 'post'

    label : string [optional]
        The label string applied to this plot.
        Note that the label

    **kwargs
        Additional keyword arguments to `matplotlib.pyplot.fill_between` and
        `matplotlib.pyplot.step`.

        Note that only those arguments which are common to both functions will be
        supported.

    Returns
    -------
    librosa.display.AdaptiveWaveplot
        An object of type `librosa.display.AdaptiveWaveplot`

    See Also
    --------
    AdaptiveWaveplot
    matplotlib.pyplot.step
    matplotlib.pyplot.fill_between
    matplotlib.markers

    Examples
    --------
    Plot a monophonic waveform with an envelope view

    >>> import matplotlib.pyplot as plt
    >>> y, sr = librosa.load(librosa.ex('choice'), duration=10)
    >>> fig, ax = plt.subplots(nrows=3, sharex=True)
    >>> librosa.display.waveshow(y, sr=sr, ax=ax[0])
    >>> ax[0].set(title='Envelope view, mono')
    >>> ax[0].label_outer()

    Or a stereo waveform

    >>> y, sr = librosa.load(librosa.ex('choice', hq=True), mono=False, duration=10)
    >>> librosa.display.waveshow(y, sr=sr, ax=ax[1])
    >>> ax[1].set(title='Envelope view, stereo')
    >>> ax[1].label_outer()

    Or harmonic and percussive components with transparency

    >>> y, sr = librosa.load(librosa.ex('choice'), duration=10)
    >>> y_harm, y_perc = librosa.effects.hpss(y)
    >>> librosa.display.waveshow(y_harm, sr=sr, alpha=0.5, ax=ax[2], label='Harmonic')
    >>> librosa.display.waveshow(y_perc, sr=sr, color='r', alpha=0.5, ax=ax[2], label='Percussive')
    >>> ax[2].set(title='Multiple waveforms')
    >>> ax[2].legend()

    Zooming in on a plot to show raw sample values

    >>> fig, (ax, ax2) = plt.subplots(nrows=2, sharex=True)
    >>> ax.set(xlim=[6.0, 6.01], title='Sample view', ylim=[-0.2, 0.2])
    >>> librosa.display.waveshow(y, sr=sr, ax=ax, marker='.', label='Full signal')
    >>> librosa.display.waveshow(y_harm, sr=sr, alpha=0.5, ax=ax2, label='Harmonic')
    >>> librosa.display.waveshow(y_perc, sr=sr, color='r', alpha=0.5, ax=ax2, label='Percussive')
    >>> ax.label_outer()
    >>> ax.legend()
    >>> ax2.legend()

    F)Zmonor   Nr   z'max_points={} must be strictly positivecolorrY   r   )r   r   )stepr   )rV   rW   Zxlim_changed)r   Zvalid_audiondimr(   Znewaxisr   r   r   r   nextZ
_get_linesZprop_cyclerrC   r   rl   r   Z
times_liker   Zfill_betweenr   r   	callbacksconnectr_   r   r   )rX   rV   r   rr   r   r   r   r   r^   r   r   rj   Zy_envZy_bottomZy_toprR   rT   rU   Zadaptorr   r   r    r     s\     


       
)r9   NNNT)rP   N)r   NrP   F)Nro   rP   )ro   )rP   rm   )rP   rm   N)rP   rm   )5r8   r   Znumpyr(   Zmatplotlib.cmr   Zmatplotlib.axesr   Zmatplotlib.tickerr   r   r   r   r   r	   r   Zpackaging.versionr
   r   r#   r   r   Zutil.exceptionsr   Zutil.decoratorsr   __all__r   r   rD   r   r   rO   r   r   r   rl   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    <module>   s   #mAZ-(W   8	  ,8         
 +







