U
    md                  #   @   s.  d dl Z d dlmZ d dlmZ d dlmZ d dlmZm	Z	m
Z
mZmZmZmZ d dlZd dlZd dlZd dlmZ d dlmZmZmZmZ d dlmZ d dlmZ d d	lmZ m!Z! d d
l"m#Z# d dl$m%Z% d dl&m'Z'm&Z& ddl(m)Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl(m1Z1 ee2ee3df f Z4e.d Z5e.d Z6e.d Z7ee2e3ee
e3 ge3f f Z8G dd deej9Z:dddZ;dd Z<dej=ee
e2 e'df ee d$d%d&Z>dej=ee2 d'd(d)Z?d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdL"Z@ddMdNZAde2eeB eeC e2eeBe2df dOdPdQZDdee
e2 e'df e'dRdSdTZEdUdV ZFee2e
e2 e'f dWdXdYZGdZd[ ZHdd]d^ZIdd_d`ZJddadbZKddedfZLdeee
e f e.di djdkdlZMdej=e.di eee	e f dpdqdrZNeej=dsdtduZOdeej=e
eC dvdwdxZPdydz ZQd{d| ZRd}d~ ZSdddZTdd ZUdddZVee!dddZWee3dddZXeej=dddZYeej=dddZZdd Z[dddZ\deeeCeCf e:f eCeCee3 ee3 ee
e3  ee
e3  ee!ej]f dddZ^dd Z_ej`e2dddZadddZbdS )    N)ABC)	lru_cache)UnionListSequenceTuple
CollectionOptionalCallable)pyplot)rcParamstickergridspecaxes)Axes)is_color_like)SubplotParamsFigureCircle)PatchCollection)Cyclercycler   )logging)settings)Literal)NeighborsView   )palettes.)fafrrtZrt_circularZdrlZeq_tree.)ZlightnormalmediumZsemiboldboldZheavyblack)zxx-smallzx-smallZsmallr$   Zlargezx-largezxx-largec                   @   s   e Zd ZdZdS )_AxesSubplotz>Intersection between Axes and SubplotBase: Has methods of bothN)__name__
__module____qualname____doc__ r,   r,   O/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scanpy/plotting/_utils.pyr'   #   s   r'         ?c                 C   s   |
dkrt  }
|
j| |d}|dk	r0|
| |dk	rB|
| |dk	rT|
| |dk	rt|
jtt||dd |dk	r|
	tt|| t j
|||
d td||	d dS )zPlot a matrix.N)cmapvertical)Zrotation)shrinkaxmatrix)showsave)plZgcaimshow
set_xlabel
set_ylabel	set_title
set_xticksrangelen
set_ytickscolorbarsavefig_or_show)r3   xlabelylabelZxticksytickstitleZcolorbar_shrink	color_mapr4   r5   r2   imgr,   r,   r-   r3   ,   s&    


  r3   c                 K   s:   t jtdd td D tddddd t| f| d	S )
zPlot X. See timeseries_subplot.c                 s   s   | ]}d | V  qdS )r   Nr,   ).0sr,   r,   r-   	<genexpr>P   s     ztimeseries.<locals>.<genexpr>figure.figsizegQ?g\(\?gp=
ף?leftrightbottomfigsizeZsubplotparsN)r6   figuretupler   spparstimeseries_subplot)Xkwargsr,   r,   r-   
timeseriesM   s
    rW   r,    gene expressionTviridis)rU   paletter2   c                    s  dk	rt d ttjf}t|
}
|dkr<t jd n| jdkrZ dddf   jd dkr|
d jd   d } fddt	 jd D }nh|rĈg} dddf fg}nFtj
dd\}}t|
dt|  d } fd	d|D }|dkrt }t|D ]J\}\}}|j||d
dtd || t|dkr^|| nd|tjd	 q$| }|D ](}|j||g|d |d gddd q||| |dk	r|| || || |dk	r|| t|dkr|	r|jdd dS )z    Plot X.

    Parameters
    ----------
    X
        Call this with:
        X with one column, color categorical.
        X with one column, color continuous.
        X with n columns, color is of length n.
    Nr   r   colorc                    s    g | ]} d d |f fqS Nr,   rG   i)rU   x_ranger,   r-   
<listcomp>y   s     z&timeseries_subplot.<locals>.<listcomp>T)Zreturn_inversec                    s,   g | ]$}|k  |kd d f fqS r]   r,   )rG   levelrU   r\   r`   r,   r-   ra      s     .facezlines.markersizerX   )markerZ	edgecolorrH   clabelr/   
rasterized--r&   r\   F)Zframeon)
isinstancefloatnpZfloatingdefault_palettearangeshapendimby_keyr<   uniquearrayr=   r6   Zsubplot	enumeratescatterr   r   _vector_friendlyget_ylimplotset_ylimset_xlimr8   r9   r>   legend)rU   timer\   	var_nameshighlights_xrA   rB   rC   xlimr}   r[   rE   r2   Zuse_color_mapcolorsZsubsetslevels_r_   xyylimhr,   rc   r-   rT   V   sR    
 

&






rT   )rU   r   c           	      C   s   t |dkrt| jd }|jdkr6|dddf }| j} t| }tj	dd\}}|j
tj| tjddd	|d
}tj|dd tt| jd | |D ]$}tj||gd| jd gddd qtd| jd d g td| jd d g dS )z    Plot timeseries as heatmap.

    Parameters
    ----------
    X
        Data array.
    var_names
        Array of strings naming variables stored in columns of X.
    r   r   r   N)g      @   rP   )dtypeautoZnearest)Zaspectinterpolationr/   r.   )r1   rj   r&   rk   )r=   rn   rp   rq   rr   Tminrv   r6   Zsubplotsr7   ru   Zfloat_r?   rC   r<   rz   r   r   )	rU   r   r   rE   Zmin_xr   r2   rF   r   r,   r,   r-   timeseries_as_heatmap   s&    

