U
    md2                  !   @   s6  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 d dl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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dde(j)e(j*ddddddddddddddddfeee'ee+e'f f ee+ee+ f ee, e,e-eee.e.f  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+ ed ee	j/ e,ee, ee+e,df ee ee, ee. ee. ee. ee ee(e0df dddZ1dS )    )OptionalUnionMapping)Sequence)TupleN)AnnData)pyplot)rcParams)	Normalize   )logging)_doc_params)Literal   )fix_kwdscheck_colornorm)	ColorLike_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e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j ee ee ee ee dddZeee	feee ee dddZdd ZdS )
MatrixPlota      Allows the visualization of values using a color map.

    Parameters
    ----------
    {common_plot_args}
    title
        Title for the figure.
    expression_cutoff
        Expression cutoff that is used for binarizing the gene expression and
        determining the fraction of cells expressing given genes. A gene is
        expressed only if the expression value is greater than this threshold.
    mean_only_expressed
        If True, gene expression is averaged only over the cells
        expressing the given genes.
    standard_scale
        Whether or not to standardize that dimension between 0 and 1,
        meaning for each variable or group,
        subtract the minimum and divide each by its maximum.
    values_df
        Optionally, a dataframe with the values to plot can be given. The
        index should be the grouby categories and the columns the genes names.

    kwds
        Are passed to :func:`matplotlib.pyplot.scatter`.

    See also
    --------
    :func:`~scanpy.pl.matrixplot`: Simpler way to call MatrixPlot but with less options.
    :func:`~scanpy.pl.rank_genes_groups_matrixplot`: to plot marker genes identified
        using the :func:`~scanpy.tl.rank_genes_groups` function.

    Examples
    --------

    Simple visualization of the average expression of a few genes grouped by
    the category 'bulk_labels'.

    .. plot::
        :context: close-figs

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

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

    .. plot::
        :context: close-figs

        markers = {{'T-cell': 'CD3D', 'B-cell': 'CD79A', 'myeloid': 'CST3'}}
        sc.pl.MatrixPlot(adata, markers, groupby='bulk_labels').show()
    Zmatrixplot_zMean expression
in groupz
image.cmapgrayg?NF   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	values_dfvminvmaxvcenternormc                 K   s   t j| |||f||||||	|
|||||||||d| |d kr| jjdd }|dkr|j|ddd}|j|ddd	d}n@|dkr||d8 }||d 	d}n|d krn
t
d || _| j| _| j| _| j| _d S )	N)r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r2   r4   r5   r6   r7   r   )levelr"   r   )axisr!   z(Unknown type for standard_scale, ignored)r   __init__Zobs_tidyr%   ZmeansubmindivmaxZfillnaloggwarningr3   DEFAULT_COLORMAPcmapDEFAULT_EDGE_COLOR
edge_colorDEFAULT_EDGE_LWedge_lw)selfr#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   kwds rI   T/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scanpy/plotting/_matrixplot.pyr:   ]   sP    
zMatrixPlot.__init__rB   rD   rF   c                 C   s4   || j kr|| _ || jkr || _|| jkr0|| _| S )au          Modifies plot visual parameters.

        Parameters
        ----------
        cmap
            String denoting matplotlib color map.
        edge_color
            Edge color between the squares of matrix plot. Default is gray
        edge_lw
            Edge line width.

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

        Examples
        -------

        .. plot::
            :context: close-figs

            import scanpy as sc

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

        Change color map and turn off edges:


        .. plot::
            :context: close-figs

            (
                sc.pl.MatrixPlot(adata, markers, groupby='bulk_labels')
                .style(cmap='Blues', edge_color='none')
                .show()
            )

        rK   )rG   rB   rD   rF   rI   rI   rJ   style   s    0


zMatrixPlot.stylec                 C   st  | j  }| jd k	r(|jd d | jf }| jd k	rF|j| jd d f }| jrR|j}t	| j
d| j}d| j
krz| j
d= t| jj| jj| jj| jj}dD ]}|j| d qt| j
|| j| j|d}|j|f|}|j}|j}	tt|d }
||
 || tt|	d }| | |j!|	dddd	 |j"d
dd |#d |$t|d |%dt|	 |S )NrB   )topbottomleftrightg      ?)rB   Z	edgecolorZ	linewidthr7   g      ?Z   centerF)ZrotationZhaminorZbothZsmall)r9   Z	labelsizer   )&r3   copyZvar_names_idx_orderZilocr)   locZare_axes_swappedTplZget_cmaprH   getrB   r   Z
vboundnormr4   r5   r6   r7   ZspinesZset_linewidthr   rD   rF   ZpcolorindexcolumnsnpZarangelenZ
set_yticksZset_yticklabelsZ
set_xticksZset_xticklabelsZtick_paramsgridZset_ylimZset_xlim)rG   r2   Z	_color_dfrB   	normalizer9   rH   _Zy_labelsZx_labelsZy_ticksZx_ticksrI   rI   rJ   	_mainplot   sN    







zMatrixPlot._mainplot)NFr   NNNNNNNNNNNNNNN)__name__
__module____qualname____doc__DEFAULT_SAVE_PREFIXDEFAULT_COLOR_LEGEND_TITLEr	   rA   rC   rE   r   r   r   r   strr   r   boolintr   floatr   r   pd	DataFramer
   r:   r   rL   r`   rI   rI   rI   rJ   r      sp   8                  

H9r   )Zshow_save_axr   Zgroupby_plots_argsZvminmaxFr   r    )r#   r$   r%   r&   r'   r(   r+   
dendrogramr*   rB   colorbar_titler,   r-   r.   r/   r0   r1   r3   	swap_axesshowsaver2   
return_figr4   r5   r6   r7   returnc                 K   s   t | |f||||||||||||||||||d|}|rH|j|d |rT|  |j|	dj|
d}|rp|S |  tt j||d |dkrtj	n|}|s|
 S dS )a      Creates a heatmap of the mean expression values per group of each var_names.

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

    Parameters
    ----------
    {common_plot_args}
    {groupby_plots_args}
    {show_save_ax}
    {vminmax}
    kwds
        Are passed to :func:`matplotlib.pyplot.pcolor`.

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

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

    Examples
    --------

    .. plot::
        :context: close-figs

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

    Using var_names as dict:

    .. plot::
        :context: close-figs

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

    Get Matrix object for fine tuning:

    .. plot::
        :context: close-figs

        mp = sc.pl.matrixplot(adata, markers, 'bulk_labels', return_fig=True)
        mp.add_totals().style(edge_color='black').show()

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

    .. plot::
        :context: close-figs

        axes_dict = mp.get_axes()
    )r%   r&   r'   r(   r1   r*   r+   r,   r-   r.   r/   r0   r3   r2   r4   r5   r6   r7   )Zdendrogram_key)rB   )r*   )rp   rq   N)r   Zadd_dendrogramro   rL   ZlegendZmake_figurer   re   r   ZautoshowZget_axes)r#   r$   r%   r&   r'   r(   r+   rm   r*   rB   rn   r,   r-   r.   r/   r0   r1   r3   ro   rp   rq   r2   rr   r4   r5   r6   r7   rH   mprI   rI   rJ   
matrixplot  sJ    cru   )2typingr   r   r   r   r   numpyr[   Zpandasrk   Zanndatar   Z
matplotlibr   rW   r	   Zmatplotlib.colorsr
    r   r?   _utilsr   Z_compatr   r   r   r   r   r   Z	_settingsr   Z_docsr   r   r   Z_baseplot_classr   r   r   r   rA   rf   rg   rh   ri   rj   rl   dictru   rI   rI   rI   rJ   <module>   s    |


