3
ƽhl                @   s  d Z ddlmZ ddlZddlmZ ddlZddlZ	ddl
mZmZmZ ddlmZ ddlmZmZmZ dd	lmZ G d
d dZG dd dZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZ G d d! d!eZ!G d"d# d#e!Z"G d$d% d%Z#G d&d' d'e!Z$G d(d) d)e$Z%G d*d+ d+e!Z&G d,d- d-e!Z'G d.d/ d/eZ(dS )0a  
GUI neutral widgets
===================

Widgets that are designed to work for any of the GUI backends.
All of these widgets require you to predefine a `matplotlib.axes.Axes`
instance and pass that as the first parameter.  Matplotlib doesn't try to
be too smart with respect to layout -- you will have to figure out how
wide and tall you want your Axes to be to accommodate your widget.
    )	ExitStackN)Integral   )cbookcolorsticker)Line2D)Circle	RectangleEllipse)blended_transform_factoryc               @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )LockDrawa  
    Some widgets, like the cursor, draw onto the canvas, and this is not
    desirable under all circumstances, like when the toolbar is in zoom-to-rect
    mode and drawing a rectangle.  To avoid this, a widget can acquire a
    canvas' lock with ``canvas.widgetlock(widget)`` before drawing on the
    canvas; this will prevent other widgets from doing so at the same time (if
    they also try to acquire the lock first).
    c             C   s
   d | _ d S )N)_owner)self r   8/tmp/pip-build-7iwl8md4/matplotlib/matplotlib/widgets.py__init__#   s    zLockDraw.__init__c             C   s   | j |std|| _dS )zReserve the lock for *o*.zalready lockedN)	available
ValueErrorr   )r   or   r   r   __call__&   s    
zLockDraw.__call__c             C   s   | j |stdd| _dS )zRelease the lock from *o*.zyou do not own this lockN)r   r   r   )r   r   r   r   r   release,   s    
zLockDraw.releasec             C   s   | j   p| j|S )z+Return whether drawing is available to *o*.)lockedisowner)r   r   r   r   r   r   2   s    zLockDraw.availablec             C   s
   | j |kS )z"Return whether *o* owns this lock.)r   )r   r   r   r   r   r   6   s    zLockDraw.isownerc             C   s
   | j dk	S )z6Return whether the lock is currently held by an owner.N)r   )r   r   r   r   r   :   s    zLockDraw.lockedN)
__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   r   r   r      s   r   c               @   sB   e Zd ZdZdZdZdZdd Zdd Ze	eeddZ
d	d
 ZdS )Widgetz5
    Abstract base class for GUI neutral widgets
    Tc             C   s
   || _ dS )z!Set whether the widget is active.N)_active)r   activer   r   r   
set_activeG   s    zWidget.set_activec             C   s   | j S )z!Get whether the widget is active.)r   )r   r   r   r   
get_activeK   s    zWidget.get_activezIs the widget active?)docc             C   s   | j  S )z
        Return whether *event* should be ignored.

        This method should be called at the beginning of any event callback.
        )r    )r   eventr   r   r   ignoreR   s    zWidget.ignoreN)r   r   r   r   drawoneventsonr   r!   r"   propertyr    r%   r   r   r   r   r   ?   s   r   c               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	
AxesWidgeta  
    Widget connected to a single `~matplotlib.axes.Axes`.

    To guarantee that the widget remains responsive and not garbage-collected,
    a reference to the object should be maintained by the user.

    This is necessary because the callback registry
    maintains only weak-refs to the functions, which are member
    functions of the widget.  If there are no references to the widget
    object it may be garbage collected which will disconnect the callbacks.

    Attributes
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent axes for the widget.
    canvas : `~matplotlib.backend_bases.FigureCanvasBase`
        The parent figure canvas for the widget.
    active : bool
        If False, the widget does not respond to events.
    c             C   s   || _ |jj| _g | _d S )N)axfigurecanvascids)r   r*   r   r   r   r   p   s    
zAxesWidget.__init__c             C   s   | j j||}| jj| dS )z
        Connect callback with an event.

        This should be used in lieu of ``figure.canvas.mpl_connect`` since this
        function stores callback ids for later clean up.
        N)r,   mpl_connectr-   append)r   r$   callbackcidr   r   r   connect_eventu   s    zAxesWidget.connect_eventc             C   s    x| j D ]}| jj| qW dS )z-Disconnect all events created by this widget.N)r-   r,   mpl_disconnect)r   cr   r   r   disconnect_events   s    zAxesWidget.disconnect_eventsN)r   r   r   r   r   r2   r5   r   r   r   r   r)   [   s   
r)   c               @   sB   e Zd ZdZdddZdd Zd	d
 Zdd Zdd Zdd Z	dS )Buttona  
    A GUI neutral button.

    For the button to remain responsive you must keep a reference to it.
    Call `.on_clicked` to connect to the button.

    Attributes
    ----------
    ax
        The `matplotlib.axes.Axes` the button renders into.
    label
        A `matplotlib.text.Text` instance.
    color
        The color of the button when not hovering.
    hovercolor
        The color of the button when hovering.
    N0.850.95c             C   s   t j| | |dk	r|j| |jdd|dd|jd| _d| _i | _| jd| j	 | jd| j
 | jd| j |jd	 |j| |jg  |jg  || _|| _dS )
a-  
        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            The `~.axes.Axes` instance the button will be placed into.
        label : str
            The button text.
        image : array-like or PIL Image
            The image to place in the button, if not *None*.  The parameter is
            directly forwarded to `~matplotlib.axes.Axes.imshow`.
        color : color
            The color of the button when not activated.
        hovercolor : color
            The color of the button when the mouse is over it.
        Ng      ?center)verticalalignmenthorizontalalignment	transformr   button_press_eventbutton_release_eventmotion_notify_eventF)r)   r   Zimshowtext	transAxeslabelcnt	observersr2   _click_release_motionset_navigateset_facecolor
set_xticks
set_ytickscolor
hovercolor)r   r*   rB   imagerL   rM   r   r   r   r      s$    





zButton.__init__c             C   sB   | j |s|j| jks| j r"d S |jj| jkr>|jj| j d S )N)r%   inaxesr*   r'   r,   mouse_grabber
grab_mouse)r   r$   r   r   r   rE      s    
zButton._clickc             C   sf   | j |s|jj| jkrd S |jj| j | j s>|j| jkrBd S x| jj D ]\}}|| qNW d S )N)	r%   r,   rP   r*   release_mouser'   rO   rD   items)r   r$   r1   funcr   r   r   rF      s    
zButton._releasec             C   s\   | j |rd S |j| jkr | jn| j}tj|| jj sX| jj| | j	rX| jj
jj  d S )N)r%   rO   r*   rM   rL   r   
same_colorget_facecolorrI   r&   r+   r,   draw)r   r$   r4   r   r   r   rG      s    
zButton._motionc             C   s"   | j }|| j|< |  j d7  _ |S )z
        Connect the callback function *func* to button click events.

        Returns a connection id, which can be used to disconnect the callback.
        r   )rC   rD   )r   rT   r1   r   r   r   
on_clicked   s    
zButton.on_clickedc             C   s&   y| j |= W n tk
r    Y nX dS )z6Remove the callback function with connection id *cid*.N)rD   KeyError)r   r1   r   r   r   
disconnect   s    zButton.disconnect)Nr7   r8   )
r   r   r   r   r   rE   rF   rG   rX   rZ   r   r   r   r   r6      s    
&	r6   c            	   @   sR   e Zd ZdZ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S )SlideraB  
    A slider representing a floating point range.

    Create a slider from *valmin* to *valmax* in axes *ax*. For the slider to
    remain responsive you must maintain a reference to it. Call
    :meth:`on_changed` to connect to the slider event.

    Attributes
    ----------
    val : float
        Slider value.
          ?NT
