a
    Sic                    @   sX  d Z ddlZddlmZ ddlZddlmZ ddl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 ddlmZ ddlmZ ddl m!Z" ddl#m$Z% G dd dej&Z'd	d
 Z(G dd dZ)dd Z*dd Z+e
j,j-dd e
j.G dd dej/e)Z0e
j.G dd de0Z1e
j,j-de
j,j2 d dS )zG
Classes to support contour plotting and labelling for the Axes class.
    N)Integral)ma)_api
_docstring)MouseButtonc                       s    e Zd ZdZ fddZ  ZS )
ClabelTextz
    Unlike the ordinary text, the get_rotation returns an updated
    angle in the pixel coordinate assuming that the input rotation is
    an angle in data coordinate (or whatever transform set).
    c                    s$   |   t  g|  g\}|S N)get_transformtransform_anglessuperget_rotationget_position)selfZ	new_angle	__class__ N/var/www/html/django/DPS/env/lib/python3.9/site-packages/matplotlib/contour.pyr   )   s    zClabelText.get_rotation)__name__
__module____qualname____doc__r   __classcell__r   r   r   r   r   "   s   r   c                 C   s   | j jj}|jdk}|jdk}|r.|jtjks<|rF|jdv rF|  n~|rV|jtj	ksd|rz|jdv rz|s| 
  |  nJ|r|jtjks|r|jd ur|j| j kr| j|j|jd||d |  d S )Nbutton_press_eventkey_press_event)escapeenter)Z	backspacedeleteF)	transforminlineinline_spacing)axesfigurecanvasnamebuttonr   MIDDLEkeyZstop_event_loopRIGHT	pop_labeldrawLEFTinaxesadd_label_nearxy)csr   r   eventr"   Z	is_buttonis_keyr   r   r   _contour_labeler_event_handler/   s6    




r2   c                   @   s   e Zd ZdZd+dddddddddd	ddZd	d
 Zdd Zdd Ze	ddd Z
dd Zdd Zdd Zd,ddZdd Zdd Zdd Zd d! Zd"d# Zd-d$d%Zd.d'd(Zd)d* ZdS )/ContourLabelerz7Mixin to provide labelling capability to `.ContourSet`.NT   F)	fontsizer   r   fmtcolorsuse_clabeltextmanualrightside_upzorderc       	      
   C   s   |du rt jdd}|  || _|| _|| _|	| _|
du rJd| j | _n|
| _|du rr| j	}t
tt| j}nht
|}g g  }}t| j	D ]$\}}||v r|| || qt|t|k rtd| d| j	 || _|| _t | _| j| | j }|gt| | _|du r:| | _t| j| j| _n<tj|t| jd}t
tt| j| _tj |t! d| _g | _"t#| jr| jD ]\}}| $|||| qn\| jrt%d	 t%d
 |st%d t&j'j(| j)j*ddgdt+,t-| ||d n| .|| t/0d| j1| _2| j2S )a  
        Label a contour plot.

        Adds labels to line contours in this `.ContourSet` (which inherits from
        this mixin class).

        Parameters
        ----------
        levels : array-like, optional
            A list of level values, that should be labeled. The list must be
            a subset of ``cs.levels``. If not given, all levels are labeled.

        fontsize : str or float, default: :rc:`font.size`
            Size in points or relative size e.g., 'smaller', 'x-large'.
            See `.Text.set_size` for accepted string values.

        colors : color or colors or None, default: None
            The label colors:

            - If *None*, the color of each label matches the color of
              the corresponding contour.

            - If one string color, e.g., *colors* = 'r' or *colors* =
              'red', all labels will be plotted in this color.

            - If a tuple of colors (string, float, rgb, etc), different labels
              will be plotted in different colors in the order specified.

        inline : bool, default: True
            If ``True`` the underlying contour is removed where the label is
            placed.

        inline_spacing : float, default: 5
            Space in pixels to leave on each side of label when placing inline.

            This spacing will be exact for labels at locations where the
            contour is straight, less so for labels on curved contours.

        fmt : `.Formatter` or str or callable or dict, optional
            How the levels are formatted:

            - If a `.Formatter`, it is used to format all levels at once, using
              its `.Formatter.format_ticks` method.
            - If a str, it is interpreted as a %-style format string.
            - If a callable, it is called with one level at a time and should
              return the corresponding label.
            - If a dict, it should directly map levels to labels.

            The default is to use a standard `.ScalarFormatter`.

        manual : bool or iterable, default: False
            If ``True``, contour labels will be placed manually using
            mouse clicks. Click the first button near a contour to
            add a label, click the second button (or potentially both
            mouse buttons at once) to finish adding labels. The third
            button can be used to remove the last label added, but
            only if labels are not inline. Alternatively, the keyboard
            can be used to select label locations (enter to end label
            placement, delete or backspace act like the third mouse button,
            and any other key will select a label location).

            *manual* can also be an iterable object of (x, y) tuples.
            Contour labels will be created as if mouse is clicked at each
            (x, y) position.

        rightside_up : bool, default: True
            If ``True``, label rotations will always be plus
            or minus 90 degrees from level.

        use_clabeltext : bool, default: False
            If ``True``, `.ClabelText` class (instead of `.Text`) is used to
            create labels. `ClabelText` recalculates rotation angles
            of texts during the drawing time, therefore this can be used if
            aspect of the axes changes.

        zorder : float or None, default: ``(2 + contour.get_zorder())``
            zorder of the contour labels.

        Returns
        -------
        labels
            A list of `.Text` instances for the labels.
        NF)	useOffset   zSpecified levels z don't match available levels N)cmapnormz9Select label locations manually using first mouse button.z.End manual selection with second mouse button.z1Remove last label by clicking third mouse button.r   r   )timeouthandlerz	text.Text)3tickerScalarFormattercreate_dummy_axislabelFmt_use_clabeltextZlabelManualr:   _contour_zorder_clabel_zorderlevelslistrangelencvalues	enumerateappend
