o
    iL                     @  s   d Z ddlmZ ddlmZmZ ddlZddlZddl	m
Z
 ddlm  mZ ddlmZ ddlZddlmZ ddlmZ erEddlmZ ejG d	d
 d
ZdddZdd Zdd ZdS )zF
Module consolidating common testing functions for checking plotting.
    )annotations)TYPE_CHECKINGSequenceN)cache_readonly)is_list_like)SeriesAxesc                   @  s   e Zd ZdZdd Zdd Zedd Zedd	 Zd;ddZ	d;ddZ
dd Zd<ddZ	d<d=ddZdd Z	
d>ddZd d! Z	
d?d"d#Zd@d%d&Zd>d'd(Zd)d* Zd+d, ZdAd.d/Z	d;d0d1Zi fd2d3ZdBd5d6Zd7d8 Zd9d: Zd
S )CTestPlotBasezE
    This is a common base class used for various plotting tests
    c                 C  s   dd l }|  d S Nr   )
matplotlib
rcdefaults)selfmpl r   W/var/www/edux/Edux_v2/venv/lib/python3.10/site-packages/pandas/tests/plotting/common.pysetup_method"   s   zTestPlotBase.setup_methodc                 C  s   t   d S N)tmcloser   r   r   r   teardown_method'   s   zTestPlotBase.teardown_methodc                 C  s   dd l m} |S r   )matplotlib.pyplotpyplot)r   pltr   r   r   r   *   s   zTestPlotBase.pltc                 C  s   dd l m} |jS r   )matplotlib.colorscolorscolorConverter)r   r   r   r   r   colorconverter0   s   zTestPlotBase.colorconverterNTc                 C  sf   |r
|du r
t d| |}|D ]}|r(| dusJ | |  | q| du s0J qdS )aQ  
        Check each axes has expected legend labels

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        labels : list-like
            expected legend labels
        visible : bool
            expected legend visibility. labels are checked only when visible is
            True
        Nz-labels must be specified when visible is True)
ValueError_flatten_visible
get_legend_check_text_labels	get_texts)r   axeslabelsvisibleaxr   r   r   _check_legend_labels6   s   
z!TestPlotBase._check_legend_labelsc                 C  sV   |r
|du r
t d|r!| \}}dd |D }||ksJ dS | du s)J dS )aB  
        Check ax has expected legend markers

        Parameters
        ----------
        ax : matplotlib Axes object
        expected_markers : list-like
            expected legend markers
        visible : bool
            expected legend visibility. labels are checked only when visible is
            True
        Nz.Markers must be specified when visible is Truec                 S     g | ]}|  qS r   )
get_marker).0handler   r   r   
<listcomp>^       z5TestPlotBase._check_legend_marker.<locals>.<listcomp>)r   get_legend_handles_labelsr!   )r   r'   expected_markersr&   handles_markersr   r   r   _check_legend_markerM   s   z!TestPlotBase._check_legend_markerc           	      C  s`   |  }|  }t|t|ksJ t||D ]\}}| }| }t|| qt  dS )z
        Check each axes has identical lines

        Parameters
        ----------
        xp : matplotlib Axes object
        rs : matplotlib Axes object
        N)	get_lineslenzip
get_xydatar   assert_almost_equalr   )	r   xprsxp_linesrs_linesxplrslxpdatarsdatar   r   r   _check_datac   s   	zTestPlotBase._check_datac                 C  sB   ddl m} t||st|s|g}|D ]
}| |ksJ qdS )a   
        Check each artist is visible or not

        Parameters
        ----------
        collections : matplotlib Artist or its list-like
            target Artist or its list or collection
        visible : bool
            expected visibility
        r   )
CollectionN)matplotlib.collectionsrC   
isinstancer   get_visible)r   collectionsr&   rC   patchr   r   r   _check_visiblew   s   zTestPlotBase._check_visibler$   Axes | Sequence[Axes]filledboolreturnNonec                 C  s2   |  |}|D ]}|jD ]	}|j|ksJ qqdS )z
        Check for each artist whether it is filled or not

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        filled : bool
            expected filling
        N)r    patchesfill)r   r$   rK   r'   rH   r   r   r   _check_patches_all_filled   s   