horizontalc             K   s  |j dkrtdtj| | |	dk	rDt|	d rDtdjt|	|
dk	rjt|
d rjtdjt|
|dkrtd	j||| _|| _|| _	|	| _
|
| _d
| _|| _|| _|| _| j|}|dkr|}|| _|| _|dkr|j||ddf|| _|j|ddddd| _n,|j||ddf|| _|j|ddddd| _|dkr\|j||f |j}n|j||f |j}|| _|j | _ t!| j t"j#st"j# | _ | j j$| | j j%d
 | j j&d |j'g  |j(g  |j)d
 | j*d| j+ | j*d| j+ |r| j*d| j+ |dkrR|j,dd||j-ddd| _.|j,dd| j/||j-ddd| _0n:|j,dd||j-ddd| _.|j,dd| j/||j-ddd| _0d| _1i | _2| j3| dS )a  
        Parameters
        ----------
        ax : Axes
            The Axes to put the slider in.

        label : str
            Slider label.

        valmin : float
            The minimum value of the slider.

        valmax : float
            The maximum value of the slider.

        valinit : float, default: 0.5
            The slider initial position.

        valfmt : str, default: None
            %-format string used to format the slider value.  If None, a
            `.ScalarFormatter` is used instead.

        closedmin : bool, default: True
            Whether the slider interval is closed on the bottom.

        closedmax : bool, default: True
            Whether the slider interval is closed on the top.

        slidermin : Slider, default: None
            Do not allow the current slider to have a value less than
            the value of the Slider *slidermin*.

        slidermax : Slider, default: None
            Do not allow the current slider to have a value greater than
            the value of the Slider *slidermax*.

        dragging : bool, default: True
            If True the slider can be dragged by the mouse.

        valstep : float, default: None
            If given, the slider will snap to multiples of *valstep*.

        orientation : {'horizontal', 'vertical'}, default: 'horizontal'
            The orientation of the slider.

        Notes
        -----
        Additional kwargs are passed on to ``self.poly`` which is the
        `~matplotlib.patches.Rectangle` that draws the slider knob.  See the
        `.Rectangle` documentation for valid property names (``facecolor``,
        ``edgecolor``, ``alpha``, etc.).
        Z3dz"Sliders cannot be added to 3D AxesNvalz$Argument slidermin ({}) has no 'val'z$Argument slidermax ({}) has no 'val'r]   verticalzBArgument orientation ({}) must be either'horizontal' or 'vertical'Fr   r   r)rL   lwTr=   r>   r?   g      ?gRQ?bottomr9   )r<   r:   r;   g{Gz?toprightleft)r]   r_   g{Gzg{Gz)4namer   r)   r   hasattrformattypeorientation	closedmin	closedmax	slidermin	slidermaxdrag_activevalminvalmaxvalstep_value_in_boundsr^   valinitZaxhspanpolyaxhlineZhlineZaxvspanaxvlineZvlineZset_ylimZyaxisZset_xlimZxaxisvalfmtZget_major_formatter_fmt
isinstancer   ZScalarFormatterZset_axisZset_useOffsetZset_useMathTextrJ   rK   rH   r2   _updater@   rA   rB   _formatvaltextrC   rD   set_val)r   r*   rB   rp   rq   rt   rx   rk   rl   rm   rn   Zdraggingrr   rj   kwargsZaxisr   r   r   r      s    8












zSlider.__init__c             C   s   | j r&| jt|| j | j  | j   }|| jkrB| js:dS | j}n|| jkr\| jsVdS | j}| jdk	r|| jjkr| js|dS | jj}| jdk	r|| jjkr| jsdS | jj}|S )z&Makes sure *val* is with given bounds.N)	rr   rp   roundrk   rq   rl   rm   r^   rn   )r   r^   r   r   r   rs     s(    

zSlider._value_in_boundsc             C   s   | j |s|jdkrdS |jdkrB|j| jkrBd| _|jj| j | jsLdS |jdksl|jdkr|j| jkrd| _|jj| j dS | j	dkr| j
|j}n| j
|j}|d| jgkr| j| dS )zUpdate the slider position.r   Nr=   Tr>   Fr_   )r%   buttonrf   rO   r*   ro   r,   rQ   rR   rj   rs   ydataxdatar^   r~   )r   r$   r^   r   r   r   r{     s$    


zSlider._updatec             C   sB   | j dk	r| j | S | jj| j|| jg\}}}|| jj  S dS )zPretty-print *val*.N)rx   ry   Zformat_ticksrp   rq   Z
get_offset)r   r^   _sr   r   r   r|     s    

zSlider._formatc             C   s   | j j}| jdkr,d|f|d< d|f|d< n|df|d< |df|d< || j _| jj| j| | jrr| jjj	j
  || _| jsdS x| jj D ]\}}|| qW dS )zf
        Set slider value to *val*

        Parameters
        ----------
        val : float
        r_   r   r         N)ru   xyrj   r}   set_textr|   r&   r*   r+   r,   	draw_idler^   r'   rD   rS   )r   r^   r   r1   rT   r   r   r   r~     s    
zSlider.set_valc             C   s"   | j }|| j|< |  j d7  _ |S )a  
        When the slider value is changed call *func* with the new
        slider value

        Parameters
        ----------
        func : callable
            Function to call when slider is changed.
            The function must accept a single float as its arguments.

        Returns
        -------
        int
            Connection id (which can be used to disconnect *func*)
        r   )rC   rD   )r   rT   r1   r   r   r   
on_changed  s    
zSlider.on_changedc             C   s&   y| j |= W n tk
r    Y nX dS )z
        Remove the observer with connection id *cid*

        Parameters
        ----------
        cid : int
            Connection id of the observer to be removed
        N)rD   rY   )r   r1   r   r   r   rZ     s    	zSlider.disconnectc             C   s   | j | jkr| j| j dS )z%Reset the slider to the initial valueN)r^   rt   r~   )r   r   r   r   reset  s    zSlider.reset)	r\   NTTNNTNr]   )r   r   r   r   r   rs   r{   r|   r~   r   rZ   r   r   r   r   r   r[      s      
 		r[   c               @   sB   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dS )CheckButtonsaE  
    A GUI neutral set of check buttons.

    For the check buttons to remain responsive you must keep a
    reference to this object.

    Connect to the CheckButtons with the `.on_clicked` method.

    Attributes
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent axes for the widget.
    labels : list of `.Text`

    rectangles : list of `.Rectangle`

    lines : list of (`.Line2D`, `.Line2D`) pairs
        List of lines for the x's in the check boxes.  These lines exist for
        each box, but have ``set_visible(False)`` when its box is not checked.
    Nc          	   C   s  t j| | |jg  |jg  |jd |dkr@dgt| }t|dkrtdt|d  }tjd| |t|}n
d}dg}|j }g | _	g | _
g | _dd|jd	d
}xt|||D ]\}}	}
|jd||	|jddd}|d |d  }}d||d   }}t||f||d||jd}t||| g|| |gf|}t||| g||| gf|}|j|
 |j|
 | j	j| | jj| | j
j||f |j| |j| |j| qW | jd| j d| _i | _dS )a  
        Add check buttons to `matplotlib.axes.Axes` instance *ax*

        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            The parent axes for the widget.

        labels : list of str
            The labels of the check buttons.

        actives : list of bool, optional
            The initial check states of the buttons. The list must have the
            same length as *labels*. If not given, all buttons are unchecked.
        FNr   g      ?g      ?g      ?kg      ?Zbutt)rL   	linewidthr<   Zsolid_capstylere   r9   )r<   r;   r:   r   g?black)r   widthheight	edgecolor	facecolorr<   r=   r   )r)   r   rJ   rK   rH   lennplinspacerV   labelslines
rectanglesrA   zipr@   r
   r   set_visibler/   	add_patchadd_liner2   _clickedrC   rD   )r   r*   r   ZactivesdyysaxcolorZ
lineparamsyrB   r    twhxpl1l2r   r   r   r     sL    






zCheckButtons.__init__c             C   s   | j |s |jdks |j| jkr$d S xVtt| j| jD ]@\}\}}|j j	|j
|jsl|j j	|j
|jr8| j| P q8W d S )Nr   )r%   r   rO   r*   	enumerater   r   r   get_window_extentcontainsr   r   r!   )r   r$   ir   r   r   r   r   r   _  s      
zCheckButtons._clickedc             C   s   d|  kot | jk n  s*td| | j| \}}|j|j   |j|j   | jrl| jjj	j
  | jsvdS x(| jj D ]\}}|| j| j  qW dS )aM  
        Toggle (activate or deactivate) a check button by index.

        Callbacks will be triggered if :attr:`eventson` is True.

        Parameters
        ----------
        index : int
            Index of the check button to toggle.

        Raises
        ------
        ValueError
            If *index* is invalid.
        r   zInvalid CheckButton index: %dN)r   r   r   r   r   get_visibler&   r*   r+   r,   rW   r'   rD   rS   get_text)r   indexr   r   r1   rT   r   r   r   r!   h  s    zCheckButtons.set_activec             C   s   dd | j D S )zX
        Return a tuple of the status (True/False) of all of the check buttons.
        c             S   s   g | ]\}}|j  qS r   )r   ).0r   r   r   r   r   
<listcomp>  s    z+CheckButtons.get_status.<locals>.<listcomp>)r   )r   r   r   r   
get_status  s    zCheckButtons.get_statusc             C   s"   | j }|| j|< |  j d7  _ |S )z
        Connect the callback function *func* to button click events.

        Returns a connection id, which can be used to disconnect the callback.
        r   )rC   rD   )r   rT   r1   r   r   r   rX     s    
