U
    ÅmœdÊi  ã                '   @   sh  d dl mZmZmZ d dl m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mZ dd	l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" ddl#m$Z$m%Z%m&Z& ee d�G dd„ de$ƒƒZ'ee!e e%e"d�dddde'j(dddddddde'j)e'j*e'j+e'j,e'j-ddddde'j.e'j/dddddfeee&ee0e&f f ee0ee0 f e1ee1 e2ee0 ee0 eee3e3f  ee1e0f ee0 eeee2e2f   eee0  eed  ee3 ee0 e1ee3e1f e2ed ee1 eee0  e1ee1 ee1e0df ee1 ee0 ee0 ee ee3 ee3 ee3 ee ee'e4df dœ"dd„ƒZ5dS )é    )ÚOptionalÚUnionÚMapping)ÚSequence)ÚTupleN)ÚAnnData)Úpyplot)Úis_color_likeÚ	Normalizeé   )Úlogging)Ú_doc_params)ÚLiteralé   )Úmake_grid_specÚcheck_colornorm)Ú_AxesSubplot)Úsavefig_or_show)Úsettings)Údoc_common_plot_argsÚdoc_show_save_axÚdoc_vboundnorm)ÚBasePlotÚdoc_common_groupby_plot_argsÚ	_VarNames)Úcommon_plot_argsc                   @   sˆ  e Zd ZdZdZdZdZdZdZdZ	dZ
dZd	ZdZdZd
Zd
ZdZdZdeeeeeef f eeee f ee eeeee  ee eeeef  ee eeeeef   eee  ee ee ed ee ee ee ee ee  dœdd„Z!eeee	e
eeeeeefee ee eeeef  ee ee ee eed  ee eeeef  ee ee dœdd„Z"dd„ Z#dd„ Z$dd„ Z%dS )ÚStackedViolinu›
      Stacked violin plots.

    Makes a compact image composed of individual violin plots
    (from :func:`~seaborn.violinplot`) stacked on top of each other.
    Useful to visualize gene expression per cluster.

    Wraps :func:`seaborn.violinplot` for :class:`~anndata.AnnData`.

    Parameters
    ----------
    {common_plot_args}
    title
        Title for the figure
    stripplot
        Add a stripplot on top of the violin plot.
        See :func:`~seaborn.stripplot`.
    jitter
        Add jitter to the stripplot (only when stripplot is True)
        See :func:`~seaborn.stripplot`.
    size
        Size of the jitter points.
    order
        Order in which to show the categories. Note: if `dendrogram=True`
        the categories order will be given by the dendrogram and `order`
        will be ignored.
    scale
        The method used to scale the width of each violin.
        If 'width' (the default), each violin will have the same width.
        If 'area', each violin will have the same area.
        If 'count', a violinâ€™s width corresponds to the number of observations.
    row_palette
        The row palette determines the colors to use for the stacked violins.
        The value should be a valid seaborn or matplotlib palette name
        (see :func:`~seaborn.color_palette`).
        Alternatively, a single color name or hex value can be passed,
        e.g. `'red'` or `'#cc33ff'`.
    standard_scale
        Whether or not to standardize a dimension between 0 and 1,
        meaning for each variable or observation,
        subtract the minimum and divide each by its maximum.
    swap_axes
         By default, the x axis contains `var_names` (e.g. genes) and the y axis
         the `groupby` categories. By setting `swap_axes` then x are the `groupby`
         categories and y the `var_names`. When swapping
         axes var_group_positions are no longer used
    kwds
        Are passed to :func:`~seaborn.violinplot`.


    See also
    --------
    :func:`~scanpy.pl.stacked_violin`: simpler way to call StackedViolin but with less
        options.
    :func:`~scanpy.pl.violin` and :func:`~scanpy.pl.rank_genes_groups_stacked_violin`:
        to plot marker genes identified using :func:`~scanpy.tl.rank_genes_groups`

    Examples
    -------

    >>> import scanpy as sc
    >>> adata = sc.datasets.pbmc68k_reduced()
    >>> markers = ['C1QA', 'PSAP', 'CD79A', 'CD79B', 'CST3', 'LYZ']
    >>> sc.pl.StackedViolin(adata, markers, groupby='bulk_labels', dendrogram=True)

    Using var_names as dict:

    >>> markers = {{'T-cell': 'CD3D', 'B-cell': 'CD79A', 'myeloid': 'CST3'}}
    >>> sc.pl.StackedViolin(adata, markers, groupby='bulk_labels', dendrogram=True)
    Zstacked_violin_zMedian expression
