3
ƽh                @   s  d Z ddlmZ ddlZddlmZ ddlZddlj	Z
ddljZddljZddljZddljZddljZddljZddljZddljZddljZddl j!Z!ddl"j#Z$ddl%m&Z& G dd dej'Z(G dd	 d	Z)d
d Z*dd Z+dd Z,G dd dej-e)Z.G dd de.Z/dS )zG
Classes to support contour plotting and labelling for the Axes class.
    )IntegralN)ma)BlockingContourLabelerc               @   s   e Zd ZdZdd Zd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             C   s&   | j  jtjj| g| j g\}|S )N)get_transformtransform_anglestextTextget_rotationget_position)selfZ	new_angle r   8/tmp/pip-build-7iwl8md4/matplotlib/matplotlib/contour.pyr
   *   s    zClabelText.get_rotationN)__name__
__module____qualname____doc__r
   r   r   r   r   r   #   s   r   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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 )0ContourLabelerz7Mixin to provide labelling capability to `.ContourSet`.NT   z%1.3fF)	fontsizeinlineinline_spacingfmtcolorsuse_clabeltextmanualrightside_upzorderc   	         C   s  || _ || _|| _|	| _|
dkr.d| j | _n|
| _|dkrV| j}ttt	| j
}nlt|}g g  }}x2t| jD ]$\}}||krt|j| |j| qtW t	|t	|k rtd| d| j || _|| _tj | _| jj| | jj }|gt	| | _|dkr"| | _tj| j
| j| _n<tj|t	| jd}ttt	| j| _tj|tj d| _g | _tj | jrxl| jD ]\}}| j!|||| qzW nF| jrt"d t"d |st"d	 t#| }||| n| j$|| t%j&d
| j'| _(| j(S )aK  
        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 : str or dict, default: '%1.3f'
            A format string for the label.

            Alternatively, this can be a dictionary matching contour levels
            with arbitrary strings to use for each contour level (i.e.,
            fmt[level]=string), or it can be any callable, such as a
            `.Formatter` instance, that returns a string when called with a
            numeric contour level.

        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.
        N   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.z	text.Text))labelFmt_use_clabeltextZlabelManualr   _contour_zorder_clabel_zorderlevelslistrangelencvalues	enumerateappend
ValueErrorlabelLevelListlabelIndiceListfont_managerZFontPropertieslabelFontPropsZset_sizeZget_size_in_pointslabelFontSizeListlabelMappablenpZtakelabelCValueListmcolorsListedColormapcmScalarMappableNoNormlabelXYsiterableadd_label_nearprintr   labelscbooksilent_list
labelTextsZlabelTextsList)r   r&   r   r   r   r   r   r   r   r   r   indicesZlevlabsilevZfont_size_ptsr    xyZblocking_contour_labelerr   r   r   clabel3   sZ    ^




zContourLabeler.clabelc             C   s*   t |d| kp(tj|ddd| kj S )z8Return whether a contour is long enough to hold a label.
   r   )axisg333333?)r)   r4   Zptpany)r   linecontour
labelwidthr   r   r   print_label   s    zContourLabeler.print_labelc                s(   d| d  t  fdd| jD S )z7Return *True* if a label is already near this location.g333333?r   c             3   s2   | ]*}|d   d |d  d   k V  qdS )r   r      Nr   ).0loc)threshrF   rG   r   r   	<genexpr>   s   z+ContourLabeler.too_close.<locals>.<genexpr>)rK   r;   )r   rF   rG   lwr   )rR   rF   rG   r   	too_close   s    zContourLabeler.too_closec             C   s   t |d }tj|}x>|D ]6}|| | || |  }	}
| j|	|
|rJq|	|
|fS W |d }|| | || |  }	}
|	|
|fS )a  
        Return x, y, and the index of a label location.

        Labels are plotted at a location with the smallest
        deviation of the contour from a straight line
        unless there is another label nearby, in which case
        the next best place on the contour is picked up.
        If all such candidates are rejected, the beginning
        of the contour is chosen.
        r   r   )intr4   ZargsortrU   )r   Z	distancesXXYYysizerT   ZhysizeZadistindrF   rG   r   r   r   get_label_coords   s    