zCheckButtons.on_clickedc             C   s&   y| j |= W n tk
r    Y nX dS )z-Remove the observer with connection id *cid*.N)rD   rY   )r   r1   r   r   r   rZ     s    zCheckButtons.disconnect)N)
r   r   r   r   r   r   r!   r   rX   rZ   r   r   r   r   r     s   
D	r   c               @   s   e Zd ZdZejdedd Zd,d	d
Ze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( Zd)d* Zd+S )-TextBoxa*  
    A GUI neutral text input box.

    For the text box to remain responsive you must keep a reference to it.

    Call `.on_text_change` to be updated whenever the text changes.

    Call `.on_submit` to be updated whenever the user hits enter or
    leaves the text entry field.

    Attributes
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent axes for the widget.
    label : `.Text`

    color : color
        The color of the text box when not hovering.
    hovercolor : color
        The color of the text box when hovering.
    z3.3c             C   s   dd t jD S )Nc             S   s   g | ]}d |kr|qS )Zkeymapr   )r   keyr   r   r   r     s    z-TextBox.params_to_disable.<locals>.<listcomp>)mplrcParams)r   r   r   r   params_to_disable  s    zTextBox.params_to_disable .951{Gz?c             C   s   t j| | d| _|j| d||jddd| _| jj| jd|| jjddd| _d| _i | _	i | _
|jddd	|g g d
 d| _|jdddd	tjj d| _| jd| j | jd| j | jd| j | jd| j | jd| j || _|| _d	| _dS )a  
        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            The `~.axes.Axes` instance the button will be placed into.
        label : str
            Label for this text box.
        initial : str
            Initial value in the text box.
        color : color
            The color of the box.
        hovercolor : color
            The color of the box when the mouse is over it.
        label_pad : float
            The distance between the label and the right side of the textbox.
        g?g      ?r9   rd   )r<   r:   r;   re   r   r   F)xlimylimZnavigater   ZxticksZyticks)visibler<   r=   r>   r?   key_press_eventZresize_eventN)r   r   )r   r   )r)   r   ZDIST_FROM_LEFTr@   rA   rB   r*   	text_disprC   change_observerssubmit_observerssetcursor_indexvlinesr   
transformsZIdentityTransformcursorr2   rE   rF   rG   	_keypress_resizerL   rM   capturekeystrokes)r   r*   rB   initialrL   rM   Z	label_padr   r   r   r     s4    
zTextBox.__init__c             C   s
   | j j S )N)r   r   )r   r   r   r   r@     s    zTextBox.textc             C   s   | j jjd kr| j jjj  | jj }|d | j }| jj|p@d | jj	 }|sZ|j
|_| jj|j|jf|j|jfggdd | jj| | j jjj  d S )N,T)segmentsr   )r*   r+   Z_cachedRendererr,   rW   r   r   r   r   r   x0x1r   r   y0y1)r   r@   Z	widthtextbbr   r   r   _rendercursor  s    	

 zTextBox._rendercursorc             C   s,   | j r(x | jj D ]\}}|| j qW d S )N)r'   r   rS   r@   )r   r1   rT   r   r   r   _notify_submit_observers  s    z TextBox._notify_submit_observersc             C   s2   | j |rd S |jj| jkr d S |jj| j d S )N)r%   r,   rP   r*   rR   )r   r$   r   r   r   rF     s
    
zTextBox._releasec             C   s~  | j |rd S | jrz|j}| j}t|dkr^|d | j | || jd   }|  jd7  _n|dkr| jt|kr|  jd7  _n|dkr| jdkr|  jd8  _n|dkrd| _n|dkrt|| _n|dkr| jdkrL|d | jd  || jd   }|  jd8  _n<|dkrL| jt| jkrL|d | j || jd d   }| jj| | j  | j	  |d	krz| j
  d S )
Nr   rd   re   r   homeendZ	backspacedeleteZenter)r%   r   r   r@   r   r   r   r   r   _notify_change_observersr   )r   r$   r   r@   r   r   r   r     sB    




zTextBox._keypressc             C   s>   t |}| j|krd S | jj| | j  | j  | j  d S )N)strr@   r   r   r   r   r   )r   r^   Znewvalr   r   r   r~   =  s    
zTextBox.set_valc             C   s,   | j r(x | jj D ]\}}|| j qW d S )N)r'   r   rS   r@   )r   r1   rT   r   r   r   r   F  s    z TextBox._notify_change_observersc             C   s   d| _ t }|j| _t| jjjjdd }|d k	rL|j	|  |j
|j	j|  n0tj " |jtjdd tjD  W d Q R X d S )NTtoolmanagerc             S   s   i | ]}|j d rg |qS )zkeymap.)
startswith)r   r   r   r   r   
<dictcomp>^  s    z(TextBox.begin_typing.<locals>.<dictcomp>)r   r   close_on_stop_typinggetattrr*   r+   r,   managerZkeypresslockpushr   r   Z(_suppress_matplotlib_deprecation_warningenter_contextr   Z
rc_contextr   )r   r   stackr   r   r   r   begin_typingK  s    

