U
    Åmœd@¹  ã                +   @   sr  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 d dl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) ddl)m*Z*m+Z+m,Z,m-Z- ddl(m)Z.m/Z0 ddl1m2Z2 ddl3m4Z4 d8ddœee4d e
e5e6e-df e
e5e,f dœdd„Z7dd ddd ei ƒfee8ef dœdd „Z9dddei ƒdd ddd!dddddei ƒd"d#d"ddd$dd%d dddddei ƒdd&dd&ddd&dddf(ee	e6 e	e
e8ee
e8e5f eee6f f f  e	e+ ee8ef e	ej: e
e5e8ee5 df e
e8ee8 ee8e8f df e;e8e	e8 e	e8 e	e5 e8e	e5 ee8ef e6e6e6e	e6 e	e6 e5e	e8 e6e	e5 e
ej:e8edf e;e
e8e#f e	e  ee8ef e	e; e;e;e;e;e	e; e
e;e8df e	e  e
e ee  df d'œ'd(d)„Z<ddddddd dddddei ƒd"d#d"d*dddd&ddddd&ei ƒdd$fee8ef ee8ef d+œd,d-„Z=d&d.dee>d/d.�ƒdd0dd1ddddd&d&d&dddd&ddddfeee
e8e5f  ee8 e;ee8 e
e8e#df ee8e
e8e#f f e	ee8  e5e	e8 ee	e5 e	e5 f e	e8 e	e5 e	e5 e;e;e;e
e5e6e-df e
e5e,df e;e;e;e	e; e
e;e8df e	e  e	e  d2œd3d4„Z?d9d6d7„Z@dS ):é    N)ÚPath)ÚMappingProxyType)ÚOptionalÚUnionÚListÚSequenceÚMappingÚAnyÚTuple)ÚAnnData)Úis_categorical_dtype)ÚpyplotÚrcParamsÚticker)Úpatheffects)ÚAxes)Úis_color_likeÚColormap)Úissparse)Úcheck_random_stateé   )Ú_utils)ÚmatrixÚ_IGraphLayoutÚ_FontWeightÚ	_FontSizeé   )r   Úlogging)Úsettings)ÚLiteralFÚ2dúon dataÚboldçš™™™™™©?©Úpos)r    Z3d)ÚadataÚ
projectionÚlegend_fontsizeÚlegend_fontweightc          %      K   sZ  t jddg|d�\}}}}|dkr0| jd d }d}|dkrT|dkrH|n|}d\}}|dkr d| jkrld	}n4d
| jkr|d}n$d| jkrŒd}nd| jkrœd}nd}ddlm}m}m} || |d ||||||||	|
||||||ddd� |dk�rx|| jd d k�rj|| |ƒ}||d|jd d�d } |dd…| f }!t	j
|!ddg| jd�j| j| dd� ¡  ¡  ¡ }n| jd d }|d  ¡ |d  ¡  }"}#|d  |"¡ |d  |#¡ d|k�rÄ| d¡}$n|}$|	dk	�rÚ|	|d< |
dk	�rì|
|d< |dk	�rþ||d< t| f|d dd||$|||dœ|—Ž |dk	�r8t |¡ t jd||d � |dk�rV|S dS )!aa      Scatter and PAGA graph side-by-side.

    Consists in a scatter plot and the abstracted graph. See
    :func:`~scanpy.pl.paga` for all related parameters.

    See :func:`~scanpy.pl.paga_path` for visualizing gene changes along paths
    through the abstracted graph.

    Additional parameters are as follows.

    Parameters
    ----------
    adata
        Annotated data matrix.
    kwds_scatter
        Keywords for :func:`~scanpy.pl.scatter`.
    kwds_paga
        Keywords for :func:`~scanpy.pl.paga`.

    Returns
    -------
    A list of :class:`~matplotlib.axes.Axes` if `show` is `False`.
    r   é   )ÚpanelsÚright_marginNÚpagaÚgroups)Ú r/   ZX_draw_graph_faZdraw_graph_faZX_umapZumapZX_tsneZtsneZX_draw_graph_frZdraw_graph_fr)Ú	embeddingÚ
_get_basisÚ_components_to_dimensionsF)ÚaxÚbasisÚcolorÚedgesÚalphar.   Ú
componentsÚ
legend_locr(   r)   Úlegend_fontoutlineÚ	color_mapÚpaletteÚframeonÚsizeÚtitleÚshowÚsave)r8   Ú
dimensionsZ
total_dimsÚxÚy)ÚcolumnsÚindexT)Zobservedr%   ÚlabelsÚfontsizeÚ
fontweightÚfontoutline)r3   r@   rA   r?   rG   Úcolorsr=   r%   Úpaga_compare©r@   rA   )r   Ú
setup_axesÚunsZobsmZscatterplotsr0   r1   r2   ÚshapeÚpdÚ	DataFrameZ	obs_namesÚgroupbyÚobsÚmedianZ
sort_indexZto_numpyZget_xlimÚget_ylimZset_xlimZset_ylimÚpopr-   ÚplÚsuptitleÚsavefig_or_show)%r&   r4   r6   r5   r7   r.   r8   r'   r9   r(   r)   r:   r;   r<   r=   r>   r?   r,   Úleft_marginr@   rA   Ztitle_graphZgroups_graphr%   Zpaga_graph_paramsÚaxsÚ_rY   r0   r1   r2   Z_basisZdimsÚcoordsÚxlimZylimrG   © r`   úT/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scanpy/plotting/_tools/paga.pyrL      s´    4þ



í

  ÿþ ÿÿ



ÿ÷
ö


rL   )Úlayout_kwdsc                    s”  dd l }dd l}t|ƒ}| | ¡}	|d kr.d}|dkrjzddlm}
 W n" tk
rh   t d¡ d}Y nX |dk�r|d kr’| 	| j
d df¡}n| ¡ }|
dddddd	d
dddddd�}d|krÌ|d }nd|krÞ|d }nd}|j| ||d�}dd„ t|ƒD ƒ‰ �nV|dk�rH| |¡}t ||¡‰ tˆ ƒ| j
d k �r^tdƒ‚�n| | d¡¡ t | ¡}d|k�ršt |¡}|j|t|tƒ�rŒ|n|gd�j}n²|dk�r²| |¡j}nš|d k�rÖ| 	| j
d df¡ ¡ }n(| ¡ }|d d …df  d9  < | ¡ }z|j|f|ddœ|—Žj}W n. tk
�rJ   |j|fd|i|—Žj}Y nX dd„ t|ƒD ƒ‰ tˆ ƒdk�rtdˆ d< t ‡ fd d!„t|	ƒD ƒ¡}|S )"Nr   ÚfrÚfa)ÚForceAtlas2z—Package 'fa2' is not installed, falling back to layout 'fr'.To use the faster and better ForceAtlas2 layout, install package 'fa2' (`pip install fa2`).r   Fç      ð?Tg333333ó?g       @)ZoutboundAttractionDistributionZ
linLogModeZadjustSizesZedgeWeightInfluenceZjitterToleranceZbarnesHutOptimizeZbarnesHutThetaZmultiThreadedZscalingRatioZstrongGravityModeZgravityÚverboseÚmaxiterÚ
iterationsiô  )r%   ri   c                 S   s$   i | ]\}}||d  |d  g“qS ©r   r*   r`   ©Ú.0ÚnÚpr`   r`   ra   Ú
<dictcomp>è   s      z _compute_pos.<locals>.<dictcomp>Úeq_treezKThis is a forest and not a single tree. Try another `layout`, e.g., {'fr'}.é   Úrt)ÚrootÚcircler*   éÿÿÿÿÚweight)ÚseedÚweightsrw   c                 S   s$   i | ]\}}||d  |d  g“qS rj   r`   rk   r`   r`   ra   ro     s      )ç      à?ry   c                    s   g | ]\}}ˆ | ‘qS r`   r`   )rl   Úcountrm   r$   r`   ra   Ú
<listcomp>  s     z _compute_pos.<locals>.<listcomp>)ÚrandomÚnetworkxr   ÚGraphZfa2re   ÚImportErrorÚloggÚwarningZrandom_samplerP   ÚcopyÚforceatlas2Ú	enumerater   Zhierarchy_posÚlenÚ
ValueErrorrw   ÚbytesÚ	_sc_utilsZget_igraph_from_adjacencyÚlayoutÚ
isinstanceÚlistr^   ÚtolistÚAttributeErrorÚnpÚarray)Úadjacency_solidr‰   Úrandom_stateÚinit_posÚadj_treers   rb   r|   ÚnxÚ
nx_g_solidre   Zinit_coordsrƒ   ri   Zpos_listZ	nx_g_treeÚgZg_treeÚ	pos_arrayr`   r$   ra   Ú_compute_pos¬   s¦    	
ÿ

ð

  ÿ

ÿ


 ÿ


ÿ
ÿ ÿÿr˜   Úconnectivitiesrf   ry   é   ç{®Gáz„?T)'r&   Ú	thresholdr5   r‰   rb   r’   rs   rG   Úsingle_componentÚsolid_edgesÚdashed_edgesÚtransitionsrH   rI   rJ   Ú	text_kwdsÚnode_size_scaleÚnode_size_powerÚedge_width_scaleÚmin_edge_widthÚmax_edge_widthÚ	arrowsizer?   r[   r‘   r%   Únormalize_to_colorÚcmapÚcaxÚcb_kwdsr=   Úadd_posÚexport_to_gexfÚuse_rawÚplotr@   rA   r3   Úreturnc)           =   "      s~  |$dk	r|$‰t  d¡ |#dkr"|}#ˆ jd d ‰‡ ‡fdd„})t|#tjƒr”t|#tt|#ƒƒ tjƒr”dd„ tˆ j	ˆ j
jƒD ƒ‰‡fd	d„|# ¡ D ƒ}#|)|#ƒr¢|#g}#|dkr°tj}|)ˆƒrÒ‡fd
d„tt|#ƒƒD ƒ‰ˆdkröt|#ƒdkrödd„ |#D ƒ‰n8tˆtƒ�r‡fdd„|#D ƒ‰nˆdk�r.dd„ |#D ƒ‰|dk�rhˆ jdk�rJˆ jnˆ jj‰‡ ‡fdd„|#D ƒ}*ndd„ |#D ƒ}*t|tƒ�r°|ˆk�r¢tdˆ› d|›d�ƒ‚tˆƒ |¡}t|tjƒ�rÞ|d ˆk�rÞ‡fdd„|D ƒ}ˆ jd |	  ¡ }+d},|dk�rd}|dk�r$d|+j|+j|k < |+ ¡  |
dk	�rbˆ jd |
  ¡ },|dk�rbd|,j|,j|k < |, ¡  |dk�ržd}-|dk�rˆˆ jd d }-t|+|||||-|d�}|%�rtj|(|#|*d�\}.}/}0}1t|#ƒdk�rÜt|.tƒ�sÜ|.g}.t|#ƒD �].\}2}3ˆ|2 dk	�r|.|2  ˆ|2 ¡ tˆ |.|2 t|#tjƒ�r*|#n|3|	|
|||+|,|ˆ|2 |||||||||||||*|2 ||"ˆ|2 |!|||d�}4|*|2 �rä|dk�rò|/d d }5|/d d |5 }6d|0 t|#ƒ }7|/d d|2 d  d|7  }8|8|5|7|6g}9t  !¡ }:|: "|9¡};n||2 };t j#|4t$ %tj&¡|;d �}<�qä| �r4|ˆ jd d!< t  'd"¡ |%�rztj(d|&|'d#� t|#ƒdk�rlt|.tƒ�rl|.d }.|&d$k�rz|.S dS )%u       Plot the PAGA graph through thresholding low-connectivity edges.

    Compute a coarse-grained layout of the data. Reuse this by passing
    `init_pos='paga'` to :func:`~scanpy.tl.umap` or
    :func:`~scanpy.tl.draw_graph` and obtain embeddings with more meaningful
    global topology [Wolf19]_.

    This uses ForceAtlas2 or igraph's layout algorithms for most layouts [Csardi06]_.

    Parameters
    ----------
    adata
        Annotated data matrix.
    threshold
        Do not draw edges for weights below this threshold. Set to 0 if you want
        all edges. Discarding low-connectivity edges helps in getting a much
        clearer picture of the graph.
    color
        Gene name or `obs` annotation defining the node colors.
        Also plots the degree of the abstracted graph when
        passing {`'degree_dashed'`, `'degree_solid'`}.

        Can be also used to visualize pie chart at each node in the following form:
        `{<group name or index>: {<color>: <fraction>, ...}, ...}`. If the fractions
        do not sum to 1, a new category called `'rest'` colored grey will be created.
    labels
        The node labels. If `None`, this defaults to the group labels stored in
        the categorical for which :func:`~scanpy.tl.paga` has been computed.
    pos
        Two-column array-like storing the x and y coordinates for drawing.
        Otherwise, path to a `.gdf` file that has been exported from Gephi or
        a similar graph visualization software.
    layout
        Plotting layout that computes positions.
        `'fa'` stands for â€œForceAtlas2â€�,
        `'fr'` stands for â€œFruchterman-Reingoldâ€�,
        `'rt'` stands for â€œReingold-Tilfordâ€�,
        `'eq_tree'` stands for â€œeqally spaced treeâ€�.
        All but `'fa'` and `'eq_tree'` are igraph layouts.
        All other igraph layouts are also permitted.
        See also parameter `pos` and :func:`~scanpy.tl.draw_graph`.
    layout_kwds
        Keywords for the layout.
    init_pos
        Two-column array storing the x and y coordinates for initializing the
        layout.
    random_state
        For layouts with random initialization like `'fr'`, change this to use
        different intial states for the optimization. If `None`, the initial
        state is not reproducible.
    root
        If choosing a tree layout, this is the index of the root node or a list
        of root node indices. If this is a non-empty vector then the supplied
        node IDs are used as the roots of the trees (or a single tree if the
        graph is connected). If this is `None` or an empty list, the root
        vertices are automatically calculated based on topological sorting.
    transitions
        Key for `.uns['paga']` that specifies the matrix that stores the
        arrows, for instance `'transitions_confidence'`.
    solid_edges
        Key for `.uns['paga']` that specifies the matrix that stores the edges
        to be drawn solid black.
    dashed_edges
        Key for `.uns['paga']` that specifies the matrix that stores the edges
        to be drawn dashed grey. If `None`, no dashed edges are drawn.
    single_component
        Restrict to largest connected component.
    fontsize
        Font size for node labels.
    fontoutline
        Width of the white outline around fonts.
    text_kwds
        Keywords for :meth:`~matplotlib.axes.Axes.text`.
    node_size_scale
        Increase or decrease the size of the nodes.
    node_size_power
        The power with which groups sizes influence the radius of the nodes.
    edge_width_scale
        Edge with scale in units of `rcParams['lines.linewidth']`.
    min_edge_width
        Min width of solid edges.
    max_edge_width
        Max width of solid and dashed edges.
    arrowsize
       For directed graphs, choose the size of the arrow head head's length and
       width. See :py:class: `matplotlib.patches.FancyArrowPatch` for attribute
       `mutation_scale` for more info.
    export_to_gexf
        Export to gexf format to be read by graph visualization programs such as
        Gephi.
    normalize_to_color
        Whether to normalize categorical plots to `color` or the underlying
        grouping.
    cmap
        The color map.
    cax
        A matplotlib axes object for a potential colorbar.
    cb_kwds
        Keyword arguments for :class:`~matplotlib.colorbar.Colorbar`,
        for instance, `ticks`.
    add_pos
        Add the positions to `adata.uns['paga']`.
    title
        Provide a title.
    frameon
        Draw a frame around the PAGA graph.
    plot
        If `False`, do not create the figure, simply compute the layout.
    save
        If `True` or a `str`, save the figure.
        A string is appended to the default filename.
        Infer the filetype if ending on \{`'.pdf'`, `'.png'`, `'.svg'`\}.
    ax
        A matplotlib axes object.

    Returns
    -------
    If `show==False`, one or more :class:`~matplotlib.axes.Axes` objects.
    Adds `'pos'` to `adata.uns['paga']` if `add_pos` is `True`.

    Examples
    --------

    .. plot::
        :context: close-figs

        import scanpy as sc
        adata = sc.datasets.pbmc3k_processed()
        sc.tl.paga(adata, groups='louvain')
        sc.pl.paga(adata)

    You can increase node and edge sizes by specifying additional arguments.

    .. plot::
        :context: close-figs

        sc.pl.paga(adata, node_size_scale=10, edge_width_scale=2)

    Notes
    -----
    When initializing the positions, note that â€“ for some reason â€“ igraph
    mirrors coordinates along the x axis... that is, you should increase the
    `maxiter` parameter by 1 if the layout is flipped.

    .. currentmodule:: scanpy

    See also
    --------
    tl.paga
    pl.paga_compare
    pl.paga_path
    Nz9`groups` is deprecated in `pl.paga`: use `labels` insteadr-   r.   c                    s<   t | tjƒo$t| ƒtˆ jˆ jjƒk}|p:| d kp:t | tƒS ©N)rŠ   ÚcabcÚ
Collectionr…   rT   ÚcatÚ
categoriesÚstr)rC   Zhas_one_per_category)r&   Ú
groups_keyr`   ra   Úis_flatã  s    ÿzpaga.<locals>.is_flatc                 S   s   i | ]\}}||“qS r`   r`   )rl   Úirm   r`   r`   ra   ro   í  s     zpaga.<locals>.<dictcomp>c                    s   i | ]\}}ˆ   ||¡|“qS r`   )Úget)rl   rm   Úv)Únames_to_ixsr`   ra   ro   ð  s     
 c                    s   g | ]}ˆ ‘qS r`   r`   ©rl   r]   ©rG   r`   ra   r{   ø  s     zpaga.<locals>.<listcomp>r*   c                 S   s   g | ]}|‘qS r`   r`   ©rl   Úcr`   r`   ra   r{   û  s     c                    s   g | ]}ˆ ‘qS r`   r`   r¿   )r?   r`   ra   r{   ý  s     c                 S   s   g | ]}d ‘qS r±   r`   r¿   r`   r`   ra   r{   ÿ  s     c                    s2   g | ]*}|ˆ   ¡ kr&ˆ j| jjd kp,|ˆk‘qS )Úcategory)Úobs_keysrT   ZdtypeÚnamer¿   )r&   Ú	var_namesr`   ra   r{     s   ýc                 S   s   g | ]}d ‘qS )Fr`   r½   r`   r`   ra   r{     s     z-If `root` is a string, it needs to be one of z not Ú.r   c                    s   g | ]}t ˆ ƒ |¡‘qS r`   )r‹   rF   )rl   Úrr¾   r`   ra   r{     s     r›   >   rr   rp   Úrt_circularÚconnectivities_tree)r‰   r‘   r’   rb   r“   rs   )r3   r+   Ú	colorbars)rK   rž   rŸ   r    rœ   r�   Úadjacency_dashedrs   rG   rH   rI   rJ   r¡   r¢   r£   r¤   r¥   r¦   r¨   r=   r©   Úcolorbarr«   r®   r?   r­   r�   r§   r%   gú~j¼t“x?r   çš™™™™™É?)Úformatrª   r%   z3added 'pos', the PAGA positions (adata.uns['paga'])rM   F))r€   r�   rO   rŠ   r²   r   ÚnextÚiterr„   rT   r´   rµ   Úitemsr   Z_frameonÚranger…   r¶   ÚrawrÄ   r†   r‹   rF   r   r‚   ÚdataÚeliminate_zerosr˜   r   rN   Ú	set_titleÚ_paga_graphrX   ZgcfZadd_axesrË   r   ZFuncFormatterZticks_formatterÚhintrZ   )=r&   rœ   r5   r‰   rb   r’   rs   rG   r�   rž   rŸ   r    rH   rI   rJ   r¡   r¢   r£   r¤   r¥   r¦   r§   r?   r[   r‘   r%   r¨   r©   rª   rË   r«   r=   r¬   r­   r®   rK   r.   r¯   r@   rA   r3   r¸   rÉ   r�   rÊ   r“   r\   Z	panel_posZdraw_region_widthZfigure_widthZicolorrÀ   ÚsctÚbottomÚheightÚwidthÚleftZ	rectangleZfigZax_cbr]   r`   )r&   r·   rG   r¼   r?   rÄ   ra   r-     s    F
 ÿÿ

û
ÿ





ù
ýá!


ý


r-   Ú	reference)r¡   r«   c           U   	      s   dd l }|
} | d k	rJt| tƒrJ| | jd d krJtd | jd d | ¡ƒ‚| jd d }!| d krn| j|! jj} ˆ d ks€ˆ |!k�r|!d k	�r|!d | jks¼t	| j|! jjƒt	| j|!d  ƒkrÈt
 | |!¡ | j|!d  ‰ t| j|! jjƒD ]\}"}#|#tjkrèdˆ |"< qè| |¡}$|d k	�r"| |¡}%t|ttfƒ�s8|}&nŽt|ƒ}|jdk�rTtdƒ‚d	}'| ¡ �4}(|( ¡  |(D ] })|) d
¡�r„ �q�|'|)7 }'�qnW 5 Q R X ddlm}* tj|*|'ƒdd�}+|+ddg j}&dd„ t|&ƒD ƒ}tˆ tƒ�rtˆ ƒ�r‡ fdd„tt	| ƒƒD ƒ‰ tˆ tƒ�r”ˆ  d¡�r”ˆ dk�rBdd„ |%jdd�D ƒ‰ n*ˆ dk�rddd„ |$jdd�D ƒ‰ ntdƒ‚t ˆ ¡t ˆ ¡ t  ˆ ¡t ˆ ¡  ‰ | j!d k�r¦| j"n| j!j"},tˆ tƒ�rJˆ |,k�rJg }-| j|! jj}.t|.ƒD ]f\}/}0|0| j|! kj}1| j!d k	�r|�r| j!d d …ˆ f }2n| d d …ˆ f }2|- #t $|2j%|1 ¡¡ �qÞ|-‰ tˆ tƒ�rÆˆ | jk�rÆt&| jˆ  ƒ�sÆg }-| j|! jj}.t|.ƒD ]4\}/}0|0| j|! kj}1|- #| jj'|1ˆ f  $¡ ¡ �qŒ|-‰ tˆ tƒ�r4ˆ | jk�r4t&| jˆ  ƒ�r4t(j)| |!ˆ |�rdndd�\}3}4t
 | ˆ ¡ t( *| jˆ d  |4¡}5|5‰ t	ˆ ƒt	| ƒk�rdtdt	| ƒ› d t	ˆ ƒ› d!�ƒ‚t+j,j- .|¡\}6}
|6d"k�r�|�s�t/ 0d#¡ |6d"k�r^|�r^t 1|
¡}7t 2|7|7  ¡ k¡d d }8| 3¡ |
|8kd d …f }| 4¡ d d …|
|8kf }t ˆ ¡|
|8k ‰ t | ¡|
|8k } | j|! jj|
|8k  5¡ }9t/ 6d$|9› �¡ | |¡}$|d k	�r^td%ƒ‚|d t7d&  }:|d k	�rÌd'd„ |%j8d(d)�D ƒ};|:t |;¡ };|d k	�r´t 9|;d |¡};|j:|%|||;dd*d+d,� |d k�rPd-d„ |$j8d(d)�D ƒ};|:t |;¡ };|d k	�s|d k	�rt 9|;||¡};t; <¡ �$ t; =d.¡ |j:|$|||;d/d0� W 5 Q R X n | jd |  >¡ }<|d k�rpd1}d|<j?|<j?|k < |< @¡  | A|<jB¡}=d2d„ |=j8d(d)�D ƒ};|:t |;¡ };|d k	�sÌ|d k	�rÚt 9|;||¡};|j:|=|||;d/|d3� |�rÚtˆ d tCƒ�r$dd4lDmE‰ ‡fd5d„ˆ D ƒ‰ t|$ F¡ ƒD ]l\}>}?t| |> ƒ|$jG|> d6< tˆ |> ƒ|$jG|> d7< tHtHd8||> d  d8||> d"  dd9�d:�|$jG|> d;< �q0tjId< }@t/ Jd=|@› �¡ tjIjKd(d(d>� | L|$tjId< ¡ | M|¡ | Ng ¡ | Og ¡ |!d k	�r"|!d? | jk�r"| j|!d?  }Ant Pt	| ƒ¡}Ad@}B|Bt Q|jRd ¡dA  | }Ct S|A¡}D|Ct T|A|D |¡ }A|d k�r€t7dB }|d k	�r¦tH|ƒ}tUjV|dCdD�g|dE< tˆ d tWjXƒ�	s>t	|&ƒ}E|jY|&d d …df |&d d …d"f ˆ d |E… dF|A|dG�}Ft| ƒD ]:\}>}G|jZ|&|>df |&|>d"f |GfdHdH||dIœ|—Ž �qþ�nÞtt[|&d d …df |&d d …d"f ƒƒD �]´\‰\}H}Itˆ ˆ tWjXƒ�	s–tˆ ˆ › dJ�ƒ‚ˆ ˆ  \¡ }J‡ ‡fdKd„|JD ƒ}Kt]|Kƒ}L|Ld"k �	rît^|Jƒ}J|J #d¡ |K #d"t]|Kƒ ¡ n$t _|Ld"¡�
stdLˆ› dM|L› d!�ƒ‚t `|K¡}M|M|Md  }Mdg|M 5¡  }Mt[|Md d… |Md"d … |JƒD ]–\}N}O}Pt adNtjb |N dNtjb |O dO¡}Qdgt c|Q¡ 5¡  }Rdgt d|Q¡ 5¡  }St e|R|Sg¡}Tt f|T¡  ¡ }'|jY|Hg|Ig|T|'dN |Aˆ  |PdP�}F�
qR| d k	�	rd|jZ|H|I| ˆ fdHdH||dIœ|—Ž �	qd|FS )QNr   r-   r.   z>Provide a list of group labels for the PAGA groups {}, not {}.Ú_colorsZgreyz.gdfzqCurrently only supporting reading positions from .gdf files. Consider generating them using, for instance, Gephi.r/   zedgedef>)ÚStringIOru   )Úheaderé   é   c                 S   s"   i | ]\}}||d  |d g“qS rj   r`   rk   r`   r`   ra   ro   Õ  s      z_paga_graph.<locals>.<dictcomp>c                    s   g | ]}ˆ ‘qS r`   r`   r¿   )rK   r`   ra   r{   Ù  s     z_paga_graph.<locals>.<listcomp>ÚdegreeZdegree_dashedc                 S   s   g | ]\}}|‘qS r`   r`   ©rl   r]   Údr`   r`   ra   r{   ß  s     rv   )rv   Zdegree_solidc                 S   s   g | ]\}}|‘qS r`   r`   rä   r`   r`   ra   r{   á  s     z2`degree` either "degree_dashed" or "degree_solid".rÝ   Ú
prediction)ræ   rÝ   Znormalizationz#Expected `colors` to be of length `z
`, found `z`.r*   znGraph has more than a single connected component. To restrict to this component, pass `single_component=True`.zHRestricting graph to largest connected component by dropping categories
z4`single_component` only if `dashed_edges` is `None`.zlines.linewidthc                 S   s   g | ]}|d  d ‘qS ©ru   rv   r`   ©rl   rC   r`   r`   ra   r{   7  s     T)rÓ   Zdashedry   )r3   rÛ   Ú
edge_colorÚstyler7   c                 S   s   g | ]}|d  d ‘qS rç   r`   rè   r`   r`   ra   r{   G  s     ÚignoreÚblack)r3   rÛ   ré   r›   c                 S   s   g | ]}|d  d ‘qS rç   r`   rè   r`   r`   ra   r{   X  s     )r3   rÛ   ré   r§   ©Úrgb2hexc                    s   g | ]}ˆ |ƒ‘qS r`   r`   r¿   rí   r`   ra   r{   d  s     Úlabelr5   iè  )rC   rD   Úz)ÚpositionZvizzpaga_graph.gexfzexporting to )ÚparentsÚexist_okZ_sizesiÐ  é
   zlegend.fontsizeÚw)Z	linewidthÚ
foregroundZpath_effectsZface)rÀ   Z
edgecolorsÚsr©   Úcenter)ÚverticalalignmentÚhorizontalalignmentr>   rI   zK is neither a dict of valid matplotlib colors nor a valid matplotlib color.c                    s   g | ]}ˆ ˆ | ‘qS r`   r`   r¿   )rK   Úixr`   ra   r{   ¬  s     zExpected fractions for node `z` to be close to 1, found `r   é   )Úmarkerr÷   r5   )gr}   rŠ   r¶   rO   r†   rÍ   rT   r´   rµ   r…   r   Ú,add_colors_for_categorical_sample_annotationr„   r   Zcategories_to_ignorer~   r   ÚsuffixÚopenÚreadlineÚ
startswithÚiorß   rQ   Zread_csvÚvaluesr   rÑ   rã   rŽ   r�   ÚminÚmaxrÒ   rÄ   ÚappendZmeanÚXr   Úlocrˆ   Z$compute_association_matrix_of_groupsZget_associated_colors_of_groupsÚscipyÚsparseZcsgraphZconnected_componentsr€   ÚdebugZbincountÚwhereZtocsrZtocscrŒ   Úinfor   r6   ZclipZdraw_networkx_edgesÚwarningsÚcatch_warningsÚsimplefilterr‚   rÓ   rÔ   ZDiGraphÚTÚtupleÚmatplotlib.colorsrî   ÚnodesÚnodeÚdictZwritedirr�   ÚmkdirZ
write_gexfÚset_frame_onÚ
set_xticksÚ
set_yticksZonesÚsqrtrP   rU   Úpowerr   Z
withStroker²   r   ÚscatterÚtextÚzipÚkeysÚsumr‹   ÚiscloseÚcumsumZlinspaceÚpiÚcosÚsinZcolumn_stackÚabs)Ur&   r3   rž   rŸ   r�   rÊ   r    rœ   rs   rK   rG   rH   rI   rJ   r¡   r¢   r£   r¤   r¨   r?   r%   r©   r=   r¥   r¦   r­   rË   r®   r«   r�   r§   r”   Znode_labelsr·   ZinamerÃ   r•   Znx_g_dashedr—   r÷   ÚfÚlinerß   ÚdfrÄ   Zx_colorZcatsZicatr´   ZsubsetZ
adata_geneZ
asso_namesZasso_matrixZasso_colorsZn_componentsZcomponent_sizesZlargest_componentZcats_droppedZbase_edge_widthÚwidthsZadjacency_transitionsZg_dirrz   rm   ÚfilenameZgroups_sizesZbase_scale_scatterZbase_pie_sizeZmedian_group_sizeZn_groupsrØ   ÚgroupZxxÚyyZcolor_singleZfracsÚtotalr$  Úr1Úr2r5   ZanglesrC   rD   Zxyr`   )rK   rû   rî   ra   rÖ   ~  s*   !ÿþý ÿÿÿþ




ÿ


(ÿþýÿþýü
 ÿÿÿ
ÿÿ



ù


    ÿ
     ÿýÿ



ÿ
 ÿ

ÿ
ú

ýùø4ÿ

ÿ
&"    ÿ

ýùø
rÖ   )Údpt_pseudotimeÚGreysr*   )NN)r&   r  r!  r®   Úannotationsr;   Úcolor_maps_annotationsÚpalette_groupsÚn_avgr·   r_   r?   Úytick_fontsizeÚtitle_fontsizeÚshow_node_namesÚshow_yticksÚshow_colorbarr(   r)   Únormalize_to_zero_oneÚ
as_heatmapÚreturn_datar@   rA   r3   r°   c           >         s  |dk}|	dkr4d| j d kr&tdƒ‚| j d d }	| j|	 jj‰ d| j ¡ krXtdƒ‚|dkr|t | |	¡ | j |	› d� }‡fdd	„}|dkr˜t	 
¡ n|}g }d
g}g }g }dd„ |D ƒ} t|d
 tƒ�r"g }!tˆ ƒ}"|D ]>}#|#|"k�r
tdˆ  ¡ › d|	›d|#›d�ƒ‚|! ˆ  |#¡¡ qÜ|}$n|}!‡ fdd„|D ƒ}$| }%|�rT| jdk	�rT| j}%t|ƒD �]B\}&}'g }(t|!ƒD �]>\})}*t | j¡| j|	 j|$|) k }+t|+ƒd
k�rÊtd|	›dt|*ƒ›d|	›d�ƒ‚t | jd j| j|	 j|$|) k ¡},|+|, }+|'|  ¡ k�r| j|' jn|%dd…|'f j|+ }-|(t|-ƒ�r:|-jn|- ¡ 7 }(|&d
k�rr||*gt|+ƒ 7 }| t|(ƒ¡ |D ]<}.| j|. }/t|/ƒ�r’|/jj}/| |.  t|/j|+ ƒ7  < �qr�qrˆdk�r ||(ƒ}(|&d
k�r |D ]*}'t| |' d
 tƒ�sÔ|| |' ƒ| |'< �qÔ|�r"|(t  |(¡8 }(|(t !|(¡ }(| |(¡ |�sP|j"|(|
d
 |
d … |'d� |&d
k�r\t|ƒD ]:\})}*tˆ ƒd
k�rŒ|*ˆ k�rŒˆ |* }0n|*}0| |0¡ �qb�q\t #|¡ $¡ }|�r\|j%|dd|d�}1|�rð| &t't|ƒƒ¡ |j(||d� n
| &g ¡ | )d¡ | *g ¡ |j+ddd
d� | ,d¡ |�r<t	j-|1|d � |dk�rJd!n|}t	j.|d"� n8|dk�rjd#n|}t|ƒdk�r”t	j/dd$| d%f|d&� |	}2|�sÖ| 0|2¡ t	 1g ¡ t|ƒdk�rTt	 2|d
 d' ¡ �n~d