zContourLabeler.get_label_coordsc             C   s   t |ts| j||}tj j|\}}|dkrHtj j||\}}}nR|rt	| dsbt
jd| _| jj|d| jd\}}tj|\}}nt|| d }|S )z:
        Return the width of the label in points.
        ZTeX_mathtext_parserZbitmapH   )dpipropg333333?)
isinstancestrget_textr   r	   Z_preprocess_math
texmanagerZ
TexManagerZget_text_width_height_descenthasattrmathtextZMathTextParserr\   parser1   r4   shaper)   )r   rE   r   fsizeZismathrT   _imgr   r   r   get_label_width   s    


zContourLabeler.get_label_widthc             C   s2   |j | |j| |j| j |j| jj dS )z1Set the label properties - color, fontsize, text.N)Zset_text	set_colorZset_fontpropertiesr1   Zset_clip_boxaxesZbbox)r   labelr   colorr   r   r   set_label_props  s    

zContourLabeler.set_label_propsc             C   s@   t |tr|S t |tr$|j|dS t|r4||S || S dS )zGet the text of the label.z%1.3fN)r`   ra   dictgetcallable)r   rE   r   r   r   r   rb   
  s    

zContourLabeler.get_textc             C   sj  t |}|dkr$ttj|| }nd}|dkr6|}nt|}tj|dddf ||f}tj|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j||
 |	| }tjddd tjtj|| dd}W dQ R X | j	|||||\}}}dd |D }|j
||f}|||fS )zX
        Find good place to draw a label (relatively flat part of the contour).
        rO   Nr   ignore)divideinvalid)rJ   c             S   s   g | ]}t |qS r   )tuple)rP   lr   r   r   
<listcomp>5  s    z/ContourLabeler.locate_label.<locals>.<listcomp>rz   rz   )r)   rV   r4   ceilresizehypotZerrstatesumabsr[   index)r   rL   rM   ZnsizeZxsizerY   rW   rX   ZyfirstZylastZxfirstZxlastsLdistrF   rG   rZ   lcZdindr   r   r   locate_label  s*     "zContourLabeler.locate_labelc                s  |dkrg }|d }t |}|rptj||d |d|d  g}t|rltj||d |d|d  g}d}tj|jd tdtj|dd}tjtj	|dddf |dddf dd< |  tj
| |g|rtj
d dg n
tj  fdd|jD \\}\}	tjtj|	|}
| jrL|
d	 d
 d	 }
g }t|r  tj
| |g tjtjtddd}tj|d jttj|d j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|jtj|||d |d d  |g n`|d dkrx|jtj|d|d d  |g |d dkr|jtj|||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       @rO   r   )dtype)rJ   c             3   s&   | ]}t jt j  |V  qd S )N)r4   diffinterp)rP   Zslc_col)dpplxir   r   rS   j  s   z;ContourLabeler.calc_label_rot_and_inline.<locals>.<genexpr>Z      )leftrightc                s   g | ]}t jd   |qS )r   )r4   r   )rP   lc_col)r   r   r   r   ry   }  s    z<ContourLabeler.calc_label_rot_and_inline.<locals>.<listcomp>c                s   g | ]}t jd   |qS )rO   )r4   r   )rP   r   )r   r   r   r   ry     s    c             s   s   | ]}|dkV  qdS )rO   Nrz   r   )rP   rD   r   r   r   rS     s    rz   rz   rz   rz   rz   rz   rz   rz   rz   )_is_closed_polygonr4   concatenater)   zerosrg   floatr   Zcumsumr}   arrayZ
zeros_likeTZrad2degZarctan2r   r   arangefloorastyperV   r{   allr,   	row_stack)r   slcrZ   rT   r   spacingZhlwcloseddxdyrotationnlcIZxy1Zxy2r   )r   r   r   r   calc_label_rot_and_inline:  sN    ""2