zTextBox.begin_typingc             C   sN   | j r| j  d | _d}nd}d| _ | jjd | jjjj  |rJ| j  d S )NTF)	r   r   r   r   r*   r+   r,   rW   r   )r   Znotifysubmitr   r   r   stop_typing`  s    zTextBox.stop_typingc             C   sZ   t | jdkrd| _n8| jj }tj||j |j dd}t	t | j| | _| j
  d S )Nr   r   )r   r@   r   r   r   r   clipr   r   intr   )r   r   r   Zratior   r   r   position_cursoro  s    
zTextBox.position_cursorc             C   sn   | j |rd S |j| jkr&| j  d S | js0d S |jj| jkrL|jj| j | js^| j	|j
 | j|j
 d S )N)r%   rO   r*   r   r'   r,   rP   rQ   r   r   r   r   )r   r$   r   r   r   rE   z  s    
zTextBox._clickc             C   s   | j   d S )N)r   )r   r$   r   r   r   r     s    zTextBox._resizec             C   s\   | j |rd S |j| jkr | jn| j}tj|| jj sX| jj| | j	rX| jj
jj  d S )N)r%   rO   r*   rM   rL   r   rU   rV   rI   r&   r+   r,   rW   )r   r$   r4   r   r   r   rG     s    
zTextBox._motionc             C   s"   | j }|| j|< |  j d7  _ |S )z
        When the text changes, call this *func* with event.

        A connection id is returned which can be used to disconnect.
        r   )rC   r   )r   rT   r1   r   r   r   on_text_change  s    
zTextBox.on_text_changec             C   s"   | j }|| j|< |  j d7  _ |S )z
        When the user hits enter or leaves the submission box, call this
        *func* with event.

        A connection id is returned which can be used to disconnect.
        r   )rC   r   )r   rT   r1   r   r   r   	on_submit  s    
zTextBox.on_submitc             C   s:   x4| j | jgD ]$}y
||= W q tk
r0   Y qX qW dS )z-Remove the observer with connection id *cid*.N)r   r   rY   )r   r1   regr   r   r   rZ     s
    
zTextBox.disconnectN)r   r   r   r   )r   r   r   r   r   
deprecatedr(   r   r   r@   r   r   rF   r   r~   r   r   r   r   rE   r   rG   r   r   rZ   r   r   r   r   r     s*    
5#		r   c               @   s:   e Zd ZdZdddZdd Zdd	 Zd
d Zdd ZdS )RadioButtonsa/  
    A GUI neutral radio button.

    For the buttons to remain responsive you must keep a reference to this
    object.

    Connect to the RadioButtons with the `.on_clicked` method.

    Attributes
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent axes for the widget.
    activecolor : color
        The color of the selected button.
    labels : list of `.Text`
        The button labels.
    circles : list of `~.patches.Circle`
        The buttons.
    value_selected : str
        The label text of the currently selected button.
    r   bluec          	   C   s2  t j| | || _d| _|jg  |jg  |jd dt|d  }tj	d| |t|}d}|j
 }|d d }	t|	d}	g | _g | _xt||D ]z\}
}|jd	|
||jd
dd}||kr|| _|}n|}td|
f|	d||jd}| jj| | jj| |j| |d7 }qW | jd| j d| _i | _dS )a  
        Add radio buttons to an `~.axes.Axes`.

        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            The axes to add the buttons to.
        labels : list of str
            The button labels.
        active : int
            The index of the initially selected button.
        activecolor : color
            The color of the selected button.
        NFg      ?r   r   r   g{Gz?g?g      ?re   r9   )r<   r;   r:   g333333?r   )r   radiusr   r   r<   r=   )r)   r   activecolorvalue_selectedrJ   rK   rH   r   r   r   rV   minr   circlesr   r@   rA   r	   r/   r   r2   r   rC   rD   )r   r*   r   r    r   r   r   rC   r   Zcircle_radiusr   rB   r   r   r   r   r   r   r     s>    




zRadioButtons.__init__c             C   s   | j |s |jdks |j| jkr$d S | jjj j|j|jf}i }xdt	t
| j| jD ]N\}\}}|j j|j|jstjj||j |jk rVtjj||j ||< qVW t|dkrt||jd}| j| d S )Nr   r   )r   )r%   r   rO   r*   rA   invertedr<   r   r   r   r   r   r   r   r   r   ZlinalgZnormr9   r   r   r   getr!   )r   r$   ZpclickedZ	distancesr   r   r   closestr   r   r   r     s      zRadioButtons._clickedc             C   s   d|  kot | jkn  r*td| | j| j | _x:t| jD ],\}}||kr^| j}n
| jj	 }|j
| qFW | jr| jjjj  | jsdS x(| jj D ]\}}|| j| j  qW dS )zv
        Select button with number *index*.

        Callbacks will be triggered if :attr:`eventson` is True.
        r   zInvalid RadioButton index: %dN)r   r   r   r   r   r   r   r   r*   rV   rI   r&   r+   r,   rW   r'   rD   rS   )r   r   r   r   rL   r1   rT   r   r   r   r!     s    
zRadioButtons.set_activec             C   s"   | j }|| j|< |  j d7  _ |S )z
        Connect the callback function *func* to button click events.

        Returns a connection id, which can be used to disconnect the callback.
        r   )rC   rD   )r   rT   r1   r   r   r   rX   ,  s    
zRadioButtons.on_clickedc             C   s&   y| j |= W n tk
r    Y nX dS )z-Remove the observer with connection id *cid*.N)rD   rY   )r   r1   r   r   r   rZ   7  s    zRadioButtons.disconnectN)r   r   )	r   r   r   r   r   r   r!   rX   rZ   r   r   r   r   r     s   
:r   c               @   s0  e Zd ZdZdd Zdd Zdd Zejdd	d
e	dd Z
ejddd
e	dd Zejddd
e	dd Zejddd
e	dd Zejddd
e	dd Zejddd
e	dd Zejddd Zejddd Zejddd Zejddd Zejddd  Zejdd!d" Zd#S )$SubplotToolzN
    A tool to adjust the subplot params of a `matplotlib.figure.Figure`.
    c          	   C   st  || _ |jddd |jd g | _ddddd	d
g}x^t||jt|d D ]B\}}|jd t||ddt	|j
|}|j| j | jj| qNW |jd j  | j\| _| _| _| _| _| _x"| j| j| j| jgD ]
}d|_qW x| j| jgD ]
}d|_qW | j| j_| j| j_| j| j_| j| j_|jddddg}t|d| _tj|j
dd | jj| j  W dQ R X dS )z
        Parameters
        ----------
        targetfig : `.Figure`
            The figure instance to adjust.
        toolfig : `.Figure`
            The figure instance to embed the subplot tool into.
        g?g?)re   rd   z'Click on slider to adjust subplot paramre   rb   rd   rc   wspacehspacer   Fr   g?g?g333333?g333333?Reset)validateN)!	targetfigsubplots_adjustZsuptitle_slidersr   Zsubplotsr   rH   r[   r   Zsubplotparsr   _on_slider_changedr/   axesremove
sliderleftsliderbottomsliderright	slidertopsliderwspacesliderhspacerl   rk   rn   rm   Zadd_axesr6   Zbuttonresetr   _setattr_cmrX   	_on_reset)r   r   Ztoolfignamesrf   r*   sliderZbaxr   r   r   r   D  s4    

"







zSubplotTool.__init__c             C   s0   | j jf dd | jD  | jr,| j jj  d S )Nc             S   s   i | ]}|j |jj qS r   )r^   rB   r   )r   r  r   r   r   r   t  s   z2SubplotTool._on_slider_changed.<locals>.<dictcomp>)r   r   r  r&   r,   rW   )r   r   r   r   r   r  r  s
    zSubplotTool._on_slider_changedc             C   s   t  V}|jtj| dd x"| jD ]}|jtj|dd q$W x| jD ]}|j  qHW W d Q R X | jr~|jj  | j	jj  d S )NF)r&   )
r   r   r   r  r  r   r&   r,   rW   r   )r   r$   r   r  r   r   r   r  y  s    
zSubplotTool._on_resetz3.3axleft)rf   c             C   s   | j jS )N)r  r*   )r   r   r   r   <lambda>  s    zSubplotTool.<lambda>axrightc             C   s   | j jS )N)r  r*   )r   r   r   r   r    s    axbottomc             C   s   | j jS )N)r  r*   )r   r   r   r   r    s    axtopc             C   s   | j jS )N)r  r*   )r   r   r   r   r    s    axwspacec             C   s   | j jS )N)r	  r*   )r   r   r   r   r    s    axhspacec             C   s   | j jS )N)r
  r*   )r   r   r   r   r    s    c             C   s$   | j j|d | jr | j jj  d S )N)re   )r   r   r&   r,   rW   )r   r^   r   r   r   funcleft  s    zSubplotTool.funcleftc             C   s$   | j j|d | jr | j jj  d S )N)rd   )r   r   r&   r,   rW   )r   r^   r   r   r   	funcright  s    zSubplotTool.funcrightc             C   s$   | j j|d | jr | j jj  d S )N)rb   )r   r   r&   r,   rW   )r   r^   r   r   r   
funcbottom  s    zSubplotTool.funcbottomc             C   s$   | j j|d | jr | j jj  d S )N)rc   )r   r   r&   r,   rW   )r   r^   r   r   r   functop  s    zSubplotTool.functopc             C   s$   | j j|d | jr | j jj  d S )N)r   )r   r   r&   r,   rW   )r   r^   r   r   r   
funcwspace  s    zSubplotTool.funcwspacec             C   s$   | j j|d | jr | j jj  d S )N)r   )r   r   r&   r,   rW   )r   r^   r   r   r   
funchspace  s    zSubplotTool.funchspaceN)r   r   r   r   r   r  r  r   r   r(   r  r  r  r  r  r  r  r  r  r  r  r  r   r   r   r   r   ?  s,   .r   c               @   s2   e Zd ZdZdddZdd Zdd	 Zd
d ZdS )Cursora  
    A crosshair cursor that spans the axes and moves with mouse cursor.

    For the cursor to remain responsive you must keep a reference to it.

    Parameters
    ----------
    ax : `matplotlib.axes.Axes`
        The `~.axes.Axes` to attach the cursor to.
    horizOn : bool, default: True
        Whether to draw the horizontal line.
    vertOn : bool, default: True
        Whether to draw the vertical line.
    useblit : bool, default: False
        Use blitting for faster drawing if supported by the backend.

    Other Parameters
    ----------------
    **lineprops
        `.Line2D` properties that control the appearance of the lines.
        See also `~.Axes.axhline`.

    Examples
    --------
    See :doc:`/gallery/widgets/cursor`.
    TFc             K   s   t j| | | jd| j | jd| j d| _|| _|| _|oD| jj	| _
| j
rVd|d< |j|j d fddi|| _|j|j d fddi|| _d | _d| _d S )Nr?   
draw_eventTanimatedr   r   F)r)   r   r2   onmoveclearr   horizOnvertOnr,   supports_blituseblitrv   
get_yboundlinehrw   
get_xboundlinev
background	needclear)r   r*   r!  r"  r$  	linepropsr   r   r   r     s      zCursor.__init__c             C   sB   | j |rdS | jr&| jj| jj| _| jjd | j	jd dS )z+Internal event handler to clear the cursor.NF)
r%   r$  r,   copy_from_bboxr*   bboxr)  r(  r   r&  )r   r$   r   r   r   r     s    
zCursor.clearc             C   s   | j |rdS | jjj| s dS |j| jkr^| jjd | jjd | j	rZ| jj
  d| _	dS d| _	| jsndS | jj|j|jf | jj|j|jf | jj| jo| j | jj| jo| j | j  dS )z?Internal event handler to draw the cursor when the mouse moves.NFT)r%   r,   
widgetlockr   rO   r*   r(  r   r&  r*  rW   r   	set_xdatar   	set_ydatar   r"  r!  r{   )r   r$   r   r   r   r    s&    

zCursor.onmovec             C   sZ   | j rL| jd k	r| jj| j | jj| j | jj| j | jj| jj	 n
| jj
  dS )NF)r$  r)  r,   restore_regionr*   draw_artistr(  r&  blitr-  r   )r   r   r   r   r{     s    

zCursor._updateN)TTF)r   r   r   r   r   r   r  r{   r   r   r   r   r    s
   
	r  c               @   sB   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Zdd Z	dS )MultiCursora  
    Provide a vertical (default) and/or horizontal line cursor shared between
    multiple axes.

    For the cursor to remain responsive you must keep a reference to it.

    Example usage::

        from matplotlib.widgets import MultiCursor
        import matplotlib.pyplot as plt
        import numpy as np

        fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
        t = np.arange(0.0, 2.0, 0.01)
        ax1.plot(t, np.sin(2*np.pi*t))
        ax2.plot(t, np.sin(4*np.pi*t))

        multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=1,
                            horizOn=False, vertOn=True)
        plt.show()

    TFc                s   || _ || _|| _|| _|d	 j \}}|d
 j \}	}
d||  d|	|
  d| _|o`| j j| _d | _	d| _