ValueErrorlabelLevelListlabelIndiceListfont_managerFontPropertieslabelFontPropsset_sizeZget_size_in_pointslabelFontSizeListlabelMappablenptakelabelCValueListmcolorsListedColormapcmScalarMappableNoNormlabelXYsiterabler,   printmplZ_blocking_inputZblocking_input_loopr    r!   	functoolspartialr2   labelscbooksilent_list
labelTextsZlabelTextsList)r   rL   r5   r   r   r6   r7   r8   r9   r:   r;   indicesZlevlabsilevZfont_size_ptsr@   r-   r.   r   r   r   clabelO   sp    a





zContourLabeler.clabelc                 C   s*   t |d| kp(tj|ddd| k S )z8Return whether a contour is long enough to hold a label.
   r   axis333333?)rO   r\   ptpany)r   linecontour
labelwidthr   r   r   print_label   s    zContourLabeler.print_labelc                    s(   d| d  t  fdd| jD S )z5Return whether a label is already near this location.ru   r=   c                 3   s2   | ]*}|d   d |d  d   k V  qdS )r   r=      Nr   ).0locthreshr-   r.   r   r   	<genexpr>   s   z+ContourLabeler.too_close.<locals>.<genexpr>)rw   rd   )r   r-   r.   lwr   r~   r   	too_close   s    zContourLabeler.too_closec                 C   sF   | j j}| }tjdd| | j| | j|| j| | j	d
|jS )z/Return the width of the *nth* label, in pixels.r   r!   sizeZfontproperties)r    r!   _get_renderertextTextget_textrT   rH   rZ   rX   get_window_extentwidth)r   nthfigrendererr   r   r   _get_nth_label_width   s    z#ContourLabeler._get_nth_label_widthz3.5c                 C   sX   t |ts| ||}| jj}| }tjdd|||| jd	|j
}|d|j 9 }|S )z(Return the width of the label in points.r   r   H   )
isinstancestrr   r    r!   r   r   r   rX   r   r   dpi)r   rp   r6   fsizer   r   r   r   r   r   get_label_width  s    
zContourLabeler.get_label_widthc                 C   s2   | | || || j || jj dS )z1Set the label properties - color, fontsize, text.N)set_text	set_colorZset_fontpropertiesrX   set_clip_boxr    bbox)r   labelr   colorr   r   r   set_label_props  s    

zContourLabeler.set_label_propsc                 C   sh   t |tr|S t |tr$||dS tt|ddrL|g | j|d S t|r\||S || S dS )zGet the text of the label.z%1.3fformat_ticksNrB   )r   r   dictgetcallablegetattrr   rT   )r   rp   r6   r   r   r   r     s    

zContourLabeler.get_textc                 C   s  t |}|dkr"tt|| nd}|dkr2|nt|}t|dddf ||f}t|dddf ||f}|ddddf }|ddddf }	|ddddf }
|ddddf }|| ||
  |
| |	|   }t||
 |	| }tjddd$ t|| jdd}W d   n1 s00    Y  |d }t	|}t
||d D ]6}|||f |||f  }}| |||s\ qq\|||| | | fS )	zX
        Find good place to draw a label (relatively flat part of the contour).
        r{   Nr   rB   ignore)divideinvalidrs   r=   )rO   intr\   ceilresizehypoterrstateabssumargsortrR   r   )r   rx   ry   Zctr_sizeZn_blocks
block_sizexxyyZyfirstZylastZxfirstZxlastsl	distancesZhbsizeZadistidxr-   r.   r   r   r   locate_label(  s(     4

zContourLabeler.locate_labelc              	      s  |du rg }|d }t |}|rpt||d |d|d  g}t|rlt||d |d|d  g}d}tj|jd tdtj|dd}tt	|dddf |dddf dd< |  t
| |g|rt
d dg n
t  fdd	|jD \\}\}	tt|	|}
| jrL|
d
 d d
 }
