U
    md:!                     @   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	rtd |r|dkrd}|std	 t	j
||d
}|rt|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rd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rddl*}ddl+} |"|}| ,|}!tj-t.|!t/d}|!0 D ]\}"}#|#||"< qn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\    