"r   z#eec900z#cd2626z#eee685z#9fb6cdz#7ccd7cz#ee5c42z#ccccccz#e5e5e5z#8b7e66z#a6a6a6z#1a1a1az#333333z#7f7f7fz#4d4d4dz#666666z#eedfccz#c4c4c4z#8b8989z#66cd00z#8b8b00z#bcee68z#9acd32z#c1cdcdz#d02090z#8968cdz#551a8bz#2e8b57z#9ac0cdz#b452cdz#cd5555z#999999z#e066ffz#cd96cdz#cd6889)"Zgold2Z
firebrick3Zkhaki2Z
slategray3Z
palegreen3Ztomato2Zgrey80Zgrey90wheat4Zgrey65Zgrey10Zgrey20grey50grey30Zgrey40Zantiquewhite2Zgrey77Zsnow4chartreuse3yellow4Zdarkolivegreen2Z
olivedrab3Zazure3Z	violetredZmediumpurple3purple4Z	seagreen4Z
lightblue3Zorchid3zindianred 3Zgrey60Zmediumorchid1plum3Zpalevioletred3c                 C   s   |dkrBt td ts:td dk r:tjrBtd dt_ntd }tjjddd |dkr`tj	}tj|  tj
 d|  }td	|  tj||d
d dS )zSave current figure to file.

    The `filename` is generated as follows:

        filename = settings.figdir / (writekey + settings.plot_suffix + '.' + settings.file_format_figs)
    Nzsavefig.dpi   zYou are using a low resolution (dpi<150) for saving figures.
Consider running `set_figure_params(dpi_save=...)`, which will adjust `matplotlib.rcParams['savefig.dpi']`FT)parentsexist_okrd   zsaving figure to file Ztight)dpiZbbox_inches)rl   r   strr   Z_low_resolution_warningloggwarningZfigdirmkdirZfile_format_figsZplot_suffixr6   savefig)writekeyr   extfilenamer,   r,   r-   r     s"    
r   )r   r4   r   r   r5   c                 C   s   t |trN|d krBdD ]*}||r|dd  }||d} qBq| |7 } d}|d kr\tjn|}|d krntjn|}|rt| ||d |rt	  |rt
  d S )N)z.svgz.pdfz.pngr   rX   T)r   r   )rl   r   endswithreplacer   ZautosaveZautoshowr   r6   r4   close)r   r4   r   r   r5   Ztry_extr,   r,   r-   r@   #  s"    

r@   )r[   returnc                 C   s,   | d krt d S t| ts$t| dS | S d S )Naxes.prop_cyclerk   )r   rl   r   r   r[   r,   r,   r-   ro   ?  s
    

ro   c                 C   s   g }| d}| j | D ]R}t|s`|tkr6t| }n*td| d| d t| | d} ql|| q|dk	rt|t| j | kr|| j |< dS )a3  
    checks if the list of colors in adata.uns[f'{key}_colors'] is valid
    and updates the color list in adata.uns[f'{key}_colors'] if needed.

    Not only valid matplotlib colors are checked but also if the color name
    is a valid R color name, in which case it will be translated to a valid name
    _colorsz.The following color value found in adata.uns['z_colors'] is not valid: 'z''. Default colors will be used instead.N)unsr   additional_colorsr   r   '_set_default_colors_for_categorical_obsappendlist)adatakeyZ_palette	color_keyr\   r,   r,   r-   _validate_paletteH  s    	