(,$ z(ContourLabeler.calc_label_rot_and_inlinec             C   s6   | j jj j||f\}}tj|||dd| jd}|S )Ncenter)r   horizontalalignmentverticalalignmentr   )rm   	transDatainverted	transformr   r	   r%   )r   rF   rG   r   r   r   tr   r   r   _get_label_text  s
    
zContourLabeler._get_label_textc       	      C   s\   | j jj }|j||f\}}|jtj|gtj||gg}t|||d dd| jd}|S )Nr   r   )r   r   r   r   )	rm   r   r   r   r   r4   r   r   r%   )	r   rF   rG   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j| | jj| | j	j||f | j
j| d S )N)alpha)r3   to_rgbar   rb   r"   rp   rB   r,   labelCValuesr;   rm   Z
add_artist)r   r   rF   rG   rE   cvaluero   Z_textr   r   r   
_add_label  s    zContourLabeler._add_labelc             C   s$   | j |||}| j||||| dS )zO
        Add contour label using :class:`~matplotlib.text.Text` class.
        N)r   r   )r   rF   rG   r   rE   r   r   r   r   r   	add_label  s    zContourLabeler.add_labelc             C   s$   | j |||}| j||||| dS )zD
        Add contour label using :class:`ClabelText` class.
        N)r   r   )r   rF   rG   r   rE   r   r   r   r   r   add_label_clabeltext  s    z#ContourLabeler.add_label_clabeltextc             C   s  |dkr| j j}|r&|j||f\}}| j||| jdd \}}}}	}
| j| j }|| }|j}| j jj j|	|
g}t	j
||| st	j|d| |||d g}tj|||< | jj|}| j| j }|| j}| j jj|}| j| j| | j| j| }|| j jjd 9 }| j||||r,|nd|\}}| j|	|
|| j| | j|  |r|j| x,|D ]$}t|dkrl|jtj| qlW dS )a  
        Add a label near the point (x, y). If transform is None
        (default), (x, y) is in data coordinates; if transform is
        False, (x, y) is in display coordinates; otherwise, the
        specified transform will be used to translate (x, y) into
        display coordinates.

        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.
        Nr   r]   rO   )rm   r   r   find_nearest_contourr/   collections	get_pathsverticesr   r4   allcloser   mpathPathr   rk   r.   r"   r2   figurer^   r   r   r5   popr)   r,   )r   rF   rG   r   r   r   conminsegminiminxminyminpathsZactive_pathr   xcminZlminr   rT   r   r   nr   r   r   r=     s:     


zContourLabeler.add_label_nearrO   c             C   s$   | j j| | jj|}|j  dS )z>Defaults to removing last label, but any index can be suppliedN)r   r   rB   remove)r   r   r   r   r   r   	pop_label  s    zContourLabeler.pop_labelc             C   sl  | j r| j}n| j}xPt| j| j| j| jD ]4\}}}}| j| }|j	 }	| j
|| j|}
|
| jjjd 9 }
g }|j }xt|D ]\}}|j}|	j|}t|rtj||dd g}n|}| j||
rF| j||
\}}}| j|||
|r|nd |\}}|||||| |rPx8|D ]$}t|dkr|jtj| qW q|j| qW |r.||d d < q.W d S )Nr]   rO   r   )r#   r   r   zipr/   r.   r2   r5   r   r   rk   r"   rm   r   r^   r   r+   r   r   r   r4   r   rN   r   r   r)   r,   r   r   )r   r   r   r   iconrE   rh   r   contransrT   Z	additionsr   segNumlinepathr   Zslc0r   rF   rG   rZ   r   newr   r   r   r   r?   "  s<    


