o
    g/c                     @   s  d Z ddlZddlZddlZddlZddlZddlmZmZ ddl	Z
ddlmZ ddlZddlZddlmZ ddlmZ ddlmZ g dZdd Zd	d
 ZdEddZdd Zdd Zdd ZdFddZ dd Z!dd Z"dd Z#		dGddZ$d d! Z%d"d# Z&dHd$d%Z'dId'd(Z(d)d* Z)d+d, Z*d-d. Z+dHd/d0Z,dJd1d2Z-d3d4 Z.d5d6 Z/d7d8 Z0d9d: Z1d;d< Z2d=d> Z3d?d@ Z4dAdB Z5dCdD Z6dS )Kz+Utility functions, mostly for internal use.    N)urlopenurlretrieve)stats)normalize_kwargs)
desaturatesaturateset_hls_valuesmove_legenddespineget_dataset_namesget_data_homeload_datasetc                 O   sD   d}t | z	| j|i |W S  ty!   | j|i | Y S w )z=Wrapper to handle different pandas sorting API pre/post 0.17.CThis function is deprecated and will be removed in a future version)warningswarnsort_valuesAttributeErrorsort)dfargskwargsmsg r   K/home/ubuntu/cloudmapper/venv/lib/python3.10/site-packages/seaborn/utils.pysort_df   s   
r   c           	      C   sr   t | dd} t |}g }tt | D ]\}\}}|| }|| }|| }|||g qt |j}|S )a  Convert intervals to error arguments relative to plot heights.

    Parameters
    ----------
    cis : 2 x n sequence
        sequence of confidence interval limits
    heights : n sequence
        sequence of plot heights

    Returns
    -------
    errsize : 2 x n array
        sequence of error size relative to height values in correct
        format as argument for plt.bar

       )	np
atleast_2dreshape
atleast_1d	enumerate	transposeappendasarrayT)	cisheightserrsizeilowhighhelowehighr   r   r   ci_to_errsize    s   
r/   
   c                 C   sN   d}t |t t| |\}}||  }|d |d  }|dd ||fS )a  Return arguments to plt.bar for pmf-like histogram of an array.

    DEPRECATED: will be removed in a future version.

    Parameters
    ----------
    a: array-like
        array to make histogram of
    bins: int
        number of bins

    Returns
    -------
    x: array
        left x position of bars
    h: array
        height of bars
    w: float
        width of bars

    r      r   Nr   )r   r   FutureWarningr   	histogramsum)abinsr   nxr,   wr   r   r   pmf_hist>   s   r:   c                 C   s@   | j   | jrz| | j   W dS  ty   Y dS w dS )z>Force draw of a matplotlib figure, accounting for back-compat.N)canvasdrawstaleget_rendererr   )figr   r   r   _draw_figure\   s   
r@   c                 C   sZ   d|  krdkst d t dtj| }tj| \}}}||9 }t|||}|S )al  Decrease the saturation channel of a color by some percent.

    Parameters
    ----------
    color : matplotlib color
        hex, rgb-tuple, or html color name
    prop : float
        saturation channel of color will be multiplied by this value

    Returns
    -------
    new_color : rgb tuple
        desaturated color code in RGB tuple representation

    r   r1   zprop must be between 0 and 1)
ValueErrormplcolcolorConverterto_rgbcolorsys
rgb_to_hls
hls_to_rgb)colorproprgbr,   ls	new_colorr   r   r   r   g   s   r   c                 C   s   t | ddS )a
  Return a fully saturated color with the same hue.

    Parameters
    ----------
    color : matplotlib color
        hex, rgb-tuple, or html color name

    Returns
    -------
    new_color : rgb tuple
        saturated color code in RGB tuple representation

    r1   )rL   )r   )rH   r   r   r   r      s   r   c                 C   sP   t j| }ttj| }t|||gD ]\}}|dur |||< qtj| }|S )an  Independently manipulate the h, l, or s channels of a color.

    Parameters
    ----------
    color : matplotlib color
        hex, rgb-tuple, or html color name
    h, l, s : floats between 0 and 1, or None
        new values for each channel in hls space

    Returns
    -------
    new_color : rgb tuple
        new color code in RGB tuple representation

    N)rB   rC   rD   listrE   rF   r!   rG   )rH   r,   rK   rL   rJ   valsr)   valr   r   r   r      s   
