U
    mdi                  '   @   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rn
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sd
}|
|
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rd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rt
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       