zContourLabeler.labels)N)Nr   )Tr   Nrz   )rz   )r   r   r   r   rH   rN   rU   r[   rk   rp   rb   r   r   r   r   r   r   r   r=   r   r?   r   r   r   r   r   0   s.    $
Z 
S
r   c             C   s   t j|| kr(t j||  d }|| fS ||  }||  }t j||t j|| }|dk r\d}|dkrhd}| ||  }t j|| d }||fS )zBFind the closest point to p0 on line segment connecting p1 and p2.r   r   rO   )r4   r   r~   dot)p1p2Zp0dZd21Zd01projZpcr   r   r   _find_closest_point_on_legY  s    r   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   rO   g|=gvIh%<=)ZrtolZatolrz   )r4   r   )Xr   r   r   r   r  s    r   c             C   s   t j| |dddf  d d}t j|}t j}d}d}t| }g }|dksP|rj|j|d t|  |f |t| d k s~|r|j||d t|  f x@|D ]8}	t| |	d  | |	d  |\}
}|
|k r|
}|}|	}qW |||fS )zj
    Parameters
    ----------
    lc : coordinates of vertices
    point : coordinates of test point
    Nr   rO   r   )NN)r4   r~   Zargmininfr   r,   r)   r   )r   pointZdsr   dminr   Zlegminr   Zlegslegr   xcr   r   r   _find_closest_point_on_path{  s$    	 

 r   c               @   s   e Zd ZdZddddd0ddddddddddddddddZejd	e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d1d.d/ZdS )2
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`.

    Attributes
    ----------
    ax
        The axes object in which the contours are drawn.

    collections
        A silent_list of LineCollections or PolyCollections.

    levels
        Contour levels.

    layers
        Same as levels for line contours; half-way between
        levels for filled contours.  See :meth:`_process_colors`.
    NFZneitherr   )r&   filled
linewidths
linestyleshatchesr   originextentr    r   r!   vminvmaxextendantialiasednchunklocatorr   c      +   
   O   s  || _ || _|| _|| _|| _|| _|| _|| _|	| _|| _	|| _
|| _| jdkr^| jr^d| _|| _|| _t|tjst| jtjrd| _|dkrtj }nd| _tjddddg|d | jdk	rt| jdkrtd	| j	dk	r|
dk	rtd
| jdkr
tjd | _|| _| j||}| j  | j	dk	rt| j}| jrJ|d8 }d}| j
d!k}| j
d"k}d}|t| t| }t| j	|kr|s|rd}|rd}tj| j	|d |d}
|r|r|
j| j	d  |r|
j | j	d#  | jrtj!d| _"ntj!d| _"g | _#g | _$d|
i}|dk	r6||d< t%j&j'| f| |dk	rX|| j(_)|dk	rj|| j(_*| j+  | j, \| _-| _.| jrJ| jdk	rtj/d | j0 \}}| j.dkrdgt| j- | _.|j1dd| _2xnt3||| j-| j.D ]X\}} }!}"| j4|!|"}#t5j6|#| jfd| j| j7 | j2d}$| j j8|$dd | j"j9|$ qW n| j: }%|%| _;| j< }&| j}'|'dk	rx| jf}'|j1dd| _2xlt3| j|%|&| j-D ]V\}}(})}!t5j=|!|'|(|)g| j| j7 | j2d}$|$j>d | j j8|$dd | j"j9|$ qW xP| j"D ]F}$| j?d | j@d g|$jAjBdd< | j?d | j@d g|$jAjCdd< qW | j jD| j?| j@g | j jEdd | jF  |rdjGtHtI|}*tj/d |*  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lowerupperimage)r      z3If given, 'extent' must be None or (x0, x1, y0, y1)z"Either colors or cmap must be Nonezimage.originrO   r   minbothmax)r   zmcoll.PathCollectionzmcoll.LineCollectionr    r!   z!linewidths is ignored by contourfr   none)antialiasedsZ
edgecolorsr   r   r   )Zautolimr   )r   r   r   r   r   r   Z
_nolegend_)Ztightz, z/The following kwargs were not used by contour: )r   r   )r   r   rz   )Jrm   r&   r   r   r   r   r   r   r   r   r   r   r   r   r`   r6   ZLogNormticker
LogLocatorlogscaler@   Z_check_in_listr)   r-   mplrcParams
_transform_process_args_process_levelsrV   r7   Z	set_underZset_overrA   r   rB   r   r8   r9   __init__r!   r   r   _process_colors_get_allsegs_and_allkindsallsegsallkinds_warn_external_get_lowers_and_uppersr   r$   r   _make_pathsmcollZPathCollectionr   Zadd_collectionr,   _process_linewidthstlinewidths_process_linestylesLineCollectionZ	set_label_mins_maxsZsticky_edgesrF   rG   Zupdate_datalimZautoscale_viewchangedjoinmaprepr)+r   axr&   r   r   r   r   r   r   r   r    r   r!   r   r   r   r   r   r   r   argskwargsZncolorsi0Z
extend_minZ
extend_maxZuse_set_under_overZtotal_levelskwlowersupperslevellevel_uppersegskindsr   colr  tlinestylesZaawidthZlstyler   r   r   r   r     s    3











 &zContourSet.__init__z3.3c             C   s   | j S )N)rm   )r   r   r   r   r    s    zContourSet.axc             C   sH   | j dkr| jj| _ n,t| j tj rBt| j drB| j j| j| _ | j S )zp
        Return the :class:`~matplotlib.transforms.Transform`
        instance used by this ContourSet.
        N_as_mpl_transform)r   rm   r   r`   mtransformsZ	Transformrd   r  )r   r   r   r   r     s    
zContourSet.get_transformc             C   s   | j j }d |d< |S )N_contour_generator)__dict__copy)r   stater   r   r   __getstate__  s    
zContourSet.__getstate__rF   c          	   C   sl  g }g }| j r| j \}}t| j}xtt| j||D ]\}\}	}
}tjddd|	j d |	j	 |	j
 d}|j| ||
}
||}|dkr| jdkr|jd| d|
 d q:||d kr| jdkr|jd| d
| d q:|jd|
 d| d| d q:W n\xZt| j| jD ]H\}	}tjd}|j|	 |j| ||}|jd| d| d qW ||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   rO   )Z	facecolorhatchr   r   r   $z \leq zs$r   z > z < Nz = )r   r   )r   r   )r   r   )r   r   r)   r   r+   r   mpatchesZ	RectangleZget_facecolorZ	get_hatch	get_alphar,   r   r&   r  r  Zupdate_from)r   Zvariable_nameZ
str_formatZartistsr?   r  r  Zn_levelsrD   
collectionr   r   patchr  r   r   r   legend_elements  s6    


$


zContourSet.legend_elementsc             O   s   |d | _ |d | _t|dkr(|d nd| _tj| j | _tj| j | _| j	rrt| jt| j d krt
dnt| jt| j krt
d| jdk	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   rO   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   )rP   segr   r   r   r   ry     s    z,ContourSet._process_args.<locals>.<listcomp>)rJ   )r&   r   r)   r   r4   r   zmaxr   zminr   r-   r   r  r  )r   r  r  ZflatseglistZpointsr   r   r   r     s$    



zContourSet._process_argsc             C   s   | j | jfS )zv
        Override in derived classes to create and return allsegs and allkinds.
        allkinds can be None.
        )r   r   )r   r   r   r   r     s    z$ContourSet._get_allsegs_and_allkindsc             C   s`   | j dd }| j|d krJ|j }| jr:d| j |d< n|d  d8  < | j dd }||fS )zB
        Return ``(lowers, uppers)`` for filled contours.
        NrO   r   gGz?rz   )_levelsr+  r  r   )r   r  r  r   r   r   r   $  s    z!ContourSet._get_lowers_and_uppersc             C   s.   |d k	rdd t ||D S dd |D S d S )Nc             S   s   g | ]\}}t j||d qS ))codes)r   r   )rP   r)  kindr   r   r   ry   5  s   z*ContourSet._make_paths.<locals>.<listcomp>c             S   s   g | ]}t j|qS r   )r   r   )rP   r)  r   r   r   ry   8  s    )r   )r   r  r  r   r   r   r  3  s    zContourSet._make_pathsc             C   s   dd | j | j| jdD }|| _| jt| }xBt||| jD ]0\}}}| jrf|j	| |j