g }t|r  t
| |g tjttddd}t|d tt|d tg}|d dkr܇fdd|jD }|d dkr fdd|jD }|rFtdd	 |D r|t|||d |d d  |g n`|d dkrx|t|d|d d  |g |d dkr|t|||d d g |
|fS )a  
        Calculate the appropriate label rotation given the linecontour
        coordinates in screen units, the index of the label location and the
        label width.

        If *lc* is not None or empty, also break contours and compute
        inlining.

        *spacing* is the empty space to leave around the label, in pixels.

        Both tasks are done together to avoid calculating path lengths
        multiple times, which is relatively costly.

        The method used here involves computing the path length along the
        contour in pixel coordinates and then looking approximately (label
        width / 2) away from central point to determine rotation and then to
        break contour if desired.
        Ng       @rB   r{   r   dtypers   c                 3   s&   | ]}t t   |V  qd S r   )r\   diffinterp)r|   Zslc_coldpplxir   r   r   z  s   z;ContourLabeler.calc_label_rot_and_inline.<locals>.<genexpr>Z      )leftrightc                    s   g | ]}t d   |qS )r   r\   r   r|   Zlc_colr   r   r   r   
<listcomp>      z<ContourLabeler.calc_label_rot_and_inline.<locals>.<listcomp>c                    s   g | ]}t d   |qS r{   r   r   r   r   r   r     r   c                 s   s   | ]}|d kV  qdS )rB   Nr   )r|   ro   r   r   r   r     r   )_is_closed_polygonr\   concatenaterO   zerosshapefloatr   cumsumr   array
zeros_likeTrad2degarctan2r:   r   arangefloorastyper   r   allrR   	row_stack)r   slcindr   lcspacingZhlwcloseddxdyrotationnlcIxy1xy2r   r   r   calc_label_rot_and_inlineJ  sP    ""2

(,$ z(ContourLabeler.calc_label_rot_and_inlinec                 C   s6   | j j ||f\}}tj|||dd| jd}|S )Ncenterr   ZhorizontalalignmentZverticalalignmentr;   )r    	transDatainvertedr   r   r   rK   )r   r-   r.   r   r   r   tr   r   r   _get_label_text  s    
zContourLabeler._get_label_textc           	      C   s\   | j j }|||f\}}|t|gt||gg}t|||d dd| jd}|S )Nr   r   r   )	r    r   r   r   r
   r\   r   r   rK   )	r   r-   r.   r   ZtransDataInvr   r   Z	drotationr   r   r   r   _get_label_clabeltext  s    z$ContourLabeler._get_label_clabeltextc                 C   sf   | j j|| jd}| || j}| ||| | j| | j| | j	||f | j
| d S )Nalpha)r[   to_rgbar   r   rH   r   rm   rR   labelCValuesrd   r    
add_artist)r   r   r-   r.   rp   cvaluer   _textr   r   r   
_add_label  s    zContourLabeler._add_labelc                 C   s$   |  |||}| ||||| dS )zO
        Add contour label using :class:`~matplotlib.text.Text` class.
        N)r   r   r   r-   r.   r   rp   r   r   r   r   r   	add_label  s    zContourLabeler.add_labelc                 C   s$   |  |||}| ||||| dS )zD
        Add contour label using :class:`ClabelText` class.
        N)r   r   r   r   r   r   add_label_clabeltext  s    z#ContourLabeler.add_label_clabeltextc                 C   s*  |du r| j j}|r&|||f\}}| ||| jdd \}}}}	}
| j|  }|| j}| j j |	|
g}t	
||| st	j|||dd}t|||< | j|}| |}| | j j||||r|nd|\}}| |	|
|| j| | j|  |r&|| |dd |D  dS )a  
        Add a label near the point ``(x, y)``.

        Parameters
        ----------
        x, y : float
            The approximate location of the label.
        inline : bool, default: True
            If *True* remove the segment of the contour beneath the label.
        inline_spacing : int, default: 5
            Space in pixels to leave on each side of label when placing
            inline. This spacing will be exact for labels at locations where
            the contour is straight, less so for labels on curved contours.
        transform : `.Transform` or `False`, default: ``self.axes.transData``
            A transform applied to ``(x, y)`` before labeling.  The default
            causes ``(x, y)`` to be interpreted as data coordinates.  `False`
            is a synonym for `.IdentityTransform`; i.e. ``(x, y)`` should be
            interpreted as display coordinates.
        Nr4   r   rs   c                 S   s"   g | ]}t |d krt|qS r   )rO   mpathPath)r|   nr   r   r   r     r   z1ContourLabeler.add_label_near.<locals>.<listcomp>)r    r   r   find_nearest_contourrU   collections	get_pathsverticesr   r\   allcloseinsertr   r   indexr   r   r   rT   r^   popextend)r   r-   r.   r   r   r   conminsegminiminxminyminpathsr   Zxcminlminr   r   r   r   r   r   r,     s6    


zContourLabeler.add_label_nearrB   c                 C   s$   | j | | j|}|  dS )z>Defaults to removing last label, but any index can be suppliedN)r   r   rm   remove)r   r   r   r   r   r   r(     s    zContourLabeler.pop_labelc              	   C   s  | j r| j}n| j}tt| j| j| jD ]\}\}}}| j| }|	 }	| 
|}
g }| }t|D ]\}}|j}|	|}| ||
r| ||
\}}}| |||
|r|nd |\}}|||||| |r|D ] }t|dkr|t| qqh|| qh|r*||d d < q*d S )Nr{   )rI   r   r   rQ   ziprU   rT   r^   r   r	   r   r   r   r   rz   r   r   rO   rR   r   r   )r   r   r   r   r   iconrp   r   contransr   	additionsr  segNumlinepathr   r   r-   r.   r   r   newr   r   r   r   rj     s:    


zContourLabeler.labels)N)Nr4   )Tr4   N)rB   )r   r   r   r   rq   rz   r   r   r   
deprecatedr   r   r   r   r   r   r   r   r   r   r,   r(   rj   r   r   r   r   r3   L   s4    "
"
Z  
@
r3   c                 C   s   t j| d | d dddS )z
    Return whether first and last object in a sequence are the same. These are
    presumably coordinates on a polygonal curve, in which case this function
    tests if that curve is closed.
    r   rB   g|=gvIh%<=)rtolatol)r\   r   )Xr   r   r   r   M  s    r   c                 C   s   t | dkr*|| d  d  | d dfS | dd | dd  }|d jdd}d||dk< t|| dd  | jdd| dddddf }| dd ||  }|| d jdd}t|}|| || ||d ffS )a  
    Parameters
    ----------
    xys : (N, 2) array-like
        Coordinates of vertices.
    p : (float, float)
        Coordinates of point.

    Returns
    -------
    d2min : float
        Minimum square distance of *p* to *xys*.
    proj : (float, float)
        Projection of *p* onto *xys*.
    imin : (int, int)
        Consecutive indices of vertices of segment in *xys* where *proj* is.
        Segments are considered as including their end-points; i.e if the
        closest point on the path is a node in *xys* with index *i*, this
        returns ``(i-1, i)``.  For the special case where *xys* is a single
        point, this returns ``(0, 0)``.
    r{   r   r=   r   r   NrB   rs   )rO   r   r\   clipargmin)xyspZdxysnormsZ	rel_projsZprojsZd2sr  r   r   r   _find_closest_point_on_pathV  s    

r  a  
Attributes
----------
ax : `~matplotlib.axes.Axes`
    The Axes object in which the contours are drawn.

collections : `.silent_list` of `.PathCollection`\s
    The `.Artist`\s representing the contour. This is a list of
    `.PathCollection`\s for both line and filled contours.

levels : array
    The values of the contour levels.

layers : array
    Same as levels for line contours; half-way between
    levels for filled contours.  See ``ContourSet._process_colors``.
)Zcontour_set_attributesc                   @   s   e Zd ZdZdddddddddddddddddddddd	Zd
d Zdd ZdefddZdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd.d,d-ZdS )/
ContourSeta  
    Store a set of contour lines or filled regions.

    User-callable method: `~.Axes.clabel`

    Parameters
    ----------
    ax : `~.axes.Axes`

    levels : [level0, level1, ..., leveln]
        A list of floating point numbers indicating the contour levels.

    allsegs : [level0segs, level1segs, ...]
        List of all the polygon segments for all the *levels*.
        For contour lines ``len(allsegs) == len(levels)``, and for
        filled contour regions ``len(allsegs) = len(levels)-1``. The lists
        should look like ::

            level0segs = [polygon0, polygon1, ...]
            polygon0 = [[x0, y0], [x1, y1], ...]

    allkinds : ``None`` or [level0kinds, level1kinds, ...]
        Optional list of all the polygon vertex kinds (code types), as
        described and used in Path. This is used to allow multiply-
        connected paths such as holes within filled polygons.
        If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
        should look like ::

            level0kinds = [polygon0kinds, ...]
            polygon0kinds = [vertexcode0, vertexcode1, ...]

        If *allkinds* is not ``None``, usually all polygons for a
        particular contour level are grouped together so that
        ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.

    **kwargs
        Keyword arguments are as described in the docstring of
        `~.Axes.contour`.

    %(contour_set_attributes)s
    NFr   neitherr   )rL   filled
linewidths
linestyleshatchesr   originextentr@   r7   rA   vminvmaxr   antialiasednchunklocatorr   negative_linestylesc          !         sN  |_ |_|_|_|_|_|_|_|	_|_	|_
|_jdu r^jr^d_|_|_t|tjstjtjrd_|du rt }nd_tjg d|d jdurtjdkrtdj	dur|
durtdjd	krtjd
 _|_|_jdu r*tjd _j|i |}  j
dv _j
dv _j	durtj}jr|d8 }d}d}|t j t j }tj	|krЈjsjrd}jrd}tj!j	|d |d}
|rjr|
"j	d  jr|
#j	d  t$%d_&g _'g _(d|
i}|durP||d< t)j*j+fi | |durv|j,_-|dur|j,_./  t0dddu r1 \_2_3nj3du rdgtj2 _3jr6jdurt4d 5 \}}|6dd_7fddt8||j2j3D j&dd< nl9  _:}; }j  durdjf |6dd_7 fddt8j||j2j3D j&dd< j&D ]V} j j<| dd j=d j>d g| j?j@dd< j=d j>d g| j?jAdd< qj Bj=j>g j jCdd D  |rJt4ddEtFtG|  dS )a  
        Draw contour lines or filled regions, depending on
        whether keyword arg *filled* is ``False`` (default) or ``True``.

        Call signature::

            ContourSet(ax, levels, allsegs, [allkinds], **kwargs)

        Parameters
        ----------
        ax : `~.axes.Axes`
            The `~.axes.Axes` object to draw on.

        levels : [level0, level1, ..., leveln]
            A list of floating point numbers indicating the contour
            levels.

        allsegs : [level0segs, level1segs, ...]
            List of all the polygon segments for all the *levels*.
            For contour lines ``len(allsegs) == len(levels)``, and for
            filled contour regions ``len(allsegs) = len(levels)-1``. The lists
            should look like ::

                level0segs = [polygon0, polygon1, ...]
                polygon0 = [[x0, y0], [x1, y1], ...]

        allkinds : [level0kinds, level1kinds, ...], optional
            Optional list of all the polygon vertex kinds (code types), as
            described and used in Path. This is used to allow multiply-
            connected paths such as holes within filled polygons.
            If not ``None``, ``len(allkinds) == len(allsegs)``. The lists
            should look like ::

                level0kinds = [polygon0kinds, ...]
                polygon0kinds = [vertexcode0, vertexcode1, ...]

            If *allkinds* is not ``None``, usually all polygons for a
            particular contour level are grouped together so that
            ``level0segs = [polygon0]`` and ``level0kinds = [polygon0kinds]``.

        **kwargs
            Keyword arguments are as described in the docstring of
            `~.Axes.contour`.
        NFT)Nlowerupperimage)r"     z3If given, 'extent' must be None or (x0, x1, y0, y1)z"Either colors or cmap must be Noner,  zimage.originzcontour.negative_linestyleminbothmaxr0  r{   r   r>   rB   r@   rA   allsegsz!linewidths is ignored by contourfr;   c              
      s>   g | ]6\}}}}t j || jfd  j   jdqS )none)antialiaseds
edgecolorsr   r   r;   )mcollPathCollection_make_pathsr&  r   r	   rJ   )r|   levellevel_uppersegskindsr   r   r   r   ^  s   

z'ContourSet.__init__.<locals>.<listcomp>r=   c                    sD   g | ]<\}}}}}t j||d  ||gj jdd	qS )r4  Z
_nolegend_)
facecolorsr5  r  r   r   r   r;   r   )r7  r8  r9  r   r	   rJ   )r|   r:  r   Zlstyler<  r=  aar   r   r   r   r  s   
)Zautolim)tightz/The following kwargs were not used by contour: z, )Hr    rL   r  r  r   r!  r   r"  r#  r7   r   r&  r'  r(  r   r_   LogNormrE   
LogLocatorlogscaler   check_in_listrO   rS   rg   rcParams
_transformr)  _process_args_process_levelsZ_extend_minZ_extend_maxr   r`   	set_underset_overrk   rl   r   rm   r   ra   rb   __init__rA   r$  r%  _process_colorsr   _get_allsegs_and_allkindsr3  allkindswarn_external_get_lowers_and_uppersr   rJ   r	  _process_linewidthstlinewidths_process_linestylesadd_collection_mins_maxssticky_edgesr-   r.   Zupdate_datalimZautoscale_viewchangedjoinmaprepr)!r   axrL   r  r  r   r!  r   r"  r#  r@   r7   rA   r$  r%  r   r&  r'  r(  r   r)  argskwargsncolorsi0Zuse_set_under_overZtotal_levelskwlowersuppersrT  tlinestylescolr   r@  r   rM    s    3






	

 $zContourSet.__init__c                 C   sF   | j du r| jj| _ n*t| j tjs@t| j dr@| j | j| _ | j S )z9Return the `.Transform` instance used by this ContourSet.N_as_mpl_transform)rH  r    r   r   mtransforms	Transformhasattrrh  r>  r   r   r   r	     s    