in groupZBluesFr   çš™™™™™É?NÚwidthç      à?r   é   )ÚvarÚgroup)ÚadataÚ	var_namesÚgroupbyÚuse_rawÚlogÚnum_categoriesÚcategories_orderÚtitleÚfigsizeÚgene_symbolsÚvar_group_positionsÚvar_group_labelsÚvar_group_rotationÚlayerÚstandard_scaleÚaxÚvminÚvmaxÚvcenterÚnormc                 K   sX  t j| |||f||||||	|
|||||||||dœ|—Ž |dkr~| jj| j d¡dd�| _| jj| j d¡dd� d¡| _nN|dkr¸|  j| j d¡8  _| j| j d¡  d¡| _n|d krÂn
t 	d¡ | j
| _| j| _| j| _| j| _| j| _| j| _| j| _| j| _| j| _| j d| j¡ | j d	| j¡ | j d
| j ¡ | j d| j!¡ d S )N)r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r2   r3   r4   r5   r6   Úobsr   r   )Úaxisr!   z(Unknown type for standard_scale, ignoredÚcutÚinnerÚ	linewidthÚscale)"r   Ú__init__Úobs_tidyÚsubÚminÚdivÚmaxZfillnaÚloggÚwarningÚDEFAULT_COLORMAPÚcmapÚDEFAULT_ROW_PALETTEÚrow_paletteÚDEFAULT_STRIPPLOTÚ	stripplotÚDEFAULT_JITTERÚjitterÚDEFAULT_JITTER_SIZEÚjitter_sizeÚDEFAULT_PLOT_YTICKLABELSÚplot_yticklabelsÚDEFAULT_YLIMÚylimÚDEFAULT_PLOT_X_PADDINGÚplot_x_paddingÚDEFAULT_PLOT_Y_PADDINGÚplot_y_paddingÚkwdsÚ
setdefaultÚDEFAULT_CUTÚDEFAULT_INNERÚDEFAULT_LINE_WIDTHÚDEFAULT_SCALE)Úselfr#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   rW   © r^   úX/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scanpy/plotting/_stacked_violin.pyr=      s^    üìë"
zStackedViolin.__init__©ZareaÚcountr   )rF   rJ   rL   rN   r;   rH   r<   ÚyticklabelsrR   Ú	x_paddingÚ	y_paddingc                 C   sú   || j kr|| _ || jkr,|| _| j| jd< || jkr<|| _|| jkrL|| _|| jkr\|| _|| jkr‚|| _| jrzd| _ntj	| _|	| j
kr’|	| _
|
| jkr¢|
| _|| jkr²|| _|| jd krÔ|| jkrÔ|| jd< || jd krö|| jkrö|| jd< | S )u*          Modifies plot visual parameters

        Parameters
        ----------
        cmap
            String denoting matplotlib color map.
        stripplot
            Add a stripplot on top of the violin plot.
            See :func:`~seaborn.stripplot`.
        jitter
            Add jitter to the stripplot (only when stripplot is True)
            See :func:`~seaborn.stripplot`.
        jitter_size
            Size of the jitter points.
        linewidth
            linewidth for the violin plots.
        row_palette
            The row palette determines the colors to use for the stacked violins.
            The value should be a valid seaborn or matplotlib palette name
            (see :func:`~seaborn.color_palette`).
            Alternatively, a single color name or hex value can be passed,
            e.g. `'red'` or `'#cc33ff'`.
        scale
            The method used to scale the width of each violin.
            If 'width' (the default), each violin will have the same width.
            If 'area', each violin will have the same area.
            If 'count', a violinâ€™s width corresponds to the number of observations.
        yticklabels
            Set to true to view the y tick labels.
        ylim
            minimum and maximum values for the y-axis. If set. All rows will have
            the same y-axis range. Example: ylim=(0, 5)
        x_padding
            Space between the plot left/right borders and the violins. A unit
            is the distance between the x ticks.
        y_padding
            Space between the plot top/bottom borders and the violins. A unit is
            the distance between the y ticks.

        Returns
        -------
        :class:`~scanpy.pl.StackedViolin`

        Examples
        -------
        >>> adata = sc.datasets.pbmc68k_reduced()
        >>> markers = ['C1QA', 'PSAP', 'CD79A', 'CD79B', 'CST3', 'LYZ']

        Change color map and turn off edges

        >>> sc.pl.MatrixPlot(adata, markers, groupby='bulk_labels')        ...               .style(row_palette='Blues', linewidth=0).show()

        Úcolorg333333Ó?r;   r<   )rF   rH   rW   rJ   rL   rN   rP   Úwspacer   ZDEFAULT_WSPACErR   rT   rV   r[   r\   )r]   rF   rJ   rL   rN   r;   rH   r<   rb   rR   rc   rd   r^   r^   r_   ÚstyleÊ   s6    G










