U
    mdf                  	   @   s   d Z ddl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 ejejdd	d
Zdeeee ee eeee f ddddZdS )z)Calculate density of cells in embeddings
    N)AnnData)UnionOptionalSequence   )logging)sanitize_anndata)xyc                 C   sN   ddl m} t| |g}|||}t|}t|}|| ||  }|S )z:    Calculates the density of points in 2 dimensions.
    r   )gaussian_kde)Zscipy.statsr   npZvstackminmax)r	   r
   r   ZxyzZmin_zZmax_zZscaled_z r   X/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scanpy/tools/_embedding_density.py_calc_density   s    

r   umap)adatabasisgroupby	key_added
componentsreturnc                 C   sH  t |  td| | }|dkr,d}d| |  krNtd| d|dkrZd}t|trn|d	}t	
|td
 }t|dkrtd|dkr|d
7 }|dk	r|| jkrtd|d| j| jjdkrt|d|dk	r|}n$|dk	r| d| }n
| d}|dk	r| j| jj}t	| j}|D ]^}| j| |k}	| jd|  |	|d f }
| jd|  |	|d
 f }t|
|}|||	< qB|| j|< nP| jd|  dd|d f }
| jd|  dd|d
 f }t|
|| j|< |dkr|d
7 }t|| d| j| d< td| d| d dS )a	      Calculate the density of cells in an embedding (per condition).

    Gaussian kernel density estimation is used to calculate the density of
    cells in an embedded space. This can be performed per category over a
    categorical cell annotation. The cell density can be plotted using the
    `pl.embedding_density` function.

    Note that density values are scaled to be between 0 and 1. Thus, the
    density value at each cell is only comparable to densities in
    the same category.

    Beware that the KDE estimate used (`scipy.stats.gaussian_kde`) becomes
    unreliable if you don't have enough cells in a category.

    This function was written by Sophie Tritschler and implemented into
    Scanpy by Malte Luecken.

    Parameters
    ----------
    adata
        The annotated data matrix.
    basis
        The embedding over which the density will be calculated. This embedded
        representation should be found in `adata.obsm['X_[basis]']``.
    groupby
        Key for categorical observation/cell annotation for which densities
        are calculated per category.
    key_added
        Name of the `.obs` covariate that will be added with the density
        estimates.
    components
        The embedding dimensions over which the density should be calculated.
        This is limited to two components.

    Returns
    -------
    Updates `adata.obs` with an additional field specified by the `key_added`
    parameter. This parameter defaults to `[basis]_density_[groupby]`, where
    `[basis]` is one of `umap`, `diffmap`, `pca`, `tsne`, or `draw_graph_fa`
    and `[groupby]` denotes the parameter input.
    Updates `adata.uns` with an additional field `[key_added]_params`.

    Examples
    --------

    .. plot::
        :context: close-figs

        import scanpy as sc
        adata = sc.datasets.pbmc68k_reduced()
        sc.tl.umap(adata)
        sc.tl.embedding_density(adata, basis='umap', groupby='phase')
        sc.pl.embedding_density(
            adata, basis='umap', key='umap_density_phase', group='G1'
        )

    .. plot::
        :context: close-figs

        sc.pl.embedding_density(
            adata, basis='umap', key='umap_density_phase', group='S'
        )

    .. currentmodule:: scanpy

    See also
    --------
    pl.embedding_density
    zcomputing density on faZdraw_graph_faZX_z7Cannot find the embedded representation `adata.obsm['X_z!']`. Compute the embedding first.Nz1,2,   r   z/Please specify exactly 2 components, or `None`.ZdiffmapzCould not find z `.obs` column.categoryz) column does not contain categorical dataZ	_density_Z_densityr   )Z	covariater   _paramszadded
    'z', densities (adata.obs)
    'z_params', parameter (adata.uns))r   logginfolowerZ	obsm_keys
ValueError
isinstancestrsplitr   arrayZastypeintlenZobsZdtypenamecat
categoriesZzerosZn_obsZobsmr   dicttolistZunshint)r   r   r   r   r   Zdensity_covariater+   Zdensity_valuesr*   Zcat_maskZembed_xZembed_yZ
dens_embedr   r   r   embedding_density    sd    P







  
 r/   )r   NNN)__doc__numpyr   Zanndatar   typingr   r   r    r   r   _utilsr   Zndarrayr   r$   r/   r   r   r   r   <module>   s$       