| q@|j| q@W x8t| j| jD ]&\}}|j| j |j| jj | qW tjj|  d S )Nc             S   s   g | ]}t |fqS r   )rw   )rP   Zrgbar   r   r   ry   ;  s   z&ContourSet.changed.<locals>.<listcomp>)r   )r   r*   r   tcolorsr   r)   r   r   r   Zset_facecolorZ	set_hatchrl   rB   r   	set_alphar3   r8   r9   r	  )r   r/  r   ro   r"  r&  rn   Zcvr   r   r   r	  :  s    
zContourSet.changedc             C   s  | j dkr0| jrtj | _ ntj|d dd| _ | j j| j| j}y| j jrP|S W n t	k
rf   Y nX t
j|| jk d }t|r|d	 nd}t
j|| jkd }t|r|d d nt|}| jd
kr|d7 }| jdk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.
        NrO   )Zmin_n_ticksr   r   r   r      rz   )r   r   )r   r   )r   r   r   r   ZMaxNLocatorZtick_valuesr+  r*  Z
_symmetricAttributeErrorr4   Znonzeror)   r   )r   r   rE   Zunderr  Zoveri1r   r   r   _autolevM  s*    


zContourSet._autolevc             C   s   | j dkr&t|dkrd}q,|d }n| j }t|trD| j|| _ ntj|jtj| _ | j	s| j | j
k| j | jk @ }| j | }t|dkr| j
g| _ tjd | j	rt| j dk rtdt| j dkrtjtj| 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.rO   g        z!Contour levels must be increasing)r&   r)   r`   r   r4  r4   asarrayr   float64r   r+  r*  r@   r   r-   r   r   )r   r  Z
levels_argZinsideZ	levels_inr   r   r   _process_contour_level_argsx  s&    




$z&ContourSet._process_contour_level_argsc             C   s   t | j| _| jrd
\}}nd\}}| jdkr<| jjd| | jdkrR| jj| tj| j| _| j	sr| j| _
dS | jrtj| jdd tj| 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.
        L]?RyXsr   r   r   r   NrO   g      ?)r9  r:  RyX)r;  r:  )r   r   )r   r   rz   rz   )r'   r&   r,  r   r   insertr,   r4   r6  r   layerssqrt)r   r   r   r   r   r   r     s     


zContourSet._process_levelsc             C   s   | j j| _| jdk	rvdt| j }}| jrV|d8 }| jdkrD|d8 }| jd	krV|d7 }tt||| _	| j
tj  n| j| _	| j| j | j  | jd
krd| j_dS )a  
        Color argument processing for contouring.

        Note that we base the color mapping 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   rO   r   r   r   F)r   r   )r   r   )r   r   r   )r    
monochromer   r)   r&   r   r   r'   r(   r*   Zset_normr6   r:   r=  Z	set_arrayZautoscale_Noner!   Zclip)r   r  r3  r   r   r   r     s     




zContourSet._process_colorsc             C   s   | j }t| j}|d krBtjd }|d kr4tjd }|fg| }nntj|sX|g| }nJt|}t||k rttj	|t| }|| }t||kr|d | }dd |D }|S )Nzcontour.linewidthzlines.linewidthc             S   s   g | ]
}|fqS r   r   )rP   wr   r   r   ry     s    z2ContourSet._process_linewidths.<locals>.<listcomp>)
r   r)   r&   r   r   r4   r<   r'   rV   r{   )r   r   NlevZdefault_linewidthr  nrepsr   r   r   r    s"    



zContourSet._process_linewidthsc       	      C   s   | j }t| j}|d krndg| }| jrtjd }| j| j  d }xt| jD ]\}}||k rP|||< qPW ntt	|t
r|g| }n^tj|rt|}t||k rttj|t| }|| }t||kr|d | }ntd|S )NZsolidzcontour.negative_linestylegV瞯<z&Unrecognized type for linestyles kwarg)r   r)   r&   r?  r   r   r*  r+  r+   r`   ra   r4   r<   r'   rV   r{   r-   )	r   r   rA  r  Zneg_lsepsrD   rE   rB  r   r   r   r    s*    