r   c                 K   s@   d}t |t t }|j| fi | |j|fi | dS )z[Grab current axis and label it.

    DEPRECATED: will be removed in a future version.

    r   N)r   r   r2   pltgca
set_xlabel
set_ylabel)xlabelylabelr   r   axr   r   r   axlabel   s
   rX   c                 C   s   | t |  S )aG  Helper method for removing null values from data vectors.

    Parameters
    ----------
    vector : vector object
        Must implement boolean masking with [] subscript syntax.

    Returns
    -------
    clean_clean : same type as ``vector``
        Vector of data with null values removed. May be a copy or a view.

    )pdnotnull)vectorr   r   r   	remove_na   s   r\   c                  C   s&   t jd } d| jv r|  d S dgS )a	  Return the list of colors in the current matplotlib color cycle

    Parameters
    ----------
    None

    Returns
    -------
    colors : list
        List of matplotlib colors in the current cycle, or dark gray if
        the current color cycle is empty.
    zaxes.prop_cyclerH   z.15)mplrcParamskeysby_key)cyclerr   r   r   get_color_cycle   s   
rb   TFc              
   C   s  | du r|du rt  j}n| dur| j}n|dur|g}|D ]H}	dD ]4}
t |
  }|	j|
 | |durX|rXz||
d}W n tyM   |}Y nw |	j|
 d|f q$|r|st	dd |	j
jD }t	dd |	j
jD }|	j
d |	j
jD ]}|j| q}|	j
jD ]}|j| q|r|st	d	d |	jjD }t	d
d |	jjD }|	jd |	jjD ]}|j| q|	jjD ]}|j| q|rht|	 }|jrt|t|	 k|d }t|t|	 k|d }|	jd || |	jd || |||k}|||k}|	| t|	 }|jrht|t|	 k|d }t|t|	 k|d }|	jd || |	jd || |||k}|||k}|	| qdS )a  Remove the top and right spines from plot(s).

    fig : matplotlib figure, optional
        Figure to despine all axes of, defaults to the current figure.
    ax : matplotlib axes, optional
        Specific axes object to despine. Ignored if fig is provided.
    top, right, left, bottom : boolean, optional
        If True, remove that spine.
    offset : int or dict, optional
        Absolute distance, in points, spines should be moved away
        from the axes (negative values move spines inward). A single value
        applies to all spines; a dict can be used to set offset values per
        side.
    trim : bool, optional
        If True, limit spines to the smallest and largest major tick
        on each non-despined axis.

    Returns
    -------
    None

    N)toprightleftbottomr   outwardc                 s       | ]}|j  V  qd S N	tick1lineget_visible.0tr   r   r   	<genexpr>  
    
zdespine.<locals>.<genexpr>c                 s   rh   ri   rj   rm   r   r   r   rp     rq   rd   c                 s   rh   ri   rj   rm   r   r   r   rp   "  rq   c                 s   rh   ri   rj   rm   r   r   r   rp   &  rq   rc   r   rf   re   )rQ   gcfaxeslocalsspinesset_visiblegetr   set_positionanyyaxis
majorTicks
minorTicksset_ticks_position	tick2linexaxisr   r$   
get_xtickssizecompressminget_xlimmax
set_bounds
set_xticks
get_yticksget_ylim
set_yticks)r?   rW   rc   rd   re   rf   offsettrimrs   ax_iside
is_visiblerP   maj_onmin_onro   xticks	firstticklastticknewticksyticksr   r   r   r
      s   


r
   c                    s  ddl m} t| |r| j}| jj}n*t| tjjr!| j}| j}nt| tjj	r7| j
r1| j
d }nd}| j}nd}t||du rJ|  d}t||j}dd | D }ttjjj  fd	d
|  D }	|	d |	d}
d|v r|
|d dd
 | D }| D ]\}}|