| jr~d d< |r fdd|D | _ng | _|r fdd|D | _ng | _| j  d S )Nr   g      ?TFr  c                s"   g | ]}|j fd di qS )r   F)rw   )r   r*   )r+  xmidr   r   r   D  s   z(MultiCursor.__init__.<locals>.<listcomp>c                s"   g | ]}|j fd di qS )r   F)rv   )r   r*   )r+  ymidr   r   r   J  s   r   r   )r,   r  r!  r"  get_xlimget_ylimr   r#  r$  r)  r*  r   hlinesconnect)r   r,   r  r$  r!  r"  r+  xminxmaxyminymaxr   )r+  r5  r6  r   r   .  s.    zMultiCursor.__init__c             C   s(   | j jd| j| _| j jd| j| _dS )zConnect events.r?   r  N)r,   r.   r  
_cidmotionr   _ciddraw)r   r   r   r   r:  Q  s    
zMultiCursor.connectc             C   s    | j j| j | j j| j dS )zDisconnect events.N)r,   r3   r?  r@  )r   r   r   r   rZ   W  s    zMultiCursor.disconnectc             C   sL   | j |rdS | jr(| jj| jjj| _x| j| j D ]}|j	d q6W dS )zClear the cursor.NF)
r%   r$  r,   r,  r+   r-  r)  r   r9  r   )r   r$   liner   r   r   r   \  s    
zMultiCursor.clearc             C   s   | j |rd S |jd krd S | jjj| s.d S d| _| js>d S | jrrx,| jD ]"}|j	|j
|j
f |j| j qLW | jrx,| jD ]"}|j|j|jf |j| j qW | j  d S )NT)r%   rO   r,   r.  r   r*  r   r"  r   r/  r   r   r!  r9  r0  r   r{   )r   r$   rA  r   r   r   r  f  s$    

zMultiCursor.onmovec             C   s   | j r| jd k	r| jj| j | jrJx$t| j| jD ]\}}|j| q4W | j	rvx$t| j| j
D ]\}}|j| q`W | jj  n
| jj  d S )N)r$  r)  r,   r1  r"  r   r  r   r2  r!  r9  r3  r   )r   r*   rA  r   r   r   r{   z  s    
zMultiCursor._updateN)TFT)
r   r   r   r   r   r:  rZ   r   r  r{   r   r   r   r   r4    s   
#
r4  c               @   s   e Zd Z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 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S )._SelectorWidgetFNc             C   s   t j| | d| _|| _|o"| jj| _| j  tddddd| _	| j	j
|pLi  d | _g | _t|trp|g| _n|| _d | _d | _d | _t | _d S )NT escapeshiftcontrol)mover   squarer9   )r)   r   r   onselectr,   r#  r$  connect_default_eventsdictstate_modifier_keysupdater)  artistsrz   r   validButtons
eventpresseventrelease_prev_eventr   state)r   r*   rI  r$  r   rL  r   r   r   r     s"    

z_SelectorWidget.__init__c             C   s   t j| | |r| jd  d S )N)r)   r!   update_background)r   r    r   r   r   r!     s    z_SelectorWidget.set_activec             C   s   | j r| jj| jj| _dS )z"Force an update of the background.N)r$  r,   r,  r*   r-  r)  )r   r$   r   r   r   rT    s    z!_SelectorWidget.update_backgroundc             C   sf   | j d| j | j d| j | j d| j | j d| j | j d| j | j d| j | j d| j dS )	z+Connect the major canvas events to methods.r?   r=   r>   r  r   Zkey_release_eventZscroll_eventN)r2   r  pressr   rT  on_key_presson_key_release	on_scroll)r   r   r   r   rJ    s    z&_SelectorWidget.connect_default_eventsc             C   s   | j  s| jj  rdS | jjj| s*dS t|ds:d |_| jd k	rT|j| jkrTdS | j	d krj|j
| jkS |j| j	jkr|dS |j
| jkp|j| j	jkS )NTr   F)r    r*   r   r,   r.  r   rg   r   rO  rP  rO   )r   r$   r   r   r   r%     s    


z_SelectorWidget.ignorec             C   sh   | j j sdS | jrZ| jdk	r,| jj| j x| jD ]}| j j| q4W | jj| j j	 n
| jj
  dS )z@Draw using blit() or draw_idle(), depending on ``self.useblit``.FN)r*   r   r$  r)  r,   r1  rN  r2  r3  r-  r   )r   artistr   r   r   rM    s    


z_SelectorWidget.updatec             C   sF   |j dkrdS tj|j f| jj  }tj|jf| jj  }||fS )z/Get the xdata and ydata for event, with limits.N)NN)r   r   r   r*   r'  r   r%  )r   r$   r   r   r   r   r   	_get_data  s
    
z_SelectorWidget._get_datac             C   s8   |j dkr| j}n
tj|}| j|\|_ |_|| _|S )z
        Preprocess an event:

        - Replace *event* by the previous event if *event* has no ``xdata``.
        - Clip ``xdata`` and ``ydata`` to the axes limits.
        - Update the previous event.
        N)r   rR  copyrZ  r   )r   r$   r   r   r   _clean_event  s    

z_SelectorWidget._clean_eventc             C   sb   | j |s^| j|}|| _|| _|jp(d}|jdd}|| jd krP| jjd | j	| dS dS )z#Button press handler and validator.r   ctrlrF  rG  TF)
r%   r\  rP  rR  r   replacerL  rS  add_press)r   r$   r   r   r   r   rU    s    



z_SelectorWidget.pressc             C   s   dS )zButton press handler.Nr   )r   r$   r   r   r   r`    s    z_SelectorWidget._pressc             C   sL   | j | rH| jrH| j|}|| _| j| d| _d| _| jjd dS dS )z+Button release event handler and validator.NrG  TF)r%   rP  r\  rQ  rF   rS  discard)r   r$   r   r   r   r     s    

z_SelectorWidget.releasec             C   s   dS )zButton release event handler.Nr   )r   r$   r   r   r   rF     s    z_SelectorWidget._releasec             C   s.   | j | r*| jr*| j|}| j| dS dS )z(Cursor move event handler and validator.TF)r%   rP  r\  _onmove)r   r$   r   r   r   r    s
    

z_SelectorWidget.onmovec             C   s   dS )zCursor move event handler.Nr   )r   r$   r   r   r   rb  %  s    z_SelectorWidget._onmovec             C   s   | j |s| j| dS )z)Mouse scroll event handler and validator.N)r%   
_on_scroll)r   r$   r   r   r   rX  (  s    
z_SelectorWidget.on_scrollc             C   s   dS )zMouse scroll event handler.Nr   )r   r$   r   r   r   rc  -  s    z_SelectorWidget._on_scrollc             C   s   | j r|jpd}|jdd}|| jd krPx| jD ]}|jd q2W | j  dS x*| jj D ]\}}||kr\| jj	| q\W | j
| dS )z@Key press event handler and validator for all selection widgets.r   r]  rF  r   FN)r    r   r^  rL  rN  r   rM  rS   rS  r_  _on_key_press)r   r$   r   rY  rS  modifierr   r   r   rV  0  s    
z_SelectorWidget.on_key_pressc             C   s   dS )z@Key press event handler - for widget-specific key press actions.Nr   )r   r$   r   r   r   rd  ?  s    z_SelectorWidget._on_key_pressc             C   sJ   | j rF|jpd}x*| jj D ]\}}||kr| jj| qW | j| dS )z(Key release event handler and validator.r   N)r    r   rL  rS   rS  ra  _on_key_release)r   r$   r   rS  re  r   r   r   rW  B  s    
z_SelectorWidget.on_key_releasec             C   s   dS )zKey release event handler.Nr   )r   r$   r   r   r   rf  K  s    z_SelectorWidget._on_key_releasec             C   s$   || _ x| jD ]}|j| qW dS )z"Set the visibility of our artists.N)r   rN  r   )r   r   rY  r   r   r   r   N  s    z_SelectorWidget.set_visible)FNN)r   r   r   r   r!   rT  rJ  r%   rM  rZ  r\  rU  r`  r   rF   r  rb  rX  rc  rV  rd  rW  rf  r   r   r   r   r   rB    s,    

	rB  c               @   sJ   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Zdd Z	dd Z
dS )SpanSelectora  
    Visually select a min/max range on a single axis and call a function with
    those values.

    To guarantee that the selector remains responsive, keep a reference to it.

    In order to turn off the SpanSelector, set ``span_selector.active`` to
    False.  To turn it back on, set it to True.

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

    onselect : func(min, max), min/max are floats

    direction : {"horizontal", "vertical"}
        The direction along which to draw the span selector.

    minspan : float, default: None
        If selection is less than *minspan*, do not call *onselect*.

    useblit : bool, default: False
        If True, use the backend-dependent blitting features for faster
        canvas updates.

    rectprops : dict, default: None
        Dictionary of `matplotlib.patches.Patch` properties.

    onmove_callback : func(min, max), min/max are floats, default: None
        Called on mouse move while the span is being selected.

    span_stays : bool, default: False
        If True, the span stays visible after the mouse is released.

    button : `.MouseButton` or list of `.MouseButton`
        The mouse buttons which activate the span selector.

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> import matplotlib.widgets as mwidgets
    >>> fig, ax = plt.subplots()
    >>> ax.plot([1, 2, 3], [10, 50, 100])
    >>> def onselect(vmin, vmax):
    ...     print(vmin, vmax)
    >>> rectprops = dict(facecolor='blue', alpha=0.5)
    >>> span = mwidgets.SpanSelector(ax, onselect, 'horizontal',
    ...                              rectprops=rectprops)
    >>> fig.show()

    See also: :doc:`/gallery/widgets/span_selector`
    NFc
       
      C   s   t j| ||||	d |d kr(tddd}| j|d< tjddg|d || _d | _d | _|| _	|| _