zContourSet.get_transformc                 C   s   | j  }d |d< |S )N_contour_generator)__dict__copy)r   stater   r   r   __getstate__  s    
zContourSet.__getstate__r-   c              
   C   sd  g }g }| j r|  \}}t| j}tt| j||D ]\}\}	}
}tjddd|	 d |		 |	
 d}|| ||
}
||}|dkr| jdv r|d| d|
 d q8||d kr| jd	v r|d| d
| d q8|d|
 d| d| d q8nXt| j| jD ]H\}	}td}||	 || ||}|d| d| d q||fS )a  
        Return a list of artists and labels suitable for passing through
        to `~.Axes.legend` which represent this ContourSet.

        The labels have the form "0 < x <= 1" stating the data ranges which
        the artists represent.

        Parameters
        ----------
        variable_name : str
            The string used inside the inequality used on the labels.
        str_format : function: float -> str
            Function used to format the numbers in the labels.

        Returns
        -------
        artists : list[`.Artist`]
            A list of the artists.
        labels : list[str]
            A list of the labels.
        r  r{   r   )	facecolorhatchr   r.  $z \leq zs$r1  z > z < Nz = )r  rR  rO   r   rQ   r	  mpatches	Rectangleget_facecolor	get_hatch	get_alpharR   r   rL   r7  LineCollectionupdate_from)r   variable_name