z&TestPlotBase._check_patches_all_filledc                   s*   |  }tt||  fdd|jD S )Nc                   s   g | ]} | qS r   r   r+   vmappedr   r   r-      r.   z3TestPlotBase._get_colors_mapped.<locals>.<listcomp>)uniquedictr7   values)r   seriesr   rV   r   rT   r   _get_colors_mapped   s   zTestPlotBase._get_colors_mappedc                 C  s|  ddl m}m}m} ddlm} | j}	|durk|dur)| ||}|dt| }t|t|ks3J t	||D ]2\}
}t
|
|rK|
 }|	|}nt
|
||fr[t|
 d }n|
 }|	|}||ksjJ q8|dur|dur| ||}|dt| }t|t|ksJ t	||D ]+\}
}t
|
|r|
 d }n|
 }t
|tjrt|}|	|}||ksJ qdS dS )a3  
        Check each artist has expected line colors and face colors

        Parameters
        ----------
        collections : list-like
            list or collection of target artist
        linecolors : list-like which has the same length as collections
            list of expected line colors
        facecolors : list-like which has the same length as collections
            list of expected face colors
        mapping : Series
            Series used for color grouping key
            used for andrew_curves, parallel_coordinates, radviz test
        r   )rC   LineCollectionPolyCollection)Line2DN)rD   rC   r[   r\   matplotlib.linesr]   r   rZ   r6   r7   rE   	get_colorto_rgbatupleget_edgecolorget_facecolornpndarray)r   rG   
linecolors
facecolorsmappingrC   r[   r\   r]   convrH   colorresultexpectedr   r   r   _check_colors   s@   



zTestPlotBase._check_colorsc                 C  sb   t |s| |ksJ dS dd |D }t|t|ksJ t||D ]
\}}||ks.J q$dS )a.  
        Check each text has expected labels

        Parameters
        ----------
        texts : matplotlib Text object, or its list-like
            target text, or its list
        expected : str or list-like which has the same length as texts
            expected text label, or its list
        c                 S  r)   r   )get_text)r+   tr   r   r   r-      r.   z3TestPlotBase._check_text_labels.<locals>.<listcomp>N)r   rn   r6   r7   )r   textsrl   r%   labeler   r   r   r"      s   zTestPlotBase._check_text_labelsc           
      C  s  ddl m} | |}|D ]z}|dus|durKt|j |r$| }n