|| _|| _d
| _d | _| j| d S )N)r$  r   redg      ?)r   alphar  r]   r_   )	directionr   )r   r   )rB  r   rK  r$  r   _check_in_listrj  rectpressv	rectpropsonmove_callbackminspan
span_staysprevr,   new_axes)
r   r*   rI  rj  rp  r$  rn  ro  rq  r   r   r   r   r     s     
zSpanSelector.__init__c             C   s   || _ | j|jjk	r8| jdk	r&| j  |jj| _| j  | jdkr^t| j j| j j}d\}}nt| j j| j j}d\}}t	d	||f|dd| j
| _| jrt	d
||f|dd| j
| _| jjd | j j| j | j j| j | jg| _dS )z*Set SpanSelector to operate on a new Axes.Nr]   r   r   F)r<   r   )r   r   )r   r   )r   r   )r   r   )r*   r,   r+   r5   rJ  rj  r   	transDatarA   r
   rn  rl  rq  	stay_rectset_animatedr   rN  )r   r*   Ztransr   r   r   r   r   rs    s4    







zSpanSelector.new_axesc             C   s   t j| |p| j S )N)rB  r%   r   )r   r$   r   r   r   r%     s    zSpanSelector.ignorec             C   sd   | j j| j | jr0| jjd | jr0| jj  | j|\}}| j	dkrP|| _
n|| _
| j| dS )zon button press eventFr]   )rl  r   r   rq  ru  r$  r,   rW   rZ  rj  rm  _set_span_xy)r   r$   r   r   r   r   r   r`    s    


zSpanSelector._pressc             C   s  | j dkrdS | jjd | jrt| jj| jj  | jj| jj  | jj	| jj
  | jj| jj  | jjd | jj  | j }| j|\}}| jdkr|p| jd }n|p| jd }||kr|| }}|| }| jdk	r|| jk rdS | j|| d| _ dS )zon button release eventNFTr]   r   r   )rm  rl  r   rq  ru  set_xget_xset_yget_y	set_width	get_width
set_height
get_heightr,   r   rZ  rj  rr  rp  rI  )r   r$   vminr   r   vmaxspanr   r   r   rF     s.    



zSpanSelector._releasec             C   s   | j dkrdS | j| | jdk	r|| j }| j|\}}| jdkrP|pL| jd }n|p\| jd }||krp|| }}| j|| | j  dS )zon motion notify eventNr]   r   r   F)rm  rw  ro  rZ  rj  rr  rM  )r   r$   r  r   r   r  r   r   r   rb    s    




zSpanSelector._onmovec             C   s   | j |\}}|dkrdS ||f| _| jdkr4|}n|}|| j }}||krV|| }}| jdkr~| jj| | jj||  n| jj| | jj||  dS )zSet the span coordinates.Nr]   )	rZ  rr  rj  rm  rl  rx  r|  rz  r~  )r   r$   r   r   vZminvZmaxvr   r   r   rw    s    



zSpanSelector._set_span_xy)NFNNFN)r   r   r   r   r   rs  r%   r`  rF   rb  rw  r   r   r   r   rg  U  s   4  
!rg  c               @   sT   e Zd ZdZdddZedd Zed	d
 ZdddZdd Z	dd Z
dd ZdS )ToolHandlesa  
    Control handles for canvas tools.

    Parameters
    ----------
    ax : `matplotlib.axes.Axes`
        Matplotlib axes where tool handles are displayed.
    x, y : 1D arrays
        Coordinates of control handles.
    marker : str
        Shape of marker used to display handle. See `matplotlib.pyplot.plot`.
    marker_props : dict
        Additional marker properties. See `matplotlib.lines.Line2D`.
    r   NTc          	   C   sd   || _ t|ddddddd}|j|d k	r,|ni  t||fd|i|| _| j j| j | j| _d S )	N   r   noneg      ?FZ
_nolegend_)markerZ
markersizemfcZlsri  r   rB   r  )r*   rK  rM  r   _markersr   rY  )r   r*   r   r   r  marker_propsr$  propsr   r   r   r   <  s    
zToolHandles.__init__c             C   s
   | j j S )N)r  Z	get_xdata)r   r   r   r   r   E  s    zToolHandles.xc             C   s
   | j j S )N)r  Z	get_ydata)r   r   r   r   r   I  s    zToolHandles.yc             C   s*   |dk	r|}t j||g}| jj| dS )z Set x and y positions of handlesN)r   arrayr  set_data)r   ptsr   r   r   r   r   r  M  s    zToolHandles.set_datac             C   s   | j j| d S )N)r  r   )r   r^   r   r   r   r   T  s    zToolHandles.set_visiblec             C   s   | j j| d S )N)r  rv  )r   r^   r   r   r   rv  W  s    zToolHandles.set_animatedc             C   sN   t j| j| jg}| jjj|}|||g }t j|j }t j	|}||| fS )z1Return index and pixel distance to closest index.)
r   Zcolumn_stackr   r   r*   rt  r<   hypotTZargmin)r   r   r   r  ZdiffdistZ	min_indexr   r   r   r   Z  s    
zToolHandles.closest)r   NT)N)r   r   r   r   r   r(   r   r   r  r   rv  r   r   r   r   r   r  ,  s   
	
r  c               @   s   e Zd ZdZeZd!dd	Zd
d Zdd Zdd Z	e
dd Ze
dd Ze
dd Ze
dd Ze
dd Zejdd Zdd Zdd Ze
dd  ZdS )"RectangleSelectorz
    Select a rectangular region of an axes.

    For the cursor to remain responsive you must keep a reference to it.

    Examples
    --------
    :doc:`/gallery/widgets/rectangle_selector`
    boxr   FNdata
   c             C   s  t j| ||||
|d d| _d| _|| _|dkr:d}d| _|dkr|dkrZtdd	d
dd}| j|d< || _| jd&ddi| j| _| j	j
| j |dkr|dkrtd	dddd}| j|d< || _tddgddgfddi| j| _| j	j| j || _|| _tjddg|	d |	| _|| _|| _|dkr6tdd}nt|jddd}ddddg| _| j\}}t| j	|||| jd| _dd d!d"g| _| j\}}t| j	||d#|| jd$| _| j\}}t| j	|g|gd#|| jd$| _d| _| j| jj | jj | jj g| _!| js| jg| _!d| _"dS )'a
  
        Parameters
        ----------
        ax : `~matplotlib.axes.Axes`
            The parent axes for the widget.

        onselect : function
            A callback function that is called after a selection is completed.
            It must have the signature::

                def onselect(eclick: MouseEvent, erelease: MouseEvent)

            where *eclick* and *erelease* are the mouse click and release
            `.MouseEvent`\s that start and complete the selection.

        drawtype : {"box", "line", "none"}, default: "box"
            Whether to draw the full rectangle box, the diagonal line of the
            rectangle, or nothing at all.

        minspanx : float, default: 0
            Selections with an x-span less than *minspanx* are ignored.

        minspany : float, default: 0
            Selections with an y-span less than *minspany* are ignored.

        useblit : bool, default: False
            Whether to use blitting for faster drawing (if supported by the
            backend).

        lineprops : dict, optional
            Properties with which the line is drawn, if ``drawtype == "line"``.
            Default::

                dict(color="black", linestyle="-", linewidth=2, alpha=0.5)

        rectprops : dict, optional
            Properties with which the rectangle is drawn, if ``drawtype ==
            "box"``.  Default::

                dict(facecolor="red", edgecolor="black", alpha=0.2, fill=True)

        spancoords : {"data", "pixels"}, default: "data"
            Whether to interpret *minspanx* and *minspany* in data or in pixel
            coordinates.

        button : `.MouseButton`, list of `.MouseButton`, default: all buttons
            Button(s) that trigger rectangle selection.

        maxdist : float, default: 10
            Distance in pixels within which the interactive tool handles can be
            activated.

        marker_props : dict
            Properties with which the interactive handles are drawn.  Currently
            not implemented and ignored.

        interactive : bool, default: False
            Whether to draw a set of handles that allow interaction with the
            widget after it is drawn.

        state_modifier_keys : dict, optional
            Keyboard modifiers which affect the widget's behavior.  Values
            amend the defaults.

            - "move": Move the existing shape, default: no modifier.
            - "clear": Clear the current shape, default: "escape".
            - "square": Makes the shape square, default: "shift".
            - "center": Make the initial point the center of the shape,
              default: "ctrl".

            "square" and "center" can be combined.
        )r$  r   rL  NTr  rA  Fr  rh  r   g?)r   r   ri  fillr  r   r   r   -r   g      ?)rL   	linestyler   ri  r  pixels)