str_formatartistsrj   rd  re  Zn_levelsro   
collectionr*  r+  patchr:  r   r   r   legend_elements  s:    


"


zContourSet.legend_elementsc                 O   s   |d | _ |d | _t|dkr(|d nd| _t| j | _t| j | _| j	rrt| jt| j d krt
dnt| jt| j krt
d| jdurt| jt| jkrt
ddd	 | jD }tj|dd
}|jdd
| _|jdd
| _|S )z
        Process *args* and *kwargs*; override in derived classes.

        Must set self.levels, self.zmin and self.zmax, and update axes limits.
        r   r{   r=   Nz-must be one less number of segments as levelsz)must be same number of segments as levelsz(allkinds has different length to allsegsc                 S   s   g | ]}|D ]}|qqS r   r   )r|   segr   r   r   r   r     r   z,ContourSet._process_args.<locals>.<listcomp>rs   )rL   r3  rO   rP  r\   r2  zmaxr/  zminr  rS   r   rW  rX  )r   r_  r`  Zflatseglistpointsr   r   r   rI    s&    



zContourSet._process_argsc           	      C   s   g }g }| j rV|  \}}t||D ].\}}| j||\}}|| || q$n0| jD ](}| j|\}}|| || q\||fS )z7Compute ``allsegs`` and ``allkinds`` using C extension.)r  rR  r	  rl  Zcreate_filled_contourrR   rL   Zcreate_contour)	r   r3  rP  rd  re  r:  r;  r   r=  r   r   r   rO    s     


z$ContourSet._get_allsegs_and_allkindsc                 C   s`   | j dd }| j|d krJ| }| jr:d| j |d< n|d  d8  < | j dd }||fS )zB
        Return ``(lowers, uppers)`` for filled contours.
        NrB   r   gGz?r{   )_levelsr  rn  rE  )r   rd  re  r   r   r   rR    s    z!ContourSet._get_lowers_and_uppersc                 C   s.   |du rdd |D S dd t ||D S dS )aB  
        Create and return Path objects for the specified segments and optional
        kind codes.  segs is a list of numpy arrays, each array is either a
        closed line loop or open line strip of 2D points with a shape of
        (npoints, 2).  kinds is either None or a list (with the same length as
        segs) of numpy arrays, each array is of shape (npoints,) and contains
        the kinds codes for the corresponding line in segs.  If kinds is None
        then the Path constructor creates the kind codes assuming that the line
        is an open strip.
        Nc                 S   s   g | ]}t |qS r   r   r   )r|   r  r   r   r   r   -  r   z*ContourSet._make_paths.<locals>.<listcomp>c                 S   s   g | ]\}}t j||d qS ))codesr  )r|   r  kindr   r   r   r   /  r   )r	  )r   r<  r=  r   r   r   r9  !  s
    zContourSet._make_pathsc                 C   s   t | dstj|  d S | j| j dd | j| j| j	dD }|| _
| jt| }t||| jD ]0\}}}| jr|| || qf|| qft| j| jD ]&\}}|| j	 || j| qtj|  d S )NrP   c                 S   s   g | ]}t |fqS r   )tuple)r|   rgbar   r   r   r   <  s   z&ContourSet.changed.<locals>.<listcomp>r   )rk  ra   rb   rZ  rA   autoscale_NonerL   r   rP   r   tcolorsr!  rO   r	  r   r  set_facecolor	set_hatchset_edgecolorrm   r   	set_alphar   r[   )r   r  r!  r   rr  r~  r   Zcvr   r   r   rZ  2  s(    

zContourSet.changedc                 C   s  | j du r0| jrt | _ ntj|d dd| _ | j | j| j}z| j jrR|W S W n t	yf   Y n0 t
|| jk d }t|r|d nd}t
|| jkd }t|r|d d nt|}| jdv r|d7 }| jdv r|d8 }|| dk r dt| }}||| S )	a,  
        Select contour levels to span the data.

        The target number of levels, *N*, is used only when the
        scale is not log and default locator is used.

        We need two more levels for filled contours than for
        line contours, because for the latter we need to specify
        the lower and upper boundary of each range. For example,
        a single contour boundary, say at z = 0, requires only
        one contour line, but two filled regions, and therefore
        three levels to provide boundaries for both regions.
        Nr{   )min_n_ticksr   rB   r.  r1     )r(  rE  rE   rD  MaxNLocatortick_valuesr  r  
_symmetricAttributeErrorr\   nonzerorO   r   )r   r?   rp   underrb  overi1r   r   r   _autolevN  s*    



zContourSet._autolevc                 C   s   | j du r&t|dkrd}q,|d }n| j }t|trD| || _ nt|tj| _ | j	s| j | j
k| j | jk @ }| j | }t|dkr| j
g| _ td | j	rt| j dk rtdt| j dkrtt| j dkrtd	dS )
zH
        Determine the contour levels and store in self.levels.
        Nr      z3No contour levels were found within the data range.r=   z*Filled contours require at least 2 levels.r{   g        z!Contour levels must be increasing)rL   rO   r   r   r  r\   asarrayr   float64r  r  r  r   rQ  rS   r/  r   )r   r_  Z
levels_arginsideZ	levels_inr   r   r   _process_contour_level_argsy  s(    




$z&ContourSet._process_contour_level_argsc                 C   s   t | j| _| jrd\}}nd\}}| jdv r<| jd| | jdv rR| j| t| j| _| j	sr| j| _
dS | jrt| jdd t| jdd  | _
n"d	| jdd | jdd   | _
dS )
a&  
        Assign values to :attr:`layers` based on :attr:`levels`,
        adding extended layers as needed if contours are filled.

        For line contours, layers simply coincide with levels;
        a line is a thin layer.  No extended levels are needed
        with line contours.
        )gL]?RyXs)gRyXr  r0  r/  r   r0  r2  NrB   r{         ?)rM   rL   r  rE  r   r   rR   r\   r  r  layerssqrt)r   r*  r+  r   r   r   rJ    s"    