zStackedViolin.stylec                    sÚ  | j  ¡ }| jd k	r(|jd d …| jf }| jd k	rF|jj| jdd�|_|jdd� ¡ ‰ | j	rbˆ j
‰ t | j d| j¡¡}d| jkrŠ| jd= t| jj| jj| jj| jjƒ}||ˆ jƒƒ}| j}| j}|  |||ˆ ||¡ | d¡ | d¡ |j d¡ | ˆ jd | | ¡ |  | ˆ jd | ¡ t! "ˆ jd ¡d	 }| #|¡ |j$‡ fd
d„t%|ƒD ƒdd� t! "ˆ jd ¡d	 }	| &|	¡ ˆ j'}
|j(|
ddd� t)dd„ |
D ƒƒdk�r¾|j*ddd� |j*ddd� | +d¡ |S )NT)Zorderedr   )ÚlevelrF   Úonç        r   r   c                    s   g | ]\}}ˆ j | ‘qS r^   )Úindex)Ú.0ÚidxÚ_©Ú	_color_dfr^   r_   Ú
<listcomp>g  s     z+StackedViolin._mainplot.<locals>.<listcomp>F)ÚminorÚcenter)rr   Zhac                 S   s   g | ]}t |ƒ‘qS r^   )Úlen)rl   Úxr^   r^   r_   rq   p  s     r   ru   éZ   )r8   ZlabelrotationZbothZsmall)r8   Ú	labelsize),r>   ÚcopyZvar_names_idx_orderZilocr)   rk   Úreorder_categoriesr%   ZmedianÚare_axes_swappedÚTÚplZget_cmaprW   ÚgetrF   r   Z
vboundnormr3   r4   r5   r6   ÚvaluesrT   rV   Ú_make_rows_of_violinplotsZset_frame_onr8   ÚpatchZ	set_alphaÚset_ylimÚshapeZset_xlimÚnpZarangeÚ
set_yticksÚset_yticklabelsÚ	enumerateZ
set_xticksÚcolumnsÚset_xticklabelsrB   Útick_paramsÚgrid)r]   r2   Ú_matrixrF   Ú	normalizeÚcolormap_arrayÚx_spacer_sizeÚy_spacer_sizeZy_ticksZx_ticksÚlabelsr^   ro   r_   Ú	_mainplot1  sf    


 ÿ
ü     ÿ


 ÿ

zStackedViolin._mainplotc                 C   sJ  dd l }| j d| j¡}d| jkr*| jd= |d k	rht|ƒrL|g|jd  }	n|j||jd d�}	d| _nd g|jd  }	dd„ t|j	ƒD ƒ|_	t
 |jdd�¡ ¡ jd	d
|jjdddid�}
|
d
  d¡j |j	¡|