spancoordsr`   )mecr   NWNEZSESW)r  r$  WNESr   )r  r  r$  r   r   )r  r   r   )#rB  r   to_drawr   interactiverK  r$  rn  _shape_klassr*   r   r+  r   r   minspanxminspanyr   rk  r  drawtypemaxdistr   _corner_ordercornersr  _corner_handles_edge_orderedge_centers_edge_handlesr9   _center_handleactive_handlerY  rN  _extents_on_press)r   r*   rI  r  r  r  r$  r+  rn  r  r   r  r  r  rL  r  xcycxeyer   r   r   r   r  sp    M









zRectangleSelector.__init__c             C   sl   | j r| jj r| j| nd| _| jdks4| j  r<| j  | j s\|j}|j}||||f| _| j	| j
 dS )zon button press eventN)r  r  r   _set_active_handler  rM  r   r   extentsr   r   )r   r$   r   r   r   r   r   r`    s    zRectangleSelector._pressc             C   s  | j s| jjd | j\}}}}|| j_|| j_| jjj	||g}|\| j_
| j_|| j_|| j_| jjj	||g}|\| j_
| j_| jdkrt| jj| jj }t| jj| jj }	nH| jdkrt| jj
| jj
 }t| jj| jj }	ntjddg| jd | jdkrd| jdk	r$|| jk s<| jdk	rd|	| jk rdx| jD ]}
|
jd qDW | j  dS | j| j| j | j  dS )zon button release eventFr  r  )r  r  N)r  r  r   r  rP  r   r   r*   rt  r<   r   r   rQ  r  absr   rk  r  r  r  rN  rM  rI  )r   r$   r   x2r   y2Zxy1Zxy2ZspanxZspanyrY  r   r   r   rF     s:    



zRectangleSelector._releasec             C   s  | j rV| j dkrV| j\}}}}| j ddg| j kr8|j}| j ddg| j krR|j}nd| jksj| j dkr| jdk	r| j\}}}}|j| jj }|j| jj }||7 }||7 }||7 }||7 }nF| jj| jjg}| jj| jjg}	|j|d  d	 }|j|d
  d	 }d| jkrt	|j|	d  }
t	|j|	d
  }|
s@dS t
t	|
t	|}t	|
|k rt||t	|
d  9 }t	||k r||t	|d  9 }d| jkr|d9 }|d9 }n |d  |7  < |d
  |7  < |d | |d | |d
 | |d
 | f\}}}}||||f| _dS )z,on motion notify event if box/line is wantedCr  r  r  r  rG  Nr   g       @r   rH  gư>r9   r   )r  r  r  r   r   rS  rP  r   r   r  maxr  )r   r$   r   r  r   r  dxr   r9   Z
center_pixZdx_pixZdy_pixZmaxdr   r   r   rb  E  sJ    


 zRectangleSelector._onmovec       	      C   s   | j dkr>| jj }| jj }| jj }| jj }||||fS | jj \}}t|t| }}t|t| }}|||| || fS d S )Nr  )	r  r  ry  r{  r}  r  get_datar   r  )	r   r   r   r   r   r   r   r   r   r   r   r   
_rect_bbox|  s    




zRectangleSelector._rect_bboxc             C   s>   | j \}}}}||| || |f}|||| || f}||fS )z7Corners of rectangle from lower left, moving clockwise.)r  )r   r   r   r   r   r  r  r   r   r   r    s    zRectangleSelector.cornersc       	      C   sV   | j \}}}}|d }|d }||| || || f}|| ||| || f}||fS )z8Midpoint of rectangle edges from left, moving clockwise.g       @)r  )	r   r   r   r   r   r   r   r  r  r   r   r   r    s    zRectangleSelector.edge_centersc             C   s&   | j \}}}}||d  ||d  fS )zCenter of rectangleg       @)r  )r   r   r   r   r   r   r   r   r9     s    zRectangleSelector.centerc       	      C   sB   | j \}}}}t||| g\}}t||| g\}}||||fS )z Return (xmin, xmax, ymin, ymax).)r  sorted)	r   r   r   r   r   r;  r<  r=  r>  r   r   r   r    s    zRectangleSelector.extentsc             C   sL   | j | | jj| j  | jj| j  | jj| j  | j| j	 | j
  d S )N)
draw_shaper  r  r  r  r  r  r9   r   r   rM  )r   r  r   r   r   r    s    
c             C   s   |\}}}}t ||g\}}t ||g\}}	t | jj }
t | jj }t|
d |}t|d |}t||
d }t|	|d }	| jdkr| jj| | jj	| | jj
||  | jj|	|  n | jdkr| jj||g||	g d S )Nr   r   r  rA  )r  r*   r7  r8  r  r   r  r  rx  rz  r|  r~  r  )r   r  r   r   r   r   r;  r<  r=  r>  r   r   r   r   r   r    s     

zRectangleSelector.draw_shapec             C   s   | j j|j|j\}}| jj|j|j\}}| jj|j|j\}}d| jkr\d| _| j| _	nV|| j
d k rrd| _n@|| j
kr|| j
krd| _dS ||k r| j| | _n| j| | _| j\}}	}
}| jd
kr|	|j }}	| jdkr||j }
}||	|
|f| _	dS )z:Set active handle based on the location of the mouse eventrG  r  r   Nr  r  r  r  r  )r  r  r  )r  r  r  )r  r   r   r   r  r  rS  r  r  r  r  r  r  r   r   )r   r$   Zc_idxZc_distZe_idxZe_distZm_idxZm_distr   r  r   r  r   r   r   r    s(    



z$RectangleSelector._set_active_handlec             C   sP   t | jdr<| jjj }|j| jj j\}}tj	||gS tj	| jj
 S dS )a  
        Return an array of shape (2, 5) containing the
        x (``RectangleSelector.geometry[1, :]``) and
        y (``RectangleSelector.geometry[0, :]``) coordinates
        of the four corners of the rectangle starting and ending
        in the top left corner.
        	get_vertsN)rg   r  r*   rt  r   r<   r  r  r   r  r  )r   Zxfmr   r   r   r   r   geometry  s
    	zRectangleSelector.geometry)r  r   r   FNNr  Nr  NFN)r   r   r   r   r
   r  r   r`  rF   rb  r(   r  r  r  r9   r  setterr  r  r  r   r   r   r   r  e  s(   	    
 +7
r  c               @   s(   e Zd ZdZeZdd Zedd ZdS )EllipseSelectora  
    Select an elliptical region of an axes.

    For the cursor to remain responsive you must keep a reference to it.

    Example usage::

        import numpy as np
        import matplotlib.pyplot as plt
        from matplotlib.widgets import EllipseSelector

        def onselect(eclick, erelease):
            "eclick and erelease are matplotlib events at press and release."
            print('startposition: (%f, %f)' % (eclick.xdata, eclick.ydata))
            print('endposition  : (%f, %f)' % (erelease.xdata, erelease.ydata))
            print('used button  : ', eclick.button)

        def toggle_selector(event):
            print(' Key pressed.')
            if event.key in ['Q', 'q'] and toggle_selector.ES.active:
                print('EllipseSelector deactivated.')
                toggle_selector.RS.set_active(False)
            if event.key in ['A', 'a'] and not toggle_selector.ES.active:
                print('EllipseSelector activated.')
                toggle_selector.ES.set_active(True)

        x = np.arange(100.) / 99
        y = np.sin(x)
        fig, ax = plt.subplots()
        ax.plot(x, y)

        toggle_selector.ES = EllipseSelector(ax, onselect, drawtype='line')
        fig.canvas.mpl_connect('key_press_event', toggle_selector)
        plt.show()
    c             C   s   |\}}}}t ||g\}}t ||g\}}	||| d  ||| d  g}
|| d }|	| d }| jdkr|
| j_d| | j_d| | j_nNtjtjdd }|tj	| |
d  }|tj
| |
d  }| jj|| d S )Ng       @r  r         r   r   )r  r  r  r9   r   r   r   Zdeg2radZarangecossinr  )r   r  r   r  r   r  r;  r<  r=  r>  r9   abZradr   r   r   r   r   r   	  s     
zEllipseSelector.draw_shapec       	      C   s   | j dkrB| jj\}}| jj}| jj}||d  ||d  ||fS | jj \}}t|t| }}t|t| }}|||| || fS d S )Nr  g       @)r  r  r9   r   r   r  r   r  )	r   r   r   r   r   r   r   r   r   r   r   r   r  2	  s    
zEllipseSelector._rect_bboxN)	r   r   r   r   r   r  r  r(   r  r   r   r   r   r    s   #r  c               @   sB   e Zd ZdZdddZdd Zdd	 Zd
d Zdd Zdd Z	dS )LassoSelectora  
    Selection curve of an arbitrary shape.

    For the selector to remain responsive you must keep a reference to it.

    The selected path can be used in conjunction with `~.Path.contains_point`
    to select data points from an image.

    In contrast to `Lasso`, `LassoSelector` is written with an interface
    similar to `RectangleSelector` and `SpanSelector`, and will continue to
    interact with the axes until disconnected.

    Example usage::

        ax = subplot(111)
        ax.plot(x, y)

        def onselect(verts):
            print(verts)
        lasso = LassoSelector(ax, onselect)

    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent axes for the widget.
    onselect : function
        Whenever the lasso is released, the *onselect* function is called and
        passed the vertices of the selected path.
    button : `.MouseButton` or list of `.MouseButton`, optional
        The mouse buttons used for rectangle selection.  Default is ``None``,
        which corresponds to all buttons.
    NTc             C   sd   t j| ||||d d | _|d kr(t }|j| jdd tg g f|| _| jj	| j | jg| _
d S )N)r$  r   F)r  r   )rB  r   vertsrK  rM  r$  r   rA  r*   r   rN  )r   r*   rI  r$  r+  r   r   r   r   r   b	  s    zLassoSelector.__init__c             C   s   | j | d S )N)rU  )r   r$   r   r   r   onpresso	  s    zLassoSelector.onpressc             C   s   | j |g| _| jjd d S )NT)rZ  r  rA  r   )r   r$   r   r   r   r`  r	  s    zLassoSelector._pressc             C   s   | j | d S )N)r   )r   r$   r   r   r   	onreleasev	  s    zLassoSelector.onreleasec             C   sN   | j d k	r(| j j| j| | j| j  | jjg g g | jjd d | _ d S )NF)r  r/   rZ  rI  rA  r  r   )r   r$   r   r   r   rF   y	  s    
zLassoSelector._releasec             C   sB   | j d krd S | j j| j| | jjtt| j   | j  d S )N)r  r/   rZ  rA  r  listr   rM  )r   r$   r   r   r   rb  	  s
    