zContourSet._process_levelsc                 C   s   | j j| _| jdurvdt| j }}| jrV|d8 }| jdv rD|d8 }| jdv rV|d7 }tt||| _	| 
t  n| j| _	| | j |   | jdv rd| j_dS )a  
        Color argument processing for contouring.

        Note that we base the colormapping on the contour levels
        and layers, not on the actual range of the Z values.  This
        means we don't have to worry about bad values in Z, and we
        always have the full dynamic range available for the selected
        levels.

        The color is based on the midpoint of the layer, except for
        extended end layers.  By default, the norm vmin and vmax
        are the extreme values of the non-extended levels.  Hence,
        the layer color extremes are not the extreme values of
        the colormap itself, but approach those values as the number
        of levels increases.  An advantage of this scheme is that
        line contours, when added to filled contours, take on
        colors that are consistent with those of the filled regions;
        for example, a contour line on the boundary between two
        regions will have a color intermediate between those
        of the regions.

        Nr   r{   r  r  )r0  r2  r/  F)r@   
monochromer7   rO   rL   r  r   rM   rN   rP   set_normr_   rc   r  	set_arrayr  rA   r  )r   rb  r  r   r   r   rN    s     




zContourSet._process_colorsc                 C   s   | j }t| j}|d u rBtjd }|d u r4tjd }|fg| }nnt|sX|g| }nJt|}t||k rtt	|t| }|| }t||kr|d | }dd |D }|S )Nzcontour.linewidthzlines.linewidthc                 S   s   g | ]
}|fqS r   r   )r|   wr   r   r   r     r   z2ContourSet._process_linewidths.<locals>.<listcomp>)
r  rO   rL   rg   rG  r\   re   rM   r   r   )r   r  NlevZdefault_linewidthrT  nrepsr   r   r   rS    s"    



zContourSet._process_linewidthsc                 C   s   | j }t| j}|d u rbdg| }| jr| j| j  d }t| jD ]\}}||k rD| j||< qDntt|t	rx|g| }n^t
|rt|}t||k rtt
|t| }|| }t||kr|d | }ntd|S )NsolidgV瞯<z&Unrecognized type for linestyles kwarg)r   rO   rL   r  r  r  rQ   r)  r   r   r\   re   rM   r   r   rS   )r   r   r  rf  epsro   rp   r  r   r   r   rU    s(    



zContourSet._process_linestylesc                 C   s   | j S )z5Return alpha to be applied to all ContourSet artists.r   r>  r   r   r   rx    s    zContourSet.get_alphac                 C   s   || _ |   dS )z
        Set the alpha blending value for all ContourSet artists.
        *alpha* must be between 0 (transparent) and 1 (opaque).
        N)r   rZ  )r   r   r   r   r   r    s    zContourSet.set_alphaTc                 C   s   | j rtd|du r$tt| j}tj}d}d}d}d}	t||g}
|D ]}| j| }| }|	 }t
|D ]X\}}|j}|r||}t||
\}}}||k rr|}|}|}|d }|d }|d }	qrqL|||||	|fS )a|  
        Find the point in the contour plot that is closest to ``(x, y)``.

        This method does not support filled contours.

        Parameters
        ----------
        x, y : float
            The reference point.
        indices : list of int or None, default: None
            Indices of contour levels to consider.  If None (the default), all
            levels are considered.
        pixel : bool, default: True
            If *True*, measure distance in pixel (screen) space, which is
            useful for manual contour labeling; else, measure distance in axes
            space.

        Returns
        -------
        contour : `.Collection`
            The contour that is closest to ``(x, y)``.
        segment : int
            The index of the `.Path` in *contour* that is closest to
            ``(x, y)``.
        index : int
            The index of the path segment in *segment* that is closest to
            ``(x, y)``.
        xmin, ymin : float
            The point in the contour plot that is closest to ``(x, y)``.
        d2 : float
            The squared distance from ``(xmin, ymin)`` to ``(x, y)``.
        z(Method does not support filled contours.Nr{   r   )r  rS   rN   rO   r   r\   infr   r	   r   rQ   r   r   r  )r   r-   r.   rn   pixelZd2minr  r  r  r  pointr
  r  r  r  r  r  r   d2ZxcZlegr  r   r   r   r   "  s6    *

zContourSet.find_nearest_contour)NT)r   r   r   r   rM  r	   rp  r   r  rI  rO  rR  r9  rZ  r  r  rJ  rN  rS  rU  rx  r  r   r   r   r   r   r    s2   +
 X	<"+%-r  c                   @   s8   e Zd ZdZdddddZdd Zdd	 Zd
d ZdS )QuadContourSetz
    Create and store a set of contour lines or filled regions.

    This class is typically not instantiated directly by the user but by
    `~.Axes.contour` and `~.Axes.contourf`.

    %(contour_set_attributes)s
    N)corner_mask	algorithmc             
   O   s  t |d trz| jdu r$|d j| _|d j| _|d j| _|d j| _|d j}|d j| _|d j| _|d j	| _	n"ddl
}|du rtjd }tjjd | || _	|du r| j	dkrd}n
tjd }|| _| ||\}}}	|j|||	| j	| j|jj|jj| jd}|  }
|
| jjkrpt|
| jjrp|
| jj }t|j|jgj}||}|d }|d	 }t |t |g| _t!|t!|g| _|| _|S )
z*
        Process args and kwargs.
        r   Nzcontour.algorithmmpl2005Fzcontour.corner_mask)r#   r  	line_type	fill_type
chunk_size).r   ).r{   )"r   r  rL   r  r  Z_corner_maskrl  rW  rX  
_algorithm	contourpyrg   rG  validate_contour_argscontour_generatorZLineTypeZSeparateCodeZFillTypeZ	OuterCoder'  r	   r    r   rw   contains_branch_seperatelyr\   vstackflatr   r   r   r/  r2  )r   r  r  r_  r`  r  r  r-   r.   zr   Ztrans_to_dataptsZtransformed_ptsr   r   r   rI  |  sP    