jdi |dd |i || q|d|j  |	| |  |||fd|i|	}||
 |
  t| |r|| _ dS dS )a<  
    Recreate a plot's legend at a new location.

    The name is a slight misnomer. Matplotlib legends do not expose public
    control over their position parameters. So this function creates a new legend,
    copying over the data from the original object, which is then removed.

    Parameters
    ----------
    obj : the object with the plot
        This argument can be either a seaborn or matplotlib object:

        - :class:`seaborn.FacetGrid` or :class:`seaborn.PairGrid`
        - :class:`matplotlib.axes.Axes` or :class:`matplotlib.figure.Figure`

    loc : str or int
        Location argument, as in :meth:`matplotlib.axes.Axes.legend`.

    kwargs
        Other keyword arguments are passed to :meth:`matplotlib.axes.Axes.legend`.

    Examples
    --------

    .. include:: ../docstrings/move_legend.rst

    r   )Gridr   NzC`obj` must be a seaborn Grid or matplotlib Axes or Figure instance.z has no legend attached.c                 S      g | ]}|  qS r   )get_textrm   r   r   r   
<listcomp>      zmove_legend.<locals>.<listcomp>c                    s   i | ]\}}| v r||qS r   r   rn   kv
legend_kwsr   r   
<dictcomp>  s    zmove_legend.<locals>.<dictcomp>bbox_to_anchortitlec                 S   s    i | ]\}}| d r||qS )title_)
startswithr   r   r   r   r     s        frameonlocr   )!seaborn.axisgridr   
isinstancelegendfigurer]   rs   Axeslegend_Figurelegends	TypeErrorrA   legendHandles	get_textsinspect	signatureLegend
parameters
propertiesitemspopset_textset
setdefaultlegendPatchrl   updateremove	set_titler   get_fontproperties_legend)objr   r   r   
old_legendlegend_funcerrhandleslabelspropsr   title_kwargskeyrP   
new_legendr   r   r   r	   K  sJ    







r	   c                 C   sF   t |  ||  |d }t|   ||  |d }t|||}|S )z0Establish support for a kernel density estimate.r   r1   )r   r   r   linspace)databwgridsizecutclipsupport_minsupport_maxsupportr   r   r   _kde_support  s   r   c           	      C   s   d}t |t g }zt|}W n ty   |g}d}Y nw t|D ]\}}|du r4t|  |}n	t	
tj|| |}|| q#t	|}|sN| }|S )a  Like scoreatpercentile but can take and return array of percentiles.

    DEPRECATED: will be removed in a future version.

    Parameters
    ----------
    a : array
        data
    pcts : sequence of percentile values
        percentile or percentiles to find score at
    axis : int or None
        if not None, computes scores over this axis

    Returns
    -------
    scores: array
        array of scores at requested percentiles
        first dimension is length of object passed to ``pcts``

    r   r   N)r   r   r2   lenr   r!   r   scoreatpercentileravelr   apply_along_axisr#   r$   squeeze)	r5   pctsaxisr   scoresr7   r)   pscorer   r   r   percentiles  s$   
r   _   c                 C   s&   d|d  d|d  f}t | ||S )z2Return a percentile range from an array of values.2   r   )r   nanpercentile)r5   whichr   r   r   r   r   ci  s   r   c                 C   sD   d}t |t | dk rdS | dk rdS | dk rdS | dk r d	S d
S )z{Return a R-style significance string corresponding to p values.

    DEPRECATED: will be removed in a future version.

    r   gMbP?z***g{Gz?z**g?*g?. )r   r   r2   )r   r   r   r   r   	sig_stars  s   r   c                 C   s:   d}t |t t| } t| d}t| d}|| S )zfCalculate the IQR for an array of numbers.

    DEPRECATED: will be removed in a future version.

    r      K   )r   r   r2   r   r$   r   r   )r5   r   q1q3r   r   r   iqr  s   
r   c                  C   sL   d} t | }| }W d   n1 sw   Y  d}t|| }|S )zkReport available example datasets, useful for reporting issues.

    Requires an internet connection.

    z'https://github.com/mwaskom/seaborn-dataNz+/mwaskom/seaborn-data/blob/master/(\w*).csv)r   readrefindalldecode)urlresphtmlpatdatasetsr   r   r   r     s   

r   c                 C   sF   | du rt jdt jdd} t j| } t j| s!t |  | S )a  Return a path to the cache directory for example datasets.

    This directory is then used by :func:`load_dataset`.

    If the ``data_home`` argument is not specified, it tries to read from the
    ``SEABORN_DATA`` environment variable and defaults to ``~/seaborn-data``.

    NSEABORN_DATA~zseaborn-data)osenvironrw   pathjoin