dl3}3| 4¡ j5}4t	 6|4d
 |4d |4d( t|ƒ  |4d) |4d( t|ƒ f¡}5t 7|¡ddd…f }|5j%|dd|3j8j9|t  |¡ :t;¡d… t;t !|¡d t  |¡ ƒd*�d� |�rž|5j(d+|2d+g|d� n
|5 &g ¡ |5 )d¡ |�r|5 <¡ d |5 <¡ d
  d) }6t=j>|d)d,�}t|ƒD ],\}7}0|5j?||7 |6||7 t@d-d-d.�d/� �qê|5 *g ¡ |5 ,d¡ |5j+ddd
d� |4d( t|ƒ }8t|ƒD ]þ\}9}.|9d
k�rz|4d( t|ƒ d) }8t	 6|4d
 |4d |9d) |8  |4d) |8f¡}:t 7| |. ¡ddd…f };|.|k�rât| j|. ƒ�rÜd0nd1}<n||. }<|:j%|;dd|<d�}1|�r(|:j(d+|.d+g|d� |:j+ddd
d� n
|: &g ¡ |: )d¡ |: *g ¡ |: ,d¡ �qT|dk	�rl|jA||d� |dk�r‚|�s‚d}n|dk�r’tBjCn|}tjDd2||d3� |�røtEjF|jG|d4�}=||ƒ|=d< d| k�rà| d jG|=d5< ||�rò|�sò|=n|=fS |�r|�s|S dS dS )6a      Gene expression and annotation changes along paths in the abstracted graph.

    Parameters
    ----------
    adata
        An annotated data matrix.
    nodes
        A path through nodes of the abstracted graph, that is, names or indices
        (within `.categories`) of groups that have been used to run PAGA.
    keys
        Either variables in `adata.var_names` or annotations in
        `adata.obs`. They are plotted using `color_map`.
    use_raw
        Use `adata.raw` for retrieving gene expressions if it has been set.
    annotations
        Plot these keys with `color_maps_annotations`. Need to be keys for
        `adata.obs`.
    color_map
        Matplotlib colormap.
    color_maps_annotations
        Color maps for plotting the annotations. Keys of the dictionary must
        appear in `annotations`.
    palette_groups
        Ususally, use the same `sc.pl.palettes...` as used for coloring the
        abstracted graph.
    n_avg
        Number of data points to include in computation of running average.
    groups_key
        Key of the grouping used to run PAGA. If `None`, defaults to
        `adata.uns['paga']['groups']`.
    as_heatmap
        Plot the timeseries as heatmap. If not plotting as heatmap,
        `annotations` have no effect.
    show_node_names
        Plot the node names on the nodes bar.
    show_colorbar
        Show the colorbar.
    show_yticks
        Show the y ticks.
    normalize_to_zero_one
        Shift and scale the running average to [0, 1] per gene.
    return_data
        Return the timeseries data in addition to the axes if `True`.
    show
         Show the plot, do not return axis.
    save
        If `True` or a `str`, save the figure.
        A string is appended to the default filename.
        Infer the filetype if ending on \{`'.pdf'`, `'.png'`, `'.svg'`\}.
    ax
         A matplotlib axes object.

    Returns
    -------
    A :class:`~matplotlib.axes.Axes` object, if `ax` is `None`, else `None`.
    If `return_data`, return the timeseries data in addition to an axes.
    Nr.   r-   zWPass the key of the grouping with which you ran PAGA, using the parameter `groups_key`.r3  zc`pl.paga_path` requires computation of a pseudotime `tl.dpt` for ordering at single-cell resolutionrÞ   c                    s   t  | ˆ ¡S r±   )rˆ   Úmoving_average)Úa)r8  r`   ra   rA  E  s    z!paga_path.<locals>.moving_averager   c                 S   s   i | ]
}|g “qS r`   r`   )rl   Úannor`   r`   ra   ro   N  s      zpaga_path.<locals>.<dictcomp>zEach node/group needs to be in z (`groups_key`=z) not rÅ   c                    s   g | ]}ˆ | ‘qS r`   r`   )rl   r  )Úgroups_namesr`   ra   r{   \  s     zpaga_path.<locals>.<listcomp>z/Did not find data points that match `adata.obs[z].values == z`. Check whether `adata.obs[z%]` actually contains what you expect.r*   )rï   ÚautoZnearest)ZaspectÚinterpolationr©   )rH   FZboth)ZaxisÚwhichÚlength)r3   rÌ   )rÜ   gš™™™™™Ù?zcenter leftry   )r=   r	  Zbbox_to_anchorrH   z (a.u.)r   r   )ÚNr/   )rm   rø   )rú   rù   )ZfontdictZVega10r4  Ú	paga_pathrM   )rÓ   rE   Zdistance)HrO   ÚKeyErrorrT   r´   rµ   r!  r†   r   rþ   rX   ZgcarŠ   r¶   ÚsetrŒ   r  Zget_locrÒ   r„   rŽ   ZarangeZn_obsr  r…   ZargsortrÂ   r  r   ÚAr   Úcodesr‹   r  r  r¯   ZasarrayZsqueezeZimshowr  rÑ   Zset_yticklabelsr  r  Ztick_paramsÚgridrË   Zsubplots_adjustZlegendZ
set_xlabelZyticksZylabelr  Zget_positionZboundsZaxesr�   rK   ZListedColormapZastypeÚintrV   rˆ   rA  r  r  rÕ   r   ZautoshowrZ   rQ   rR   r  )>r&   r  r!  r®   r5  r;   r6  r7  r8  r·   r_   r?   r[   r9  r:  r;  r<  r=  r(   r)   r>  r?  r@  r@   rA   r3   Zax_was_nonerA  r  Zx_tick_locsZx_tick_labelsr.   Z	anno_dictZ
nodes_intsZgroups_names_setr  Z
nodes_strsZadata_XÚikeyÚkeyrC   Zigroupr.  ZidcsZ
idcs_groupr  rC  Zseriesrï   ZimgZxlabelÚ
matplotlibZ	ax_boundsZgroups_axisZyposZilabelZy_shiftZiannoZ	anno_axisZarrZcolor_map_annor+  r`   )rD  r8  ra   rJ  Ø  s‚   Xÿÿ
ÿ
ÿÿ
ÿÿ*þ


"








ü


üÿüü

þü
	


üÿ
ÿü




rJ  rÈ   c                    s  | j |  ¡ }| j | }|rpt||dd� t|jd ƒD ]4‰ |ˆ   ¡ d }	tj‡ fdd„|	D ƒ|	ddd� q8nŒt ¡  t	|ƒD ]z\‰ }
‡ fd	d„t	|
ƒD ƒ}‡ fd
d„t	|
ƒD ƒ}tj||ddd� |ˆ   ¡ d }	tj‡ fdd„|	D ƒ|
|	 ddd� q€t
jd||d� dS )zConnectivity of paga groups.F)r;   r@   r   r*   c                    s   g | ]}ˆ ‘qS r`   r`   ©rl   Új©r¹   r`   ra   r{   $  s     z"paga_adjacency.<locals>.<listcomp>rì   )r5   r÷   c                    s   g | ]\}}ˆ |krˆ ‘qS r`   r`   )rl   rU  rå   rV  r`   ra   r{   )  s      c                    s   g | ]\}}ˆ |kr|‘qS r`   r`   )rl   rU  rÀ   rV  r`   ra   r{   *  s      Úgrayc                    s   g | ]}ˆ ‘qS r`   r`   rT  rV  r`   ra   r{   -  s     Zpaga_connectivityrM   N)rO   Ztoarrayr   rÑ   rP   ZnonzerorX   r  Zfigurer„   r   rZ   )r&   Z	adjacencyZadjacency_treer?  r;   r@   rA   ZconnectivityZconnectivity_selectZ	neighborsÚcsrC   rD   r`   rV  ra   Úpaga_adjacency  s    

$&rY  )NFNNNNr    r!   Nr"   NNNFNNNr#   NNNN)r™   rÈ   TNNN)Ar  Úcollections.abcÚabcr²   Úpathlibr   Útypesr   Útypingr   r   r   r   r   r	   r
   ÚnumpyrŽ   ZpandasrQ   r
  Zanndatar   Zpandas.api.typesr   rS  r   rX   r   r   r   Zmatplotlib.axesr   r  r   r   Zscipy.sparser   Zsklearn.utilsr   r/   r   r   r   r   r   rˆ   r   r€   Z	_settingsr   Z_compatr   rP  ÚfloatrL   r¶   r˜   ZndarrayÚboolr-   rÖ   r  rJ  rY  r`   r`   r`   ra   Ú<module>   sà  $                      éç
õ ù
ùl×&



Ö  má

ã  `ÿä
ã  @      ù