zQuadContourSet._process_argsc                 C   s  | j rd}nd}t|}|dkrPtj|d tjd}| |\}}|dd  }n@|dkr| |d d |\}}}|dd  }ntd	||f tj	|d
d}t
| | _t
| | _| jr| jdkrt|dk|}td t
| | _| | |||fS )Ncontourfcontourr=   r   r   r{   r-  r  z&Too many arguments to %s; see help(%s)F)rn  z,Log scale: values of z <= 0 have been masked)r  rO   r   r  r\   r  _initialize_x_y
_check_xyz	TypeErrormasked_invalidr   r2  r  r/  r  rE  masked_wherer   rQ  r  )r   r_  r`  fnZNargsr  r-   r.   r   r   r   r    s.    

zQuadContourSet._contour_argsc           
      C   s  |dd \}}| j d|fd|fg|\}}tj|tjd}tj|tjd}tj|d tjd}|jdkr~td|j d|jd dk s|jd	 dk rtd
|j |j\}}|j|jkrtd|j d|j d|jd	krH|j\}|j\}	||krtd| d| d|	|kr6td|	 d| dt	||\}}np|jdkr|j|jkr|td|j d|j d|j|jkrtd|j d|j dntd|j d|||fS )z
        Check that the shapes of the input arrays match; if x and y are 1D,
        convert them to 2D using meshgrid.
        Nr=   r-   r.   r   Input z must be 2D, not Dr   r{   >Input z must be at least a (2, 2) shaped array, but has shape zNumber of dimensions of x (z	) and y (z) do not matchzLength of x (z%) must match number of columns in z ()zLength of y (z") must match number of rows in z (zShapes of x z and z z do not matchzShapes of y z%Inputs x and y must be 1D or 2D, not )
r    Z_process_unit_infor\   r  r  r   ndimr  r   meshgrid)
r   r_  r`  r-   r.   r  NyNxnxnyr   r   r   r    sN    








zQuadContourSet._check_xyzc                 C   sP  |j dkrtd|j  dn8|jd dk s:|jd dk rLtd|j n
|j\}}| jdu r| jdu rtt|t|S | j\}}}}t|||}t|||}	t||	S | jdu rd|d|f\}}}}n| j\}}}}|| | }
|| | }|t|d |
  }|t|d |  }	| jd	krD|	ddd
 }	t||	S )a  
        Return X, Y arrays such that contour(Z) will match imshow(Z)
        if origin is not None.
        The center of pixel Z[i, j] depends on origin:
        if origin is None, x = j, y = i;
        if origin is 'lower', x = j + 0.5, y = i + 0.5;
        if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5
        If extent is not None, x and y will be scaled to match,
        as in imshow.
        If origin is None and extent is not None, then extent
        will give the minimum and maximum values of x and y.
        r=   r  r  r   r{   r  Nr  r+  rB   )	r  r  r   r"  r#  r\   r  r   linspace)r   r  r  r  x0x1y0y1r-   r.   r   r   r   r   r   r    s0    





zQuadContourSet._initialize_x_y)r   r   r   r   rI  r  r  r  r   r   r   r   r  q  s
   	:,r  a-#  
`.contour` and `.contourf` draw contour lines and filled contours,
respectively.  Except as noted, function signatures and return values
are the same for both versions.

Parameters
----------
X, Y : array-like, optional
    The coordinates of the values in *Z*.

    *X* and *Y* must both be 2D with the same shape as *Z* (e.g.
    created via `numpy.meshgrid`), or they must both be 1-D such
    that ``len(X) == N`` is the number of columns in *Z* and
    ``len(Y) == M`` is the number of rows in *Z*.

    *X* and *Y* must both be ordered monotonically.

    If not given, they are assumed to be integer indices, i.e.
    ``X = range(N)``, ``Y = range(M)``.

Z : (M, N) array-like
    The height values over which the contour is drawn.  Color-mapping is
    controlled by *cmap*, *norm*, *vmin*, and *vmax*.

levels : int or array-like, optional
    Determines the number and positions of the contour lines / regions.

    If an int *n*, use `~matplotlib.ticker.MaxNLocator`, which tries
    to automatically choose no more than *n+1* "nice" contour levels
    between *vmin* and *vmax*.

    If array-like, draw contour lines at the specified levels.
    The values must be in increasing order.

Returns
-------
`~.contour.QuadContourSet`

Other Parameters
----------------
corner_mask : bool, default: :rc:`contour.corner_mask`
    Enable/disable corner masking, which only has an effect if *Z* is
    a masked array.  If ``False``, any quad touching a masked point is
    masked out.  If ``True``, only the triangular corners of quads
    nearest those points are always masked out, other triangular
    corners comprising three unmasked points are contoured as usual.

colors : color string or sequence of colors, optional
    The colors of the levels, i.e. the lines for `.contour` and the
    areas for `.contourf`.

    The sequence is cycled for the levels in ascending order. If the
    sequence is shorter than the number of levels, it's repeated.

    As a shortcut, single color strings may be used in place of
    one-element lists, i.e. ``'red'`` instead of ``['red']`` to color
    all levels with the same color. This shortcut does only work for
    color strings, not for other ways of specifying colors.

    By default (value *None*), the colormap specified by *cmap*
    will be used.

alpha : float, default: 1
    The alpha blending value, between 0 (transparent) and 1 (opaque).

%(cmap_doc)s

    This parameter is ignored if *colors* is set.

%(norm_doc)s

    This parameter is ignored if *colors* is set.

%(vmin_vmax_doc)s

    If *vmin* or *vmax* are not given, the default color scaling is based on
    *levels*.

    This parameter is ignored if *colors* is set.

origin : {*None*, 'upper', 'lower', 'image'}, default: None
    Determines the orientation and exact position of *Z* by specifying
    the position of ``Z[0, 0]``.  This is only relevant, if *X*, *Y*
    are not given.

    - *None*: ``Z[0, 0]`` is at X=0, Y=0 in the lower left corner.
    - 'lower': ``Z[0, 0]`` is at X=0.5, Y=0.5 in the lower left corner.
    - 'upper': ``Z[0, 0]`` is at X=N+0.5, Y=0.5 in the upper left
      corner.
    - 'image': Use the value from :rc:`image.origin`.