expanduserexistsmakedirs)	data_homer   r   r   r     s   	
r   c           
      K   s<  t | tjrd}t|d|  d}|r<tjt|tj|}tj	|s9| t
 vr4td|  dt|| |}n|}tj|fi |}|jd   rW|jdd }| dkrt|d	 g d
|d	< t|d ddg|d< t|d ddg|d< t|d ddg|d< | dkr|d jdd }	t|	|	 |d< | dkrt|d g d|d< t|d g d|d< t|d ddg|d< | dkrt|d g d |d< t|d! td"|d!< | d#kr|d j |d< | d$krt|d% g d&|d%< t|d' g d(|d'< t|d) g d*|d)< |S )+a  Load an example dataset from the online repository (requires internet).

    This function provides quick access to a small number of example datasets
    that are useful for documenting seaborn or generating reproducible examples
    for bug reports. It is not necessary for normal usage.

    Note that some of the datasets have a small amount of preprocessing applied
    to define a proper ordering for categorical variables.

    Use :func:`get_dataset_names` to see a list of available datasets.

    Parameters
    ----------
    name : str
        Name of the dataset (``{name}.csv`` on
        https://github.com/mwaskom/seaborn-data).
    cache : boolean, optional
        If True, try to load from the local cache first, and save to the cache
        if a download is required.
    data_home : string, optional
        The directory in which to cache data; see :func:`get_data_home`.
    kws : keys and values, optional
        Additional keyword arguments are passed to passed through to
        :func:`pandas.read_csv`.

    Returns
    -------
    df : :class:`pandas.DataFrame`
        Tabular data, possibly with some preprocessing applied.

    zThis function accepts only strings (the name of an example dataset). You passed a pandas DataFrame. If you have your own dataset, it is not necessary to use this function before plotting.z>https://raw.githubusercontent.com/mwaskom/seaborn-data/master/z.csv'z%' is not one of the example datasets.r   Ntipsday)ThurFriSatSunsexMaleFemaletimeLunchDinnersmokerYesNoflightsmonth   exercise)z1 minz15 minz30 minkind)restwalkingrunningdietzno fatzlow fattitanicclass)FirstSecondThirddeckABCDEFGpenguinsdiamondsrH   )DEFGHIJclarity)IFVVS1VVS2VS1VS2SI1SI2I1r   )IdealPremiumz	Very GoodGoodFair)r   rY   	DataFramer   r   r   r   r   basenamer  r   rA   r   read_csvilocisnullallCategoricalstruniquerN   r   )
namecacher  kwsr   r   
cache_path	full_pathr   monthsr   r   r   r   "  sX   #


r   c                    sL   | sdS zdd | D   fdd D }t |dkW S  ty%   Y dS w )zReturn a boolean for whether the list of ticklabels have overlaps.

    Parameters
    ----------
    labels : list of matplotlib ticklabels

    Returns
    -------
    overlap : boolean
        True if any of the labels overlap.

    Fc                 S   r   r   )get_window_extentrn   rK   r   r   r   r     r   z+axis_ticklabels_overlap.<locals>.<listcomp>c                    s   g | ]}|  qS r   )count_overlaps)rn   bbboxesr   r   r     s    r1   )r   RuntimeError)r   overlapsr   rM  r   axis_ticklabels_overlap  s   rQ  c                 C   s   t |  t |  fS )zReturn booleans for whether the x and y ticklabels on an Axes overlap.

    Parameters
    ----------
    ax : matplotlib Axes

    Returns
    -------
    x_overlap, y_overlap : booleans
        True when the labels on that axis overlap.

    )rQ  get_xticklabelsget_yticklabels)rW   r   r   r   axes_ticklabels_overlap  s   