d
< |
d  d¡j |jj¡|
d< |j\}}|gdg|  |g }|gdg|  |g }t||d |d | j�rHdndd||d�\}}g }t|jƒD ]Ü\}}| ||d dd…f ¡}| |¡ |	| d k�r´||d d …f }nd }| j�sÔd
}|
|
j|k }nd}|
|
j|j	| k }|jf |d|d|||	| dœ| j—Ž}| j�r6|j|d|| jd| j|d�}|  ||¡ �qhd S )Nr   re   )Zn_colorsrj   c                 S   s   g | ]\}}|› d |› �‘qS )rn   r^   )rl   rm   ru   r^   r^   r_   rq   Œ  s     z;StackedViolin._make_rows_of_violinplots.<locals>.<listcomp>F)ZdropnaZlevel_1ÚgenesÚ
categoriesr~   )r‡   Úcategoryr   r   r   )ZnrowsZncolsZhspacerf   Úheight_ratiosÚwidth_ratioséÿÿÿÿÚvertical)ru   ÚyÚdataZorientr2   Úpalettere   Úblack)ru   r™   rš   rL   re   Úsizer2   ) ZseabornrW   r}   rH   r	   r‚   Zcolor_paletteZlegends_widthr†   r‡   ÚpdZ	DataFrameÚstackZreset_indexÚrenamerk   ÚnameZastypeÚcatry   r“   r   rP   Zadd_subplotÚappendrz   r’   Z
violinplotrJ   rL   rN   Ú_setup_violin_axes_ticks)r]   r2   r‹   r�   rp   rŽ   r�   ZsnsrH   Z
row_colorsZdfZnum_rowsÚnum_colsr•   r–   ZfigÚgsZaxs_listrm   Z	row_labelÚrow_axZpalette_colorsru   Z_dfr^   r^   r_   r   w  s–    

   ýýÿÿÿþÿ	
ù
	
ùøù
z'StackedViolin._make_rows_of_violinplotsc                 C   sP  |  d¡ | jdk	r | | j¡ | jr0| d¡ | jrödD ]}|j|  d¡ q:|jd  d¡ |jd  	d|f¡ |j
ddd	d	dd
d� ddlm} |j |jddddgd�¡ | ¡ }| |d |d g¡ | ¡ }|d  d¡ |d  d¡ n$| d¡ | g ¡ |j
dddd� | d¡ | d¡ | g ¡ |j
dddddd� dS )z_
        Configures each of the violin plot axes ticks like remove or add labels etc.

        FNr'   )ÚtopÚbottomÚleftÚrightg      ø?rš   r™   Tzx-small)r8   rª   r«   Z
labelrightZ	labelleftrw   r   r   r   g333333ó?é
   )ZnbinsZstepsr—   r©   r¨   Úoff)r8   rª   r«   Ú ru   )r8   r©   r¨   ZlabeltopZlabelbottom)rŠ   rR   r�   r'   Z
set_yscalerP   ZspinesZset_visibleZset_linewidthZset_positionr‰   Zmatplotlib.tickerÚtickerZyaxisZset_major_locatorZMaxNLocatorZ
get_yticksr„   Zget_yticklabelsZset_var8   r…   Z
set_ylabelZ
set_xlabelrˆ   )r]   r§   r¥   Zspiner¯   ZyticksZ
ticklabelsr^   r^   r_   r¤   ç  sP    