| |jdd }|D ]}	|dur>t|		 | |durJt|	
 | q0|dusS|durt|j |r`| }n
| |jdd }|D ]}	|durzt|		 | |durt|	
 | qlqdS )a  
        Check each axes has expected tick properties

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        xlabelsize : number
            expected xticks font size
        xrot : number
            expected xticks rotation
        ylabelsize : number
            expected yticks font size
        yrot : number
            expected yticks rotation
        r   )NullFormatterNT)minor)matplotlib.tickerrs   r    rE   xaxisget_minor_formatterget_xticklabelsr   r9   get_fontsizeget_rotationyaxisget_yticklabels)
r   r$   
xlabelsizexrot
ylabelsizeyrotrs   r'   r%   rq   r   r   r   _check_ticks_props   s0   


zTestPlotBase._check_ticks_propslinearc                 C  s<   |  |}|D ]}|j |ksJ |j |ksJ qdS )a  
        Check each axes has expected scales

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        xaxis : {'linear', 'log'}
            expected xaxis scale
        yaxis : {'linear', 'log'}
            expected yaxis scale
        N)r    rv   	get_scaler{   )r   r$   rv   r{   r'   r   r   r   _check_ax_scales(  s
   
zTestPlotBase._check_ax_scalesc           	      C  s   ddl m} |du rd}| |}|dur,t||ksJ |D ]}t| dks+J q|dur=| ||}||ks=J t|d j	 t
j|t
jd dS )a  
        Check expected number of axes is drawn in expected layout

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        axes_num : number
            expected number of axes. Unnecessary axes should be set to
            invisible.
        layout : tuple
            expected layout, (expected number of rows , columns)
        figsize : tuple
            expected figsize. default is matplotlib default
        r   flatten_axesN)g@g333333@)dtype)!pandas.plotting._matplotlib.toolsr   r    r6   get_children_get_axes_layoutr   assert_numpy_array_equalfigureget_size_inchesrd   arrayfloat64)	r   r$   axes_numlayoutfigsizer   visible_axesr'   rk   r   r   r   _check_axes_shape9  s   
zTestPlotBase._check_axes_shapec                 C  sV   t  }t  }|D ]}|  }||d d  ||d d  qt|t|fS )Nr      )setget_position
get_pointsaddr6   )r   r$   x_sety_setr'   pointsr   r   r   r   ]  s   zTestPlotBase._get_axes_layoutc                 C  s&   ddl m} ||}dd |D }|S )z
        Flatten axes, and filter only visible

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like

        r   r   c                 S  s   g | ]}|  r|qS r   )rF   )r+   r'   r   r   r   r-   s  s    z1TestPlotBase._flatten_visible.<locals>.<listcomp>)r   r   )r   r$   r   r   r   r   r    g  s   	zTestPlotBase._flatten_visibler   c                 C  sx   |  |}|D ]2}|j}d}d}|D ]}t|dd}	t|dd}
|	r&|d7 }|
r,|d7 }q||ks3J ||ks9J qdS )a  
        Check axes has expected number of errorbars

        Parameters
        ----------
        axes : matplotlib Axes object, or its list-like
        xerr : number
            expected number of x errorbar
        yerr : number
            expected number of y errorbar
        r   has_xerrFhas_yerrr   N)r    
containersgetattr)r   r$   xerryerrr'   r   
xerr_count
yerr_countcr   r   r   r   r   _check_has_errorbarsv  s    
z!TestPlotBase._check_has_errorbarsc                 C  sv  ddl m} t|td}|du r7|du rd}t||| sJ |dkr3t|j|s+J t|jts5J dS dS |du rL| |D ]	}t||sIJ q@dS t|tsSJ t	|
 t	|ks_J | D ]U\}}	t|	|| spJ |dkr|r~|	 |ks~J qc|dkr|r|	j |ksJ t|	j|sJ t|	jtsJ qc|dkr|	d d }
|
j}|r| |ksJ qctdS )	at  
        Check box returned type is correct

        Parameters
        ----------
        returned : object to be tested, returned from boxplot
        return_type : str
            return_type passed to boxplot
        expected_keys : list-like, optional
            group labels in subplot case. If not passed,
            the function checks assuming boxplot uses single ax
        check_ax_title : bool
            Whether to check the ax.title is the same as expected_key
            Intended to be checked by calling from ``boxplot``.
            Normal ``plot`` doesn't attach ``ax.title``, it must be disabled.
        r   r   )rW   r$   bothNrW   r   r$   medians)matplotlib.axesr	   rW   ra   rE   r'   linesr    r   sortedkeysitems	get_titler$   AssertionError)r   returnedreturn_typeexpected_keyscheck_ax_titler	   typesrkeyvalueliner$   r   r   r   _check_box_return_type  sH   z#TestPlotBase._check_box_return_typec                   sb  dd l } fdd}d}|D ]} jddt| | |d7 }|jddd |jdd	|i| | r6J  jddt| | |d7 }|jdd
d |jd|dd| | r]J |dvr jddt| | |d7 }|jdd
d |jdd	|i| | sJ  jddt| | |d7 }|jddd |jd|d
d| | sJ qd S )Nr   c                    sN    j  j }  j  j }tdd | D }tdd |D }|o%| S )Nc                 s      | ]	}|j   V  qd S r   gridlinerF   r+   gr   r   r   	<genexpr>      zHTestPlotBase._check_grid_settings.<locals>.is_grid_on.<locals>.<genexpr>c                 s  r   r   r   r   r   r   r   r     r   )r   gcarv   get_major_ticksr{   all)xticksyticksxoffyoffr   r   r   
is_grid_on  s
   
z5TestPlotBase._check_grid_settings.<locals>.is_grid_onr      r$   F)gridkindT)r   r   )piehexbinscatterr   )r   r   subplotr6   rcplot)r   objkindskwsr   r   spndxr   r   r   r   _check_grid_settings  s6   



z!TestPlotBase._check_grid_settingsrj   c                   s    fdd|d D S )zT
        Auxiliary function for correctly unpacking cycler after MPL >= 1.5
        c                   s   g | ]}|  qS r   r   rR   fieldr   r   r-     r.   z/TestPlotBase._unpack_cycler.<locals>.<listcomp>zaxes.prop_cycler   )r   rcParamsr   r   r   r   _unpack_cycler  s   zTestPlotBase._unpack_cyclerc                 C  "   ddl m} | r|jd S |jS )Nr   mpl_ge_3_5_0x)"pandas.plotting._matplotlib.compatr   _shared_axes_shared_x_axesr   r'   r   r   r   r   
get_x_axis     
zTestPlotBase.get_x_axisc                 C  r   )Nr   r   y)r   r   r   _shared_y_axesr   r   r   r   
get_y_axis  r   zTestPlotBase.get_y_axis)NT)T)r$   rJ   rK   rL   rM   rN   )NNN)NNNN)r   r   )r   r   )rj   )__name__
__module____qualname____doc__r   r   r   r   r   r(   r4   rB   rI   rQ   rZ   rm   r"   r   r   r   r   r    r   r   r   r   r   r   r   r   r   r   r
      s>    





B

0
$


<
)r
   alwaysFc           
      K  s  ddl m} |rt}nt}d}t f t| zPz:|d| }|	  || |fi |D ]}t
| q0t
jdd}|| W d   n1 sNw   Y  W n tyb }	 z|	d}	~	ww W t
| nt
| w |W  d   S 1 s|w   Y  dS )aT  
    Create plot and ensure that plot return object is valid.

    Parameters
    ----------
    f : func
        Plotting function.
    filterwarnings : str
        Warnings filter.
        See https://docs.python.org/3/library/warnings.html#warning-filter
    default_axes : bool, optional
        If False (default):
            - If `ax` not in `kwargs`, then create subplot(211) and plot there
            - Create new subplot(212) and plot there as well
            - Mind special corner case for bootstrap_plot (see `_gen_two_subplots`)
        If True:
            - Simply run plotting function with kwargs provided
            - All required axes instances will be created automatically
            - It is recommended to use it when the plotting function
            creates multiple axes itself. It helps avoid warnings like
            'UserWarning: To output multiple subplots,
            the figure containing the passed axes is being cleared'
    **kwargs
        Keyword arguments passed to the plotting function.

    Returns
    -------
    Plot object returned by the last plotting.
    r   Nr   T)return_filelike)r   r   _gen_default_plot_gen_two_subplotswarningscatch_warningssimplefiltergetgcfclfr   "assert_is_valid_plot_return_objectensure_cleansavefig	Exceptionr   )
ffilterwarningsdefault_axeskwargsr   	gen_plotsretfigpatherrr   r   r   _check_plot_works  s0   

$r  c                 k  s    | di |V  dS )z'
    Create plot in a default way.
    Nr   r   r   r   r   r   r   r   r   E  s   r   c                 k  s`    d|vr
| d | di |V  | tjju rd|vsJ n| d|d< | di |V  dS )z9
    Create plot on two subplots forcefully created.
    r'         Nr   )add_subplotpdplottingbootstrap_plotr  r   r   r   r   L  s   
r   )r   F)r   
__future__r   typingr   r   r   numpyrd   pandas.util._decoratorsr   pandas.util._test_decoratorsutil_test_decoratorstdpandas.core.dtypes.apir   pandasr  r   pandas._testing_testingr   r   r	   skip_if_no_mplr
   r  r   r   r   r   r   r   <module>   s*       
q: