U
    Åmœdq  ã                   @   s"  d dl mZmZmZ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mZ zd dlmZ W n( ek
r¬   G dd„ dƒZde_Y nX ddd ddddddddddœeeeeeee f  ejeeej eeeeee  ee ee eee dœdd„Z dS )é    )ÚOptionalÚTupleÚSequenceÚTypeN)Ú	natsorted)ÚAnnData)Úsparseé   )Ú_utils)Úloggingé   )Úrename_groupsÚrestrict_adjacency)ÚMutableVertexPartitionc                   @   s   e Zd ZdS )r   N)Ú__name__Ú
__module__Ú__qualname__© r   r   úM/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scanpy/tools/_leiden.pyr      s   r   zleidenalg.VertexPartitionÚleidenTéÿÿÿÿF)Úrestrict_toÚrandom_stateÚ	key_addedÚ	adjacencyÚdirectedÚuse_weightsÚn_iterationsÚpartition_typeÚneighbors_keyÚobspÚcopy)ÚadataÚ
resolutionr   r   r   r   r   r   r   r   r   r    r!   Úreturnc                K   s¬  zddl }W n tk
r(   tdƒ‚Y nX t|ƒ}t d¡}|rH|  ¡ n| } |dkrbt | ||
¡}|dk	r„|\}}t| |||ƒ\}}tj	||d�}|	dkr |j
}	|rÀt |jd ¡ tj¡|d< ||d< ||d	< |dk	rà||d
< |j||	f|Ž}t |j¡}|dk	�r*|dk�r|d7 }t| |||||ƒ}tj| d¡tttt |¡ƒƒd�| j|< i | jd< t|||d�| jd d< tjd|dtt |¡ƒ› d|›d�d� |�r¨| S dS )u¹
      Cluster cells into subgroups [Traag18]_.

    Cluster cells using the Leiden algorithm [Traag18]_,
    an improved version of the Louvain algorithm [Blondel08]_.
    It has been proposed for single-cell analysis by [Levine15]_.

    This requires having ran :func:`~scanpy.pp.neighbors` or
    :func:`~scanpy.external.pp.bbknn` first.

    Parameters
    ----------
    adata
        The annotated data matrix.
    resolution
        A parameter value controlling the coarseness of the clustering.
        Higher values lead to more clusters.
        Set to `None` if overriding `partition_type`
        to one that doesnâ€™t accept a `resolution_parameter`.
    random_state
        Change the initialization of the optimization.
    restrict_to
        Restrict the clustering to the categories within the key for sample
        annotation, tuple needs to contain `(obs_key, list_of_categories)`.
    key_added
        `adata.obs` key under which to add the cluster labels.
    adjacency
        Sparse adjacency matrix of the graph, defaults to neighbors connectivities.
    directed
        Whether to treat the graph as directed or undirected.
    use_weights
        If `True`, edge weights from the graph are used in the computation
        (placing more emphasis on stronger edges).
    n_iterations
        How many iterations of the Leiden clustering algorithm to perform.
        Positive values above 2 define the total number of iterations to perform,
        -1 has the algorithm run until it reaches its optimal clustering.
    partition_type
        Type of partition to use.
        Defaults to :class:`~leidenalg.RBConfigurationVertexPartition`.
        For the available options, consult the documentation for
        :func:`~leidenalg.find_partition`.
    neighbors_key
        Use neighbors connectivities as adjacency.
        If not specified, leiden looks .obsp['connectivities'] for connectivities
        (default storage place for pp.neighbors).
        If specified, leiden looks
        .obsp[.uns[neighbors_key]['connectivities_key']] for connectivities.
    obsp
        Use .obsp[obsp] as adjacency. You can't specify both
        `obsp` and `neighbors_key` at the same time.
    copy
        Whether to copy `adata` or modify it inplace.
    **partition_kwargs
        Any further arguments to pass to `~leidenalg.find_partition`
        (which in turn passes arguments to the `partition_type`).

    Returns
    -------
    `adata.obs[key_added]`
        Array of dim (number of samples) that stores the subgroup id
        (`'0'`, `'1'`, ...) for each cell.
    `adata.uns['leiden']['params']`
        A dict with the values for the parameters `resolution`, `random_state`,
        and `n_iterations`.
    r   NzjPlease install the leiden algorithm: `conda install -c conda-forge leidenalg` or `pip3 install leidenalg`.zrunning Leiden clustering)r   ÚweightÚweightsr   ÚseedZresolution_parameterr   Z_RÚU)ÚvaluesÚ
categories)r#   r   r   Úparamsz    finishedzfound z clusters and added
    z-, the cluster labels (adata.obs, categorical))ÚtimeÚdeep)Ú	leidenalgÚImportErrorÚdictÚloggÚinfor!   r
   Z_choose_graphr   Zget_igraph_from_adjacencyZRBConfigurationVertexPartitionÚnpÚarrayÚesZastypeZfloat64Zfind_partitionZ
membershipr   ÚpdZCategoricalr   ÚmapÚstrÚuniqueZobsZunsÚlen)r"   r#   r   r   r   r   r   r   r   r   r   r    r!   Zpartition_kwargsr.   ÚstartZrestrict_keyZrestrict_categoriesZrestrict_indicesÚgÚpartÚgroupsr   r   r   r      sr    Sÿ

ü

úþ
ýü)r   )!Útypingr   r   r   r   Únumpyr3   Zpandasr6   Znatsortr   Zanndatar   Zscipyr   Ú r
   r   r1   Z_utils_clusteringr   r   Zleidenalg.VertexPartitionr   r/   r   Úfloatr8   Z	AnyRandomZspmatrixÚboolÚintr   r   r   r   r   Ú<module>   sT    þò
ð