r   r   c                    sf  ddl m | j| jj}ttr`t kr`t	}fdd|t
ddt|D }nttjrfdd|D }nttjr
tt|k rtdt dt| d	 g }D ]6}t|s|tkrt| }ntd
| || qt|dttstddjkr2td   fddtt|D }|| j|d < dS )a  
    Sets the adata.uns[value_to_plot + '_colors'] according to the given palette

    Parameters
    ----------
    adata
        annData object
    value_to_plot
        name of a valid categorical observation
    palette
        Palette should be either a valid :func:`~matplotlib.pyplot.colormaps` string,
        a sequence of colors (in a format that can be understood by matplotlib,
        eg. RGB, RGBS, hex, or a cycler object with key='color'

    Returns
    -------
    None
    r   to_hexc                    s   g | ]} |qS r,   r,   rG   r   r   r,   r-   ra     s     z3_set_colors_for_categorical_obs.<locals>.<listcomp>r   c                    s   g | ]} | d dqS )T)Z
keep_alphar,   )rG   k)r[   r   r,   r-   ra     s     zSLength of palette colors is smaller than the number of categories (palette length: z, categories length: z+. Some categories will have the same color.z=The following color value of the given palette is not valid: rk   zPlease check that the value of 'palette' is a valid matplotlib colormap string (eg. Set2), a  list of color names or a cycler with a 'color' key.r\   z#Please set the palette key 'color'.c                    s   g | ]}t  d  qS rk   nextr   )ccr   r,   r-   ra     s     r   N)matplotlib.colorsr   obscat
categoriesrl   r   r6   Z	colormapsZget_cmaprn   Zlinspacer=   cabcMappingr   r   r   r   r   
ValueErrorr   r   r   keysr<   r   )r   value_to_plotr[   r   r/   Zcolors_listZ_color_listr\   r,   )r   r[   r   r-   _set_colors_for_categorical_obsh  s>    
&

r   c                    s   | j | jj}t|}ttd  d |krPtd    fddt|D }nZ|dkr`tj}nJ|dkrptj	}n:|ttj
krtj
}n$dd t|D }td|d	 t| ||d
|  d
S )z
    Sets the adata.uns[value_to_plot + '_colors'] using default color palettes

    Parameters
    ----------
    adata
        AnnData object
    value_to_plot
        Name of a valid categorical observation

    Returns
    -------
    None
    r   r\   c                    s   g | ]}t  d  qS rk   r   rG   r   r   r,   r-   ra     s     z;_set_default_colors_for_categorical_obs.<locals>.<listcomp>      c                 S   s   g | ]}d qS )greyr,   r   r,   r,   r-   ra     s     zthe obs value zT has more than 103 categories. Uniform 'grey' color will be used for all categories.N)r   r   r   r=   r   rs   r<   r   Z
default_20Z
default_28Zdefault_102r   infor   )r   r   r   lengthr[   r,   r   r-   r     s     

r   Fc                 C   sh   | d}t | j| jj}|r2|r2t| || n2|| jkrZt | j| |krZt| | n
t| | d S )Nr   )r=   r   r   r   r   r   r   r   )r   r   r[   Zforce_update_colorsr   Zcolors_neededr,   r,   r-   ,add_colors_for_categorical_sample_annotation  s    
r   c              	   C   s   dd l }t| tjs| g} |d kr&d}||jkr8tdt||}||d }t||}	t	
 J t	d | D ]4}
|j||j|	 |
||d}|d |tj qrW 5 Q R X d S )Nr   	neighborsz6`edges=True` requires `pp.neighbors` to be run before.Zconnectivitiesignore)r2   widthZ
edge_color)networkxrl   r   r   r   r   r   Graph
_get_basiswarningscatch_warningssimplefilterZdraw_networkx_edgesobsmZ
set_zorderZset_rasterizedr   rx   )axsr   basisZedges_widthZedges_colorZneighbors_keynxr   g	basis_keyr2   Zedge_collectionr,   r,   r-   
plot_edges  s,    





r   c           
         s   t | tjs| g} t fdddD d }|d krJtd d d|dkr\td t } j| } j| d	  }| D ]b}|d k	r|ni }	|j	|d d d
f |d d df |d d d
f |d d df f|	dt
ji qd S )Nc                 3   s&   | ]}| d   j kr|V  qdS )r   N)r   )rG   pr   r   r,   r-   rI     s      zplot_arrows.<locals>.<genexpr>)velocityDeltaz"`arrows=True` requires `'velocity_z'` from scvelo or `'Delta_z'` from velocyto.r   zpThe module `scvelo` has improved plotting facilities. Prefer using `scv.pl.velocity_embedding` to `arrows=True`.r   r   r   ri   )rl   r   r   r   r   r   r   r   r   Zquiverr   rx   )
r   r   r   Zarrows_kwdsZv_prefixr   rU   Vr2   Zquiver_kwdsr,   r   r-   plot_arrows  s:     

r   2d   c              
   C   s   |j | jj| |j | jk}|j|d  | }	t|	d ts`ddlm}
 |
