U
    mdq                     @   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leidenTF)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
}	|rt|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    