zLassoSelector._onmove)NTNN)
r   r   r   r   r   r  r`  r  rF   rb  r   r   r   r   r  @	  s     
r  c               @   s^   e Zd ZdZ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edd ZdS )PolygonSelectora  
    Select a polygon region of an axes.

    Place vertices with each mouse click, and make the selection by completing
    the polygon (clicking on the first vertex). Hold the *ctrl* key and click
    and drag a vertex to reposition it (the *ctrl* key is not necessary if the
    polygon has already been completed). Hold the *shift* key and click and
    drag anywhere in the axes to move all vertices. Press the *esc* key to
    start a new polygon.

    For the selector to remain responsive you must keep a reference to it.

    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent axes for the widget.
    onselect : function
        When a polygon is completed or modified after completion,
        the *onselect* function is called and passed a list of the vertices as
        ``(xdata, ydata)`` tuples.
    useblit : bool, default: False
    lineprops : dict, default: ``dict(color='k', linestyle='-', linewidth=2, alpha=0.5)``.
        Artist properties for the line representing the edges of the polygon.
    markerprops : dict, default: ``dict(marker='o', markersize=7, mec='k', mfc='k', alpha=0.5)``.
        Artist properties for the markers drawn at the vertices of the polygon.
    vertex_select_radius : float, default: 15px
        A vertex is selected (to complete the polygon or to move a vertex) if
        the mouse click is within *vertex_select_radius* pixels of the vertex.

    Examples
    --------
    :doc:`/gallery/widgets/polygon_selector_demo`
    FN   c             C   s   t ddddddd}tj| ||||d dgdg | _| _d| _|d krXt d	d
ddd}| j|d< t| j| jf|| _| j	j
| j |d krt d	|jdd	d}t| j	| j| j| j|d| _d| _|| _| j| jjg| _| jd d S )NrD  rF  rE  znot-applicable)r   move_vertexmove_allrG  rH  r9   )r$  rL  r   Fr   r  r   g      ?)rL   r  r   ri  r  rL   )r  r  )r$  r  r   Tr   )rK  rB  r   _xs_ys_polygon_completedr$  r   rA  r*   r   r   r  _polygon_handles_active_handle_idxvertex_select_radiusrY  rN  r   )r   r*   rI  r$  r+  Zmarkerpropsr  rL  r   r   r   r   	  s,    

zPolygonSelector.__init__c             C   sb   | j sd| jkrDt| jdkrD| jj|j|j\}}|| jk rD|| _	| jj
 | jj
  | _| _dS )zButton press event handlerr  r   N)r  rS  r   r  r  r   r   r   r  r  r[  r  _xs_at_press_ys_at_press)r   r$   Zh_idxZh_distr   r   r   r`  	  s    
zPolygonSelector._pressc             C   s   | j dkrd| _ nzt| jdkrP| jd	 | jd krP| jd
 | jd krPd| _n<| j rd| jkrd| jkr| jjd|j | jjd|j | jr| j	| j
 dS )zButton release event handlerr   r   r   Tr  r  Nr   r   r   r   r   )r  r   r  r  r  rS  insertr   r   rI  r  )r   r$   r   r   r   rF   	  s    


zPolygonSelector._releasec             C   s&   | j |s"| j|}| j| dS dS )z'Cursor move event handler and validatorTF)r%   r\  rb  )r   r$   r   r   r   r  	  s
    


zPolygonSelector.onmovec       	      C   s  | j dkrV| j }|j|j | j|< | j|< |dkrR| jrR|j|j | jd< | jd< n"d| jkr| jr|j| jj }|j| jj }x>tt	| jD ],}| j
| | | j|< | j| | | j|< qW n| jsd| jksd| jkrdS | jj j| jd | jd f\}}tj||j ||j }t	| jdkr^|| jk r^| jd | jd  | jd	< | jd
< n|j|j | jd< | jd< | j  dS )zCursor move event handlerr   r   r  r  Nr   r   r   r   r   r   r   )r  r   r   r  r  r  rS  rP  ranger   r  r  rA  Zget_transformr<   r   r  r   r   r  _draw_polygon)	r   r$   idxr  r   r   r   r   Zv0_distr   r   r   rb  
  s*    
$zPolygonSelector._onmovec             C   sJ   | j  rFd| jksd| jkrF| jdd | jdd  | _| _| j  dS )zKey press event handlerr  r  Nr   r   r   )r  rS  r  r  r  )r   r$   r   r   r   rd  '
  s    "zPolygonSelector._on_key_pressc             C   s   | j  rR|j| jjdks,|j| jjdkrR| jj|j | jj|j | j	  nB|j| jjdkr| j
|}|jg|jg | _| _d| _ | jd dS )zKey release event handlerr  r  r   FTN)r  r   rL  r   r  r/   r   r  r   r  r\  r   )r   r$   r   r   r   rf  0
  s    

zPolygonSelector._on_key_releasec             C   s   | j j| j| j | jsNt| jdkrr| jd | jd krr| jd | jd krr| jj| jdd | jdd  n| jj| j| j | j  dS )	z5Redraw the polygon based on the new vertex positions.r   r   r   Nr   r   r   r   )rA  r  r  r  r  r   r  rM  )r   r   r   r   r  B
  s    $zPolygonSelector._draw_polygonc             C   s"   t t| jdd | jdd S )z4The polygon vertices, as a list of ``(x, y)`` pairs.Nr   r   r   )r  r   r  r  )r   r   r   r   r  Q
  s    zPolygonSelector.verts)FNNr  )r   r   r   r   r   r`  rF   r  rb  rd  rf  r  r(   r  r   r   r   r   r  	  s   # 
"&	r  c               @   s*   e Zd ZdZd
ddZdd Zdd	 ZdS )Lassoa  
    Selection curve of an arbitrary shape.

    The selected path can be used in conjunction with
    `~matplotlib.path.Path.contains_point` to select data points from an image.

    Unlike `LassoSelector`, this must be initialized with a starting
    point *xy*, and the `Lasso` events are destroyed upon release.

    Parameters
    ----------
    ax : `~matplotlib.axes.Axes`
        The parent axes for the widget.
    xy : (float, float)
        Coordinates of the start of the lasso.
    callback : callable
        Whenever the lasso is released, the *callback* function is called and
        passed the vertices of the selected path.
    NTc             C   s   t j| | |o| jj| _| jr2| jj| jj| _|\}}||fg| _	t
|g|gdddd| _| jj| j || _| jd| j | jd| j d S )Nr  r   r   )r  rL   ra   r>   r?   )r)   r   r,   r#  r$  r,  r*   r-  r)  r  r   rA  r   r0   r2   r  r  )r   r*   r   r0   r$  r   r   r   r   r   r   l
  s    zLasso.__init__c             C   sh   | j |rd S | jd k	rV| jj|j|jf t| jdkrF| j| j | jjj	| j
 d | _| j  d S )Nr   )r%   r  r/   r   r   r   r0   r*   r   r  rA  r5   )r   r$   r   r   r   r  {
  s    

zLasso.onreleasec             C   s   | j |rd S | jd krd S |j| jkr,d S |jdkr:d S | jj|j|jf | jj	t
t| j  | jr| jj| j | jj| j | jj| jj n
| jj  d S )Nr   )r%   r  rO   r*   r   r/   r   r   rA  r  r  r   r$  r,   r1  r)  r2  r3  r-  r   )r   r$   r   r   r   r  
  s    


zLasso.onmove)NT)r   r   r   r   r   r  r  r   r   r   r   r  W
  s   
r  ))r   
contextlibr   r[  numbersr   numpyr   Z
matplotlibr   r   r   r   r   r   r   Zpatchesr	   r
   r   r   r   r   r   r)   r6   r[   r   r   r   r   r  r4  rB  rg  r  r  r  r  r  r  r   r   r   r   <module>
   sP   &*i      z^r M X9   FK M