|j|d  | }	t	|	svt
d|	||df ||df g}|dkr|||df  | j|d||	d	||j | jj| tjd
 |S )z0Scatter of group using representation of data Y.r   r   )rgb2hexz%"{}" is not a valid matplotlib color.r   3dr   rd   none)rf   alpharg   
edgecolorsrH   rh   ri   )r   r   r   valuesr   rl   r   r   r   r   r   formatr   rw   r   rx   )r2   r   Zimaskr   Y
projectionsizer   maskr\   r   datar,   r,   r-   scatter_group$  s*    
r   blueF)r   r   )r2   r   c                    s  t | |dk	rtdt|r< dkr<dtd  d  n dkrTdtd  d  t tsz fddtt|D }n }dtd	  }|rd
nd}	|rdnd}
td d }|}td d }|r|d9 }||
 | d }t	dd |D }|| }t|d |
 }||
 | }|| }|
| }dt|d |  }| dkrZt
j||ftdd|	dd ||| g}tdt|D ]:}||d   ||d  |   ||d |  qt|	gd| g|g}g }| dkrbt|D ]\}}|d d|  }|d d }|| }|d d | }|dkr2t
||||g} n |dkrRt
j||||gdd} ||  qnt| tjrt| n| g}||||fS )z1Grid of axes for plotting, legends and colorbars.Nu+   We currently don’t support `left_margin`.r   zfigure.subplot.rightgzG?gQ?c                    s   g | ]} qS r,   r,   r^   right_marginr,   r-   ra   Q  s     zsetup_axes.<locals>.<listcomp>zfigure.subplot.topg333333?g{Gz?g333333?rJ   r   g?r.   c                 S   s   g | ]}d | qS r   r,   )rG   r   r,   r,   r-   ra   c  s     rK   rO   r   r   r   )r   )check_projectionNotImplementedErrorrn   anyr   rl   r   r<   r=   sumr6   rQ   rS   r   rv   r   r   r   )r2   panels	colorbarsr   left_marginr   
show_ticksZright_margin_listZ
top_offsetZbottom_offsetZleft_offsetZbase_heightheightZ
base_widthdraw_region_widthZright_margin_factorZwidth_without_offsetsZright_offsetfigure_widthZdraw_region_width_fracZleft_offset_fracZright_offset_fracZleft_positionsr_   	panel_posr   icolorr\   rL   rN   r   r,   r   r-   
setup_axes>  sp    