extent : (x0, x1, y0, y1), optional
    If *origin* is not *None*, then *extent* is interpreted as in
    `.imshow`: it gives the outer pixel boundaries. In this case, the
    position of Z[0, 0] is the center of the pixel, not a corner. If
    *origin* is *None*, then (*x0*, *y0*) is the position of Z[0, 0],
    and (*x1*, *y1*) is the position of Z[-1, -1].

    This argument is ignored if *X* and *Y* are specified in the call
    to contour.

locator : ticker.Locator subclass, optional
    The locator is used to determine the contour levels if they
    are not given explicitly via *levels*.
    Defaults to `~.ticker.MaxNLocator`.

extend : {'neither', 'both', 'min', 'max'}, default: 'neither'
    Determines the ``contourf``-coloring of values that are outside the
    *levels* range.

    If 'neither', values outside the *levels* range are not colored.
    If 'min', 'max' or 'both', color the values below, above or below
    and above the *levels* range.

    Values below ``min(levels)`` and above ``max(levels)`` are mapped
    to the under/over values of the `.Colormap`. Note that most
    colormaps do not have dedicated colors for these by default, so
    that the over and under values are the edge values of the colormap.
    You may want to set these values explicitly using
    `.Colormap.set_under` and `.Colormap.set_over`.

    .. note::

        An existing `.QuadContourSet` does not get notified if
        properties of its colormap are changed. Therefore, an explicit
        call `.QuadContourSet.changed()` is needed after modifying the
        colormap. The explicit call can be left out, if a colorbar is
        assigned to the `.QuadContourSet` because it internally calls
        `.QuadContourSet.changed()`.

    Example::

        x = np.arange(1, 10)
        y = x.reshape(-1, 1)
        h = x * y

        cs = plt.contourf(h, levels=[10, 30, 50],
            colors=['#808080', '#A0A0A0', '#C0C0C0'], extend='both')
        cs.cmap.set_over('red')
        cs.cmap.set_under('blue')
        cs.changed()

xunits, yunits : registered units, optional
    Override axis units by specifying an instance of a
    :class:`matplotlib.units.ConversionInterface`.

antialiased : bool, optional
    Enable antialiasing, overriding the defaults.  For
    filled contours, the default is *True*.  For line contours,
    it is taken from :rc:`lines.antialiased`.

nchunk : int >= 0, optional
    If 0, no subdivision of the domain.  Specify a positive integer to
    divide the domain into subdomains of *nchunk* by *nchunk* quads.
    Chunking reduces the maximum length of polygons generated by the
    contouring algorithm which reduces the rendering workload passed
    on to the backend and also requires slightly less RAM.  It can
    however introduce rendering artifacts at chunk boundaries depending
    on the backend, the *antialiased* flag and value of *alpha*.

linewidths : float or array-like, default: :rc:`contour.linewidth`
    *Only applies to* `.contour`.

    The line width of the contour lines.

    If a number, all levels will be plotted with this linewidth.

    If a sequence, the levels in ascending order will be plotted with
    the linewidths in the order specified.

    If None, this falls back to :rc:`lines.linewidth`.

linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'}, optional
    *Only applies to* `.contour`.

    If *linestyles* is *None*, the default is 'solid' unless the lines are
    monochrome. In that case, negative contours will instead take their
    linestyle from the *negative_linestyles* argument.

    *linestyles* can also be an iterable of the above strings specifying a set
    of linestyles to be used. If this iterable is shorter than the number of
    contour levels it will be repeated as necessary.

negative_linestyles : {*None*, 'solid', 'dashed', 'dashdot', 'dotted'},                        optional
    *Only applies to* `.contour`.

    If *linestyles* is *None* and the lines are monochrome, this argument
    specifies the line style for negative contours.

    If *negative_linestyles* is *None*, the default is taken from
    :rc:`contour.negative_linestyles`.

    *negative_linestyles* can also be an iterable of the above strings
    specifying a set of linestyles to be used. If this iterable is shorter than
    the number of contour levels it will be repeated as necessary.

hatches : list[str], optional
    *Only applies to* `.contourf`.

    A list of cross hatch patterns to use on the filled areas.
    If None, no hatching will be added to the contour.
    Hatching is supported in the PostScript, PDF, SVG and Agg
    backends only.

algorithm : {'mpl2005', 'mpl2014', 'serial', 'threaded'}, optional
    Which contouring algorithm to use to calculate the contour lines and
    polygons. The algorithms are implemented in
    `ContourPy <https://github.com/contourpy/contourpy>`_, consult the
    `ContourPy documentation <https://contourpy.readthedocs.io>`_ for
    further information.

    The default is taken from :rc:`contour.algorithm`.

data : indexable object, optional
    DATA_PARAMETER_PLACEHOLDER

Notes
-----
1. `.contourf` differs from the MATLAB version in that it does not draw
   the polygon edges. To draw edges, add line contours with calls to
   `.contour`.

2. `.contourf` fills intervals that are closed at the top; that is, for
   boundaries *z1* and *z2*, the filled region is::

      z1 < Z <= z2

   except for the lowest interval, which is closed on both sides (i.e.
   it includes the lowest value).

3. `.contour` and `.contourf` use a `marching squares
   <https://en.wikipedia.org/wiki/Marching_squares>`_ algorithm to
   compute contour locations.  More information can be found in
   `ContourPy documentation <https://contourpy.readthedocs.io>`_.
)Zcontour_doc)3r   rh   numbersr   numpyr\   r   
matplotlibrg   r   r   matplotlib.backend_basesr   matplotlib.pathpathr   matplotlib.tickerrE   matplotlib.cmra   matplotlib.colorsr7   r_   Zmatplotlib.collectionsr   r7  Zmatplotlib.font_managerrV   matplotlib.textr   Zmatplotlib.cbookrk   matplotlib.patchespatchesrt  matplotlib.transforms
transformsri  r   r   r2   r3   r   r  interpdupdatededent_interpdrb   r  r  paramsr   r   r   r   <module>   sT       	$     h 5 l 