úÿ




    ÿz&StackedViolin._setup_violin_axes_ticks)NFr    NNNNNNNNNNNNNN)&Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚDEFAULT_SAVE_PREFIXÚDEFAULT_COLOR_LEGEND_TITLErE   rI   rK   rM   r[   rG   r\   rO   rQ   rS   rU   rY   rZ   r   r   r   r   Ústrr   r   ÚboolÚintr   Úfloatr   r   r
   r=   rg   r‘   r   r¤   r^   r^   r^   r_   r      s¤   G
                 ë

ëMô
ôgFpr   )Zshow_save_axr   Zgroupby_plots_argsZvminmaxFr    )r!   r7   r`   )"r#   r$   r%   r'   r&   r(   r*   Úcolorbar_titler+   Ú
dendrogramr,   r-   r.   r1   r/   r0   rJ   rL   r�   r<   rb   ÚorderÚ	swap_axesÚshowÚsaveÚ
return_figrH   rF   r2   r3   r4   r5   r6   Úreturnc!           #      K   sÈ   t | |f||||||||
||||||||| dœ|!—Ž}"|	rF|"j|	d� |rR|" ¡  |"j||||||! d|¡||! dt j¡d�j|d�}"|rŽ|"S |" ¡  tt j	||d� |dkr´t
jn|}|sÄ|" ¡ S dS )	uÝ      Stacked violin plots.

    Makes a compact image composed of individual violin plots
    (from :func:`~seaborn.violinplot`) stacked on top of each other.
    Useful to visualize gene expression per cluster.

    Wraps :func:`seaborn.violinplot` for :class:`~anndata.AnnData`.

    This function provides a convenient interface to the
    :class:`~scanpy.pl.StackedViolin` class. If you need more flexibility,
    you should use :class:`~scanpy.pl.StackedViolin` directly.

    Parameters
    ----------
    {common_plot_args}
    {groupby_plots_args}
    stripplot
        Add a stripplot on top of the violin plot.
        See :func:`~seaborn.stripplot`.
    jitter
        Add jitter to the stripplot (only when stripplot is True)
        See :func:`~seaborn.stripplot`.
    size
        Size of the jitter points.
    order
        Order in which to show the categories. Note: if `dendrogram=True`
        the categories order will be given by the dendrogram and `order`
        will be ignored.
    scale
        The method used to scale the width of each violin.
        If 'width' (the default), each violin will have the same width.
        If 'area', each violin will have the same area.
        If 'count', a violinâ€™s width corresponds to the number of observations.
    yticklabels
        Set to true to view the y tick labels.
    row_palette
        Be default, median values are mapped to the violin color using a
        color map (see `cmap` argument). Alternatively, a 'row_palette` can
        be given to color each violin plot row using a different colors.
        The value should be a valid seaborn or matplotlib palette name
        (see :func:`~seaborn.color_palette`).
        Alternatively, a single color name or hex value can be passed,
        e.g. `'red'` or `'#cc33ff'`.
    {show_save_ax}
    {vminmax}
    kwds
        Are passed to :func:`~seaborn.violinplot`.

    Returns
    -------
    If `return_fig` is `True`, returns a :class:`~scanpy.pl.StackedViolin` object,
    else if `show` is false, return axes dict

    See also
    --------
    :class:`~scanpy.pl.StackedViolin`: The StackedViolin class can be used to to control
        several visual parameters not available in this function.
    :func:`~scanpy.pl.rank_genes_groups_stacked_violin` to plot marker genes identified
        using the :func:`~scanpy.tl.rank_genes_groups` function.

    Examples
    -------

    Visualization of violin plots of a few genes grouped by the category 'bulk_labels':

    >>> import scanpy as sc
    >>> adata = sc.datasets.pbmc68k_reduced()
    >>> markers = ['C1QA', 'PSAP', 'CD79A', 'CD79B', 'CST3', 'LYZ']
    >>> sc.pl.stacked_violin(adata, markers, groupby='bulk_labels', dendrogram=True)

    Same visualization but passing var_names as dict, which adds a grouping of
    the genes on top of the image:

    >>> markers = {{'T-cell': 'CD3D', 'B-cell': 'CD79A', 'myeloid': 'CST3'}}
    >>> sc.pl.stacked_violin(adata, markers, groupby='bulk_labels', dendrogram=True)

    Get StackedViolin object for fine tuning

    >>> vp = sc.pl.stacked_violin(adata, markers, 'bulk_labels', return_fig=True)
    >>> vp.add_totals().style(ylim=(0,5)).show()

    The axes used can be obtained using the get_axes() method:

    >>> axes_dict = vp.get_axes()

    )r%   r&   r'   r(   r1   r*   r+   r,   r-   r.   r/   r0   r2   r3   r4   r5   r6   )Zdendrogram_keyr<   r;   )rF   rJ   rL   rN   rH   r<   rb   r;   )r*   )r¾   r¿   N)r   Zadd_dendrogramr½   rg   r}   r[   ZlegendZmake_figurer   r´   r   ZautoshowZget_axes)#r#   r$   r%   r'   r&   r(   r*   rº   r+   r»   r,   r-   r.   r1   r/   r0   rJ   rL   r�   r<   rb   r¼   r½   r¾   r¿   rÀ   rH   rF   r2   r3   r4   r5   r6   rW   Zvpr^   r^   r_   Ústacked_violin%  s`     þíì
ø	÷
rÂ   )6Útypingr   r   r   r   r   Únumpyrƒ   Zpandasrž   Zanndatar   Z
matplotlibr   r|   Zmatplotlib.colorsr	   r
   r®   r   rC   Ú_utilsr   Z_compatr   r   r   r   r   Z	_settingsr   Z_docsr   r   r   Z_baseplot_classr   r   r   r   rµ   rI   rK   rM   r\   rO   rG   rE   r¶   r·   r¸   r¹   ÚdictrÂ   r^   r^   r^   r_   Ú<module>   s¼       ü
ß




Ý