r  DCr   r   r   r   )r   r   r   c           )         s  t tjr(t}fdd|D }n}g }t |tr@|g}tt|krvtdkrvfddtt|D t|||||||d\}}}}t|D ]\}}|| }|d d }|d d | }| }t	|s|rt
|}|| }| | }|dkr |dddf |dddf f}nJ|d	krZ|dddf |dddf |ddd
f f}ntd|dt |tr|dkr|j|d||d| |tjd}|| rd| t| }|d
 d
| d  |d	krdnd|  } | |||g}!t }"|"|!}#tj|tt|#d}$|dk	r2|||  t|D ]\}%}&t |&trR|&nt|&}&| |&df g| |&df gf}d	|kr| |&df g| |&df g| |&d
f gf}|j|ddddddd t|dkr||% nt|&}'|jdd |D |'g dddd q:|s|g  |g  d	|kr|g  q dkr\fddtt|D  n fddtt|D  t|D ]N\}(}| |( d  | |( d  d	|kr~|j |( d
 dd q~|D ]}|   q|S ) zPlot scatter plot of data.

    Parameters
    ----------
    Y
        Data array.
    projection

    Returns
    -------
    Depending on whether supplying a single array or a list of arrays,
    return a single axis or a list of axes.
    c                    s   g | ]} | qS r,   r,   r^   )
highlightsr,   r-   ra     s     z scatter_base.<locals>.<listcomp>r   c                    s   g | ]} d  qS r   r,   r   )sizesr,   r-   ra     s     )r2   r   r   r   r   r   r   r   r   Nr   r   zUnknown projection z not in '2d', '3d'whiterd   r   )rf   rg   r   r   rH   r/   ri   g~jtx?g333333?g?)r   Zcaxr&   r   
   r   )rg   Z
facecolorsr   rf   rH   zorderc                 S   s   g | ]}|d  qS r
  r,   )rG   dr,   r,   r-   ra     s     )r  Zfontsizer\   c                    s   g | ]}fd d D qS )c                    s   g | ]} t | qS r,   )r   r^   )component_namer,   r-   ra     s     z+scatter_base.<locals>.<listcomp>.<listcomp>r,   r   )component_indexnamesr  r,   r-   ra     s   c                    s   g | ]} qS r,   r,   r   )axis_labelsr,   r-   ra     s     i)Zlabelpad)!rl   r   r   sortedr   r=   r<   r  rv   r   rn   Zargsortr   rw   r   rx   r6   ZgcfZadd_axesr?   r   FuncFormatterticks_formatterr:   inttextr;   r>   Z
set_zticksr8   r9   Z
set_zlabelZautoscale_view))r   r   Z
sort_orderr   r	  r   r   r   rD   r  r  r  r   r  rE   r   r2   Zhighlights_indicesZhighlights_labelsr   r  r  r  r  r\   rN   r  ZY_sortsortr   Zsctr   rL   Z	rectanglefigZax_cbr   ZiihighlightZ
ihighlighthighlight_textZiaxr,   )r  r  r  r	  r  r-   scatter_base  s     
	

"
0


  

(





r  )r2   r   c                 O   s|   d|kr"|j d dkrdnd|d< d|kr2d|d< | j|dddf |ddd	f f|d
tji | g  | g  dS )zPlot scatter plot of data.

    Parameters
    ----------
    ax
        Axis to plot on.
    Y
        Data array, data to be plotted needs to be in the first two columns.
    rH   r     r   r  r   re   Nr   ri   )rq   rw   r   rx   r;   r>   )r2   r   argsrV   r,   r,   r-   scatter_single!  s    
2
r  )r2   rU   indicesc                 C   s  d}t | d}|jd dkr*d}t | d}|jd dkrFd}t | d	}d
| }t|D ]\}}|| dkrlqV|||  | }	t|	jd D ]}
d}|}|}|dk	r||||
f 9 }||||
f 9 }t|	|
ddf sq| j|d |d |	|
df |	|
df d|||dd	 qqVdS )z
    Plot arrows of transitions in data matrix.

    Parameters
    ----------
    ax
        Axis object from matplotlib.
    X
        Data array, any representation wished (X, psi, phi, etc).
    indices
        Indices storing the transitions.
    r   gMbP?r   i,     gMb@?r     g-C6?r  NTr   )Zlength_includes_headr   
head_widthr   r\   )axis_to_datarq   rv   r<   rn   r   arrow)r2   rU   r  weightstepr   r"  Zixr   ZX_stepZitransZalphaiZwidthiZhead_widthir,   r,   r-   arrows_transitions4  sB    




r'  c                 C   s   | dddS )Nz.3f0rd   )r  rstrip)r   posr,   r,   r-   r  e  s    r  c                 C   s   |  tt dS )zRemove trailing zeros.N)Zset_major_formatterr   r  r  )Z	x_or_y_axr,   r,   r-   	pimp_axiso  s    r+  c                 C   s    | t |  }|t | }|S )z?Take some 1d data and scale it so that min matches 0 and max 1.)rn   r   max)r   Zxscaledr,   r,   r-   scale_to_zero_onet  s    r-        ?c                    s   dd |ddf fdd	|dddf fdd	dkrVi n fd	d
  D |t d  i S )a3  Tree layout for networkx graph.

    See https://stackoverflow.com/questions/29586520/can-one-get-hierarchical-graphs-from-networkx-with-python-3
    answer by burubum.

    If there is a cycle that is reachable from root, then this will see
    infinite recursion.

    Parameters
    ----------
    G: the graph
    root: the root node
    levels: a dictionary
            key: level number (starting from 0)
            value: number of nodes in this level
    width: horizontal space allocated for drawing
    height: vertical space allocated for drawing
    totalcurrentr   Nc                    sl   || krd di| |< | |   d7  < t |}|dk	rL|| |D ]}| ||d |} qP| S )z*Compute the number of nodes for each levelr   r   Nr   r   remove)r   nodecurrentLevelparentr   neighbor)CURRENTGTOTALmake_levelsr,   r-   r:    s    
z"hierarchy_pos.<locals>.make_levelsc           	         s   d|   }|d }|||      |f| |< |    d7  < t |}|d k	rl|| |D ]}| ||d || } qp| S )Nr   r   r1  )	r*  r3  r4  r5  Zvert_locZdxrL   r   r6  )r7  r8  r9  r   make_posvert_gapr   r,   r-   r;    s     
zhierarchy_pos.<locals>.make_posc                    s   i | ]\}}|| d iqS r
  r,   )rG   r   v)r7  r9  r,   r-   
<dictcomp>  s      z!hierarchy_pos.<locals>.<dictcomp>r   )itemsr,  r   )r8  rootr   r   r  r,   )r7  r8  r9  r   r:  r;  r<  r   r-   hierarchy_pos{  s    "
rA  c                    s*   dd l }|d f fdd	| S )Nr   c                    s   |  |  |}|d k	r2| || || |}t| D ]2}t|d t| }|  | | || |}qB|D ]}| ||} qz| S )Nr   )add_noder   Zadd_edger2  r  r   )Zsc_Gr3  r5  r   old_nodennew_noder6  r8  make_sc_tree	node_setsr,   r-   rG    s    