zContourSet._process_linestylesc             C   s   | j S )z5Return alpha to be applied to all ContourSet artists.)r   )r   r   r   r   r%    s    zContourSet.get_alphac             C   s   || _ | j  dS )z
        Set the alpha blending value for all ContourSet artists.
        *alpha* must be between 0 (transparent) and 1 (opaque).
        N)r   r	  )r   r   r   r   r   r0    s    zContourSet.set_alphaTc             C   s   |dkrt tt| j}tj}d}d}d}d}	tj||g}
x|D ]}| j| }|j }|j	 }xdt
|D ]X\}}|j}|r|j|}t||
\}}}||k rl|}|}|}|d }|d }|d }	qlW qDW |||||	|fS )a;  
        Find the point in the contour plot that is closest to ``(x, y)``.

        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)``.
        d : float
            The distance from ``(xmin, ymin)`` to ``(x, y)``.
        NrO   r   )r'   r(   r)   r&   r4   r   r   r   r   r   r+   r   r   r   )r   rF   rG   rC   Zpixelr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   "  s2    (


zContourSet.find_nearest_contour)N)NT)r   r   r   r   r   r@   Z
deprecatedpropertyr  r   r!  ra   r(  r   r   r   r  r	  r4  r8  r   r   r  r  r%  r0  r   r   r   r   r   r     s4   6
 I?"+%-r   c               @   sB   e Zd ZdZddddZdd Zdd	 Zd
d Zdd ZdZ	dS )QuadContourSeta  
    Create and store a set of contour lines or filled regions.

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

    Attributes
    ----------
    ax
        The axes object in which the contours are drawn.

    collections
        A silent_list of LineCollections or PolyCollections.

    levels
        Contour levels.

    layers
        Same as levels for line contours; half-way between
        levels for filled contours. See :meth:`_process_colors` method.
    N)corner_maskc            O   sz  t |d trn| jdkr$|d j| _|d j| _|d j| _|d j| _|d j}|d j| _|d j| _nddl	j
}|dkrtjd }|| _| j||\}}}tj|}	|	tjks|	j  rd}	|j|||j |	| j| j}| j }
|
| jjkrDt|
j| jjrD|
| jj }tj|j|jgj}|j|}|d }|d }tj|tj|g| _tj|tj|g| _|| _|S )z*
        Process args and kwargs.
        r   Nzcontour.corner_mask.rO   ).r   ).rO   ) r`   rE  r&   r+  r*  Z_corner_maskr  r  r  Zmatplotlib._contour_contourr   r   _contour_argsr   ZgetmaskZnomaskrK   ZQuadContourGeneratorr   r   r   rm   r   Zcontains_branch_seperatelyr4   ZvstackZflatr   r   r   r   )r   rF  r  r  Zcontour_generatorrG  rF   rG   zZ_maskr   Ztrans_to_dataZptsZtransformed_ptsr   r   r   r     s>    





zQuadContourSet._process_argsc       	      C   s   g }| j rZ| j \}}g }xht||D ].\}}| jj||\}}|j| |j| q&W n*d}x$| jD ]}| jj|}|j| qfW ||fS )z7Compute ``allsegs`` and ``allkinds`` using C extension.N)r   r   r   r  Zcreate_filled_contourr,   r&   Zcreate_contour)	r   r   r  r  r   r  r  r   r  r   r   r   r     s    
z(QuadContourSet._get_allsegs_and_allkindsc             C   s  | j rd}nd}t|}|dkrPtj|d tjd}| j|\}}|dd  }n@|dkr| j|d d |\}}}|dd  }ntd	||f tj	|d
d}t
|j | _t
|j | _| jr| jdkrtj|dk|}tjd t
|j | _| j| |||fS )NZcontourfZcontourr   r   )r   rO   r   r1  z&Too many arguments to %s; see help(%s)F)r  z,Log scale: values of z <= 0 have been masked)r   r)   r   r6  r4   r7  _initialize_x_y
_check_xyz	TypeErrorZmasked_invalidr   r   r*  r   r+  r   Zmasked_wherer@   r   r8  )r   r  r  fnZNargsrI  rF   rG   r   r   r   rH    s,    

zQuadContourSet._contour_argsc       
      C   s  |dd \}}| j j|||d}| j j|}| j j|}tj|tjd}tj|tjd}tj|d tjd}|jdkrt	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rT|j
\}|j
\}	||kr"t	d| d| d|	|krBt	d|	 d| dtj||\}}np|jdkr|j
|j
krt	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   )ZxdataZydatar  )r   zInput z must be 2D, not Dr   rO   z>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 )rm   Z_process_unit_infoZconvert_xunitsZconvert_yunitsr4   r6  r7  r   ndimrL  rg   meshgrid)
r   r  r  rF   rG   rI  NyNxZnxnyr   r   r   rK    s>    



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kr| jdkrtjtj|tj|S | j\}}}}tj|||}tj|||}	tj||	S | jdkrd|d|f\}}}}n| j\}}}}|| | }
|| | }|tj|d |
  }|tj|d |  }	| jd	krD|	ddd
 }	tj||	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   zInput z must be 2D, not rN  r   rO   z>Input z must be at least a (2, 2) shaped array, but has shape Ng      ?r   rz   )	rP  rL  rg   r   r   r4   rQ  r   Zlinspace)r   rI  rR  rS  Zx0x1Zy0y1rF   rG   r   r   r   r   r   rJ    s,    




zQuadContourSet._initialize_x_ya:$  
        Plot contours.

        Call signature::

            contour([X, Y,] Z, [levels], **kwargs)

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

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

        Z : array-like(N, M)
            The height values over which the contour is drawn.

        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 : str or `.Colormap`, default: :rc:`image.cmap`
            A `.Colormap` instance or registered colormap name. The colormap
            maps the level values to colors.

            If both *colors* and *cmap* are given, an error is raised.

        norm : `~matplotlib.colors.Normalize`, optional
            If a colormap is used, the `.Normalize` instance scales the level
            values to the canonical colormap range [0, 1] for mapping to
            colors. If not given, the default linear scaling is used.

        vmin, vmax : float, optional
            If not *None*, either or both of these values will be supplied to
            the `.Normalize` instance, overriding the default color scaling
            based on *levels*.

        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 take their
            linestyle from :rc:`contour.negative_linestyle` setting.

            *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.

        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).
        )
r   r   r   r   r   r   rH  rK  rJ  Z_contour_docr   r   r   r   rE  l  s   0. {rE  )0r   numbersr   numpyr4   r   Z
matplotlibr   Zmatplotlib.pathpathr   Zmatplotlib.tickerr   Zmatplotlib.cmr8   Zmatplotlib.colorsr   r6   Zmatplotlib.collectionsr   r  Zmatplotlib.font_managerr0   Zmatplotlib.textr   Zmatplotlib.cbookr@   Zmatplotlib.mathtextre   Zmatplotlib.patchesZpatchesr$  Zmatplotlib.texmanagerrc   Zmatplotlib.transformsZ
transformsr  Zmatplotlib.blocking_inputr   r	   r   r   r   r   r   r9   r   rE  r   r   r   r   <module>   sB   












    -	#     S