U
    Åmœd³2  ã                !   @   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rÂn
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¡ qœt| 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r–t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     |ü
å

ã