rT  c                    s   | j  |}fdd|D }G fddd}t| tjjr'tj  ntj  |  _ 	|  fdd|D }||fS )z=Return levels and formatted levels for brief numeric legends.c                    s(   g | ]}| d  kr| d kr|qS )r   r1   r   rJ  limitsr   r   r     s   ( z-locator_to_legend_entries.<locals>.<listcomp>c                       s   e Zd Z fddZdS )z-locator_to_legend_entries.<locals>.dummy_axisc                    s    S ri   r   )selfrU  r   r   get_view_interval  s   z?locator_to_legend_entries.<locals>.dummy_axis.get_view_intervalN)__name__
__module____qualname__rX  r   rU  r   r   
dummy_axis  s    r\  c                    s   g | ]} |qS r   r   )rn   r8   )	formatterr   r   r     r   )
tick_valuesastyper   r]   ticker
LogLocatorLogFormatterScalarFormatterr   set_locs)locatorrV  dtype
raw_levelsr\  formatted_levelsr   )r]  rV  r   locator_to_legend_entries  s   

ri  c                 C   sp   t jj| ddddf }t|dk|d |d d d }|g d}z| W S  ty7   | Y S w )	a  Calculate the relative luminance of a color according to W3C standards

    Parameters
    ----------
    color : matplotlib color or sequence of matplotlib colors
        Hex code, rgb-tuple, or html color name.

    Returns
    -------
    luminance : float(s) between 0 and 1

    Nr  g#?gףp=
)@g)\(?gzG?g333333@)gz6?g,C?g]m{?)	r]   colorsrC   to_rgba_arrayr   wheredotitemrA   )rH   rJ   lumr   r   r   relative_luminance  s   "
rp  c                 C   s8   t | tr| S z| jddW S  ty   t|  Y S w )a  Return a string representing a Python object.

    Strings (i.e. type ``str``) are returned unchanged.

    Byte strings (i.e. type ``bytes``) are returned as UTF-8-decoded strings.

    For other objects, the method ``__str__()`` is called, and the result is
    returned as a string.

    Parameters
    ----------
    obj : object
        Any Python object

    Returns
    -------
    s : str
        UTF-8-decoded string representation of ``obj``

    zutf-8)encoding)r   rA  r   r   )r   r   r   r   to_utf8  s   
rr  c              
   C   sZ   dgdgdgdgdgdgdgdgd	gd
	}zt | |} W | S  ty,   t | |} Y | S w )z>Wrapper for mpl.cbook.normalize_kwargs that supports <= 3.2.1.clwlsfcecmfcmecmewms)	rH   	linewidth	linestyle	facecolor	edgecolormarkerfacecolormarkeredgecolormarkeredgewidth
markersize)r   r   )rE  artist
_alias_mapr   r   r   _normalize_kwargs  s"   r  c                 C   s(   ||vrt d|  d| d| ddS )z+Raise if value for param is not in options.`z` must be one of z, but z was passed.`N)rA   )paramoptionsvaluer   r   r   _check_argument  s
   r  c                 C   sD   t |j}t |j}|D ]}||v r|| vr|| j| |< q| S )zBAssign default kwargs for call_func using values from source_func.)r   r   r   default)rE  	call_funcsource_funcneededdefaultsr  r   r   r   _assign_default_kwargs  s   	r  c                 C   s   t jdd}| tjjd  }|D ]*}| \}}| }tdd |D s>|	d | D ]}|dur=|
| q2qdS )z@Make invisible-handle "subtitles" entries look more like titles.zlegend.title_fontsizeNr   c                 s   s    | ]}|  V  qd S ri   )rl   )rn   r  r   r   r   rp   1  s    z*adjust_legend_subtitles.<locals>.<genexpr>)rQ   r^   rw   findobjr]   	offsetboxVPackerget_childrenr?  	set_widthset_size)r   	font_sizehpackershpack	draw_area	text_arear   textr   r   r   adjust_legend_subtitles)  s   

r  )r0   )NNN)NNTTFFNFri   )r   N)TN)7__doc__r   r   r   r   rE   urllib.requestr   r   numpyr   scipyr   pandasrY   
matplotlibr]   matplotlib.colorsrj  rB   matplotlib.pyplotpyplotrQ   matplotlib.cbookr   __all__r   r/   r:   r@   r   r   r   rX   r\   rb   r
   r	   r   r   r   r   r   r   r   r   rQ  rT  ri  rp  rr  r  r  r  r  r   r   r   r   <module>   s\    

#

fZ
	
*

b