U
    Åmœd:!  ã                   @   sf  d dl mZ d dlmZmZ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mZ d
dlmZmZ d
dlmZ d
dl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ei ƒdddfeee# ej$eee%ee% f  e%ee ed e&e&eee   ee%ef ee% ee% e&ee dœdd„Z'dS )é    )ÚMappingProxyType)ÚOptionalÚTupleÚSequenceÚTypeÚMappingÚAnyN)ÚAnnData)Ú	natsorted)Úspmatrix)Úversioné   )Úrename_groupsÚrestrict_adjacencyé   )Ú_utilsÚlogging)ÚLiteral)Ú_choose_graph)ÚMutableVertexPartitionc                   @   s   e Zd ZdS )r   N)Ú__name__Ú
__module__Ú__qualname__© r   r   úN/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scanpy/tools/_louvain.pyr      s   r   zlouvain.VertexPartitionÚlouvainÚvtraagTF)r   ÚigraphÚrapids)ÚadataÚ
resolutionÚrandom_stateÚrestrict_toÚ	key_addedÚ	adjacencyÚflavorÚdirectedÚuse_weightsÚpartition_typeÚpartition_kwargsÚneighbors_keyÚobspÚcopyÚreturnc           $      C   s–  t |
ƒ}
t d¡}|dkr*|	dk	r*tdƒ‚|r6|  ¡ n| } |dkrNt| ||ƒ}|dk	rp|\}}t| |||ƒ\}}|dk�rˆ|dkr”|dk	r”t d¡ |r¤|dkr¤d}|s²t d	¡ t	j
||d
�}|rÞt |jd ¡ tj¡}nd}|dk�rlddl}|	dk�r|j}	|dk	�r||
d< |�r$||
d< t |j¡t d¡k �rH| |¡ n||
d< t d¡ |j||	f|
Ž}n|j|d�}t |j¡}�n`|dk�r‚ddl}ddl}| |j¡}| |j¡}|�rø| ¡ \}}|||f }t|tj ƒ�rì|j!}| |¡}nd}| "¡ }t#|dƒ�r | $|||¡ n| %|||¡ t d¡ |dk	�rV|j||d�\}}n| |¡\}}| &¡  'd¡dg  (¡  )¡ }nf|dk�ràddl*}ddl+} | "|¡}|  ,|¡}!tj-t.|!ƒt/d�}|! 0¡ D ]\}"}#|#||"< �qÊntdƒ‚|dk	�r|dk�r|d7 }t1| |||||ƒ}t2j3| d¡t4t5t6t 7|¡ƒƒd�| j8|< i | j9d< t ||d �| j9d d!< tjd"|d#t.t 7|¡ƒ› d$|›d%�d&� |�r’| S dS )'uD
      Cluster cells into subgroups [Blondel08]_ [Levine15]_ [Traag17]_.

    Cluster cells using the Louvain algorithm [Blondel08]_ in the implementation
    of [Traag17]_. The Louvain algorithm has been proposed for single-cell
    analysis by [Levine15]_.

    This requires having ran :func:`~scanpy.pp.neighbors` or
    :func:`~scanpy.external.pp.bbknn` first,
    or explicitly passing a ``adjacency`` matrix.

    Parameters
    ----------
    adata
        The annotated data matrix.
    resolution
        For the default flavor (``'vtraag'``) or for ```RAPIDS```, you can provide a
        resolution (higher resolution means finding more and smaller clusters),
        which defaults to 1.0.
        See â€œTime as a resolution parameterâ€� in [Lambiotte09]_.
    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
        Key under which to add the cluster labels. (default: ``'louvain'``)
    adjacency
        Sparse adjacency matrix of the graph, defaults to neighbors connectivities.
    flavor
        Choose between to packages for computing the clustering.
        ``'vtraag'`` is much more powerful, and the default.
    directed
        Interpret the ``adjacency`` matrix as directed graph?
    use_weights
        Use weights from knn graph.
    partition_type
        Type of partition to use.
        Only a valid argument if ``flavor`` is ``'vtraag'``.
    partition_kwargs
        Key word arguments to pass to partitioning,
        if ``vtraag`` method is being used.
    neighbors_key
        Use neighbors connectivities as adjacency.
        If not specified, louvain looks .obsp['connectivities'] for connectivities
        (default storage place for pp.neighbors).
        If specified, louvain 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
        Copy adata or modify it inplace.

    Returns
    -------
    :obj:`None`
        By default (``copy=False``), updates ``adata`` with the following fields:

        ``adata.obs['louvain']`` (:class:`pandas.Series`, dtype ``category``)
            Array of dim (number of samples) that stores the subgroup id
            (``'0'``, ``'1'``, ...) for each cell.

    :class:`~anndata.AnnData`
        When ``copy=True`` is set, a copy of ``adata`` with those fields is returned.
    zrunning Louvain clusteringr   NzD`partition_type` is only a valid argument when `flavour` is "vtraag">   r   r   r   z8`resolution` parameter has no effect for flavor "igraph"Fz    using the undirected graph)r&   Úweightr   Zresolution_parameterÚweightsz0.7.0Úseedz/    using the "louvain" package of Traag (2017))r/   r   Úadd_adj_listz)    using the "louvain" package of rapids)r    ZvertexÚ	partitionZtaynaud)Zdtypez7`flavor` needs to be "vtraag" or "igraph" or "taynaud".r   Z_RÚU)ÚvaluesÚ
categories)r    r!   Úparamsz    finishedzfound z clusters and added
    z-, the cluster labels (adata.obs, categorical))ÚtimeÚdeep):ÚdictÚloggÚinfoÚ
ValueErrorr,   r   r   ÚwarningÚdebugr   Zget_igraph_from_adjacencyÚnpÚarrayÚesZastypeZfloat64r   ZRBConfigurationVertexPartitionr   ÚparseÚ__version__Zset_rng_seedZfind_partitionZcommunity_multilevelZ
membershipÚcudfÚcugraphZSeriesZindptrÚindicesZnonzeroÚ
isinstanceÚmatrixÚA1ZGraphÚhasattrr1   Zfrom_cudf_adjlistZ	to_pandasZsort_valuesZto_numpyZravelZnetworkxÚ	communityZbest_partitionZzerosÚlenÚintÚitemsr   ÚpdZCategoricalr
   ÚmapÚstrÚuniqueZobsZuns)$r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   ÚstartZrestrict_keyZrestrict_categoriesZrestrict_indicesÚgr/   r   ÚpartÚgroupsrD   rE   ÚoffsetsrF   ÚsourcesÚtargetsZlouvain_partsÚ_ÚnxrK   r2   ÚkÚvr   r   r   r      sÚ    R
ÿü






þý


ÿÿ
ÿ




úþ
þü)(Útypesr   Útypingr   r   r   r   r   r   Únumpyr?   ZpandasrO   Zanndatar	   Znatsortr
   Zscipy.sparser   Ú	packagingr   Z_utils_clusteringr   r   Ú r   r   r:   Z_compatr   r   Zlouvain.VertexPartitionr   ÚImportErrorr   ÚfloatZ	AnyRandomrQ   Úboolr   r   r   r   r   Ú<module>   s\    ò

ñ