z"hierarchy_sc.<locals>.make_sc_tree)r   r   )r8  r@  rH  r   r,   rF  r-   hierarchy_sc  s    rI  r   c                 C   sp   |dkr|   n|  }d|d |d   d| td |d |d    }|dkrb| | n
| | dS )z3Zoom into axis.

    Parameters
    ----------
    r   r.   r   r   r.  )g      r.   N)get_xlimry   rn   ru   r|   r{   )r2   ZxyfactorZlimitsZ
new_limitsr,   r,   r-   zoom  s    rL  )r2   r  c                 C   s:   |   |j }|j|j }}||j9 }||j9 }dS )zuGet axis size

    Parameters
    ----------
    ax
        Axis object from matplotlib.
    fig
        Figure.
    N)Zget_window_extentZtransformedZdpi_scale_transinvertedr   r  r   )r2   r  Zbboxr   r  r,   r,   r-   get_ax_size  s    

rN  )r2   r   c                 C   sD   |   }||d |d   }|  }||d |d   }d||  S )zFor a width in axis coordinates, return the corresponding in data
    coordinates.

    Parameters
    ----------
    ax
        Axis object from matplotlib.
    width
        Width in xaxis coordinates.
    r   r   r.   )rJ  ry   )r2   r   r   Zwidthxr   Zwidthyr,   r,   r-   r#    s
    r#  )r2   points_axisc                 C   s   | j | j  }||S )zMap points in axis coordinates to data coordinates.

    Uses matplotlib.transform.

    Parameters
    ----------
    ax
        Axis object from matplotlib.
    points_axis
        Points in axis coordinates.
    )Z	transAxesZ	transDatarM  Z	transform)r2   rO  r#  r,   r,   r-   axis_to_data_points  s    rP  )r2   points_datac                 C   s   t  }||S )zMap points in data coordinates to axis coordinates.

    Uses matplotlib.transform.

    Parameters
    ----------
    ax
        Axis object from matplotlib.
    points_data
        Points in data coordinates.
    )r#  rM  )r2   rQ  Zdata_to_axisr,   r,   r-   data_to_axis_points	  s    rR  c                 C   sV   | dkrt d|  d| dkrRddlm} |tj}||dk rRtdtj d	S )
z#Validation for projection argument.>   r   r   z&Projection must be '2d' or '3d', was 'z'.r   r   )parsez3.3.3z/3d plotting requires matplotlib > 3.3.3. Found N)r   Zpackaging.versionrS  mpl__version__ImportError)r   rS  Zmpl_versionr,   r,   r-   r     s    

r   bc	                 K   s   |dkr| | } || }t | ||}
dd |
D }t|f|	}t|t jr|t |jt jr||t j	
| ||| n
|| || |S )a[  
    Taken from here: https://gist.github.com/syrte/592a062c562cd2a98a83
    Make a scatter plot of circles.
    Similar to pl.scatter, but the size of circles are in data scale.
    Parameters
    ----------
    x, y : scalar or array_like, shape (n, )
        Input data
    s : scalar or array_like, shape (n, )
        Radius of circles.
    c : color or sequence of color, optional, default : 'b'
        `c` can be a single color format string, or a sequence of color
        specifications of length `N`, or a sequence of `N` numbers to be
        mapped to colors using the `cmap` and `norm` specified via kwargs.
        Note that `c` should not be a single numeric RGB or RGBA sequence
        because that is indistinguishable from an array of values
        to be colormapped. (If you insist, use `color` instead.)
        `c` can be a 2-D array in which the rows are RGB or RGBA, however.
    vmin, vmax : scalar, optional, default: None
        `vmin` and `vmax` are used in conjunction with `norm` to normalize
        luminance data.  If either are `None`, the min and max of the
        color array is used.
    kwargs : `~matplotlib.collections.Collection` properties
        Eg. alpha, edgecolor(ec), facecolor(fc), linewidth(lw), linestyle(ls),
        norm, cmap, transform, etc.
    Returns
    -------
    paths : `~matplotlib.collections.PathCollection`
    Examples
    --------
    a = np.arange(11)
    circles(a, a, s=a*0.2, c=a, alpha=0.5, ec='none')
    pl.colorbar()
    License
    --------
    This code is under [The BSD 3-Clause License]
    (http://opensource.org/licenses/BSD-3-Clause)
    r.  c                 S   s    g | ]\}}}t ||f|qS r,   r   )rG   Zx_Zy_Zs_r,   r,   r-   ra   W  s     zcircles.<locals>.<listcomp>)rn   	broadcastr   rl   ndarrayZ
issubdtyper   numberZ	set_arraymaZmasked_invalidZset_climZset_facecolorZadd_collection)r   r   rH   r2   rf   rg   vminvmaxZscale_factorrV   ZzippedZpatchesZ
collectionr,   r,   r-   circles'  s    ,

r^  )ax_or_figsizenrowsncolswspacehspacewidth_ratiosheight_ratiosr   c           
      C   s   t ||||d}t| tr:tj| d}|tj||f|fS | }	|	d |	d |		g  |	
g  |	j|	 j||f|fS d S )N)rb  rc  rd  re  r   offF)dictrl   rR   r6   rQ   r   ZGridSpecZaxisZset_frame_onr;   r>   Zget_subplotspecZsubgridspec)
r_  r`  ra  rb  rc  rd  re  kwr  r2   r,   r,   r-   make_grid_specd  s    	




ri  c                 K   s   | |  |S )aw  
    Given a dictionary of plot parameters (kwds_dict) and a dict of kwds,
    merge the parameters into a single consolidated dictionary to avoid
    argument duplication errors.

    If kwds_dict an kwargs have the same key, only the value in kwds_dict is kept.

    Parameters
    ----------
    kwds_dict kwds_dictionary
    kwargs

    Returns
    -------
    kwds_dict merged with kwargs

    Examples
    --------

    >>> def _example(**kwds):
    ...     return fix_kwds(kwds, key1="value1", key2="value2")
    >>> example(key1="value10", key3="value3")
        {'key1': 'value10, 'key2': 'value2', 'key3': 'value3'}

    )update)Z	kwds_dictrV   r,   r,   r-   fix_kwds  s    
rk  r   c                 C   s6   || j  kr|}nd| | j  kr2d| }|S )NZX_)r   r   )r   r   r   r,   r,   r-   r     s
    
r   c                 C   s   ddl m} zddl m} W n  tk
r<   ddl m} Y nX |d k	rh| d k	s^|d k	s^|d k	rtdn$|d k	r|| ||d}n|| |d}|S )Nr   )	Normalize)TwoSlopeNorm)DivergingNormz7Passing both norm and vmin/vmax/vcenter is not allowed.)r\  r]  vcenter)r\  r]  )r   rl  rm  rV  rn  r   )r\  r]  ro  Znormrl  ZDivNormr,   r,   r-   check_colornorm  s    
rp  )
NNNNNr.   NNNN)NNr,   r,   rX   rY   NNTNrZ   N)r,   r,   N)NN)NNNN)N)NF)N)N)r   r   N)Nr   r   NNr   F)r   TNr,   NNr   Nr  r  Nr   r   rZ   TN)N)Nr.  r.  )r   r   )NrW  NNr.  )NNNN)NNNN)cr   collections.abcabcr   r   	functoolsr   typingr   r   r   r   r   r	   r
   Zanndatanumpyrn   Z
matplotlibrT  r   r6   r   r   r   r   Zmatplotlib.axesr   r   r   Zmatplotlib.figurer   rS   r   Zmatplotlib.patchesr   Zmatplotlib.collectionsr   r   r   rX   r   r   Z	_settingsr   Z_compatr   _utilsr   r   r   rm   Z	ColorLikeZ_IGraphLayoutZ_FontWeightZ	_FontSizeZVBoundZSubplotBaser'   r3   rW   rY  rT   r   r   r   boolr  r@   ro   r   r   r   r   r   r   r   r  r  r  r'  r  r+  r-  rA  rI  rL  rN  r#  rP  rR  r   r^  ZGridSpecBaseri  rk  ZAnnDatar   rp  r,   r,   r,   r-   <module>   s~  $          
!            
I      =*
!     	!I)   


!
       T                
 1

6
         
A    

 