U
    md{                     @   s  d dl mZ d dlmZmZmZmZmZmZm	Z	m
Z
 d dlZd dl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 dd	lmZ dd
lmZmZmZ ddlmZ ddl m!Z!m"Z"m#Z# ddlm$Z$ dZ%e$j&Z&ed Z'eej(ej(ge)f Z*ed Z+ed Z,ee+e,f Z-ee#e"dddddd ddei ddf
ee.ee. ee/ e0eee' ee-e*f ee/ef ee/ e0ee dddZ1G dd deZ2ee/ee/ej(f f Z3e3e	e2ddf dddZ4ddei ddfeej(ef e.eee-e*f ee/ef e0e0dd d!Z5d=ej(e.e-d"d#d$Z6d%d& Z7d>d(d)Z8d*d+ Z9e.d,d-d.Z:e.d,d/d0Z;eej(d1d2d3Z<ed4d5d6Z=d7d8 Z>G d9d: d:Z?G d;d< d<Z@dS )?    )MappingProxyType)UnionOptionalAnyMappingCallable
NamedTuple	GeneratorTupleN)AnnData)issparse
coo_matrix
csr_matrix)check_random_state   )logging)_utils)_doc_params	AnyRandomNeighborsView)Literal)_choose_representationdoc_use_rep	doc_n_pcs)settings   )umapgaussrapids)Z	cityblockZcosine	euclideanl1l2Z	manhattan)Z
braycurtisZcanberraZ	chebyshevZcorrelationZdiceZhammingZjaccardZ	kulsinskiZmahalanobisZ	minkowskiZrogerstanimotoZ
russellraoZ
seuclideanZsokalmichenerZsokalsneathZsqeuclideanZyulen_pcsuse_repTr   r   F)adatan_neighborsr#   r$   knnrandom_statemethodmetricmetric_kwds	key_addedcopyreturnc              
   C   sZ  t d}|
r|  n| } | jr.| |   t| }|j||||||||d |	dkrfd}	d}d}n|	d }|	d }i | j|	< | j|	 }||d	< ||d
< |j|d|d< ||d d< ||d d< |r||d d< |dk	r||d d< |dk	r||d d< |j	| j
|< |j| j
|< |jdk	r(|j|d< t jd|d|	d|d|dd |
rV| S dS )u      Compute a neighborhood graph of observations [McInnes18]_.

    The neighbor search efficiency of this heavily relies on UMAP [McInnes18]_,
    which also provides a method for estimating connectivities of data points -
    the connectivity of the manifold (`method=='umap'`). If `method=='gauss'`,
    connectivities are computed according to [Coifman05]_, in the adaption of
    [Haghverdi16]_.

    Parameters
    ----------
    adata
        Annotated data matrix.
    n_neighbors
        The size of local neighborhood (in terms of number of neighboring data
        points) used for manifold approximation. Larger values result in more
        global views of the manifold, while smaller values result in more local
        data being preserved. In general values should be in the range 2 to 100.
        If `knn` is `True`, number of nearest neighbors to be searched. If `knn`
        is `False`, a Gaussian kernel width is set to the distance of the
        `n_neighbors` neighbor.
    {n_pcs}
    {use_rep}
    knn
        If `True`, use a hard threshold to restrict the number of neighbors to
        `n_neighbors`, that is, consider a knn graph. Otherwise, use a Gaussian
        Kernel to assign low weights to neighbors more distant than the
        `n_neighbors` nearest neighbor.
    random_state
        A numpy random seed.
    method
        Use 'umap' [McInnes18]_ or 'gauss' (Gauss kernel following [Coifman05]_
        with adaptive width [Haghverdi16]_) for computing connectivities.
        Use 'rapids' for the RAPIDS implementation of UMAP (experimental, GPU
        only).
    metric
        A known metric’s name or a callable that returns a distance.
    metric_kwds
        Options for the metric.
    key_added
        If not specified, the neighbors data is stored in .uns['neighbors'],
        distances and connectivities are stored in .obsp['distances'] and
        .obsp['connectivities'] respectively.
        If specified, the neighbors data is added to .uns[key_added],
        distances are stored in .obsp[key_added+'_distances'] and
        connectivities in .obsp[key_added+'_connectivities'].
    copy
        Return a copy instead of writing to adata.

    Returns
    -------
    Depending on `copy`, updates or returns `adata` with the following:

    See `key_added` parameter description for the storage path of
    connectivities and distances.

    **connectivities** : sparse matrix of dtype `float32`.
        Weighted adjacency matrix of the neighborhood graph of data
        points. Weights should be interpreted as connectivities.
    **distances** : sparse matrix of dtype `float32`.
        Instead of decaying weights, this stores distances for each pair of
        neighbors.

    Notes
    -----
    If `method='umap'`, it's highly recommended to install pynndescent ``pip install pynndescent``.
    Installing `pynndescent` can significantly increase performance,
    and in later versions it will become a hard dependency.
    computing neighbors)r&   r'   r#   r$   r)   r*   r+   r(   N	neighborsconnectivities	distances_connectivities
_distancesZconnectivities_keyZdistances_key)r&   r)   paramsr(   r*   r+   r$   r#   	rp_forest    finishedzadded to `.uns[z]`
    `.obsp[z4]`, distances for each pair of neighbors
    `.obsp[z]`, weighted adjacency matrix)timedeep)logginfor-   Zis_viewZ_init_as_actual	Neighborscompute_neighborsunsr&   r2   Zobspr1   r6   )r%   r&   r#   r$   r'   r(   r)   r*   r+   r,   r-   startr0   Z	conns_keyZ	dists_keyZneighbors_dict r@   R/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scanpy/neighbors/__init__.pyr0   3   sX    S



	r0   c                   @   s.   e Zd ZU ded< ded< ded< ded< dS )FlatTreeNhyperplanesoffsetschildrenindices)__name__
__module____qualname____annotations__r@   r@   r@   rA   rB      s   
rB   )rp_forest_dictr.   c                 c   s   t j}t| |d  d d }t|D ]Z}g }|D ]B}| | d | }| | d |d  }|| | d ||  q2t | V  q&g }|D ].}| | d | }|| | d |d   qt | V  d S )Nr   r?      data)rB   _fieldslenrangeappend)rK   propsZ	num_treesitreepropr?   endr@   r@   rA   _rp_forest_generate   s    rW   )Xr&   r(   r*   r+   angularverbosec              	   C   s\   t    t jddd ddlm} W 5 Q R X t|}|| ||||||d\}}	}
||	|
fS )a
  This is from umap.fuzzy_simplicial_set [McInnes18]_.

    Given a set of data X, a neighborhood size, and a measure of distance
    compute the fuzzy simplicial set (here represented as a fuzzy graph in
    the form of a sparse matrix) associated to the data. This is done by
    locally approximating geodesic distance at each point, creating a fuzzy
    simplicial set for each such point, and then combining all the local
    fuzzy simplicial sets into a global one via a fuzzy union.

    Parameters
    ----------
    X: array of shape (n_samples, n_features)
        The data to be modelled as a fuzzy simplicial set.
    n_neighbors
        The number of neighbors to use to approximate geodesic distance.
        Larger numbers induce more global estimates of the manifold that can
        miss finer detail, while smaller values will focus on fine manifold
        structure to the detriment of the larger picture.
    random_state
        A state capable being used as a numpy random state.
    metric
        The metric to use to compute distances in high dimensional space.
        If a string is passed it must match a valid predefined metric. If
        a general metric is required a function that takes two 1d arrays and
        returns a float can be provided. For performance purposes it is
        required that this be a numba jit'd function. Valid string metrics
        include:
            * euclidean
            * manhattan
            * chebyshev
            * minkowski
            * canberra
            * braycurtis
            * mahalanobis
            * wminkowski
            * seuclidean
            * cosine
            * correlation
            * haversine
            * hamming
            * jaccard
            * dice
            * russelrao
            * kulsinski
            * rogerstanimoto
            * sokalmichener
            * sokalsneath
            * yule
        Metrics that take arguments (such as minkowski, mahalanobis etc.)
        can have arguments passed via the metric_kwds dictionary. At this
        time care must be taken and dictionary elements must be ordered
        appropriately; this will hopefully be fixed in the future.
    metric_kwds
        Arguments to pass on to the metric, such as the ``p`` value for
        Minkowski distance.
    angular
        Whether to use angular/cosine distance for the random projection
        forest for seeding NN-descent to determine approximate nearest
        neighbors.
    verbose
        Whether to report information on the current progress of the algorithm.

    Returns
    -------
    **knn_indices**, **knn_dists** : np.arrays of shape (n_observations, n_neighbors)
    ignoreTensorflow not installedmessager   )nearest_neighbors)r(   r*   r+   rY   rZ   )warningscatch_warningsfilterwarnings
umap.umap_r_   r   )rX   r&   r(   r*   r+   rY   rZ   r_   knn_indices	knn_distsforestr@   r@   rA   compute_neighbors_umap   s    K

rg   )rX   r&   r*   c                 C   sH   ddl m} |||d}tj| tjd}|| ||\}}||fS )a  Compute nearest neighbors using RAPIDS cuml.

    Parameters
    ----------
    X: array of shape (n_samples, n_features)
        The data to compute nearest neighbors for.
    n_neighbors
        The number of neighbors to use.
    metric
        The metric to use to compute distances in high dimensional space.
        This string must match a valid predefined metric in RAPIDS cuml.

        Returns
    -------
    **knn_indices**, **knn_dists** : np.arrays of shape (n_observations, n_neighbors)
    r   )NearestNeighbors)r&   r*   dtype)Zcuml.neighborsrh   npZascontiguousarrayfloat32fitZ
kneighbors)rX   r&   r*   rh   nnZX_contiguousZknn_distrd   r@   r@   rA   compute_neighbors_rapids>  s    
ro   c                 C   s   t j|| t jd}t j|| t jd}t j|| t jd}t| jd D ]~}t|D ]p}| ||f dkrlqV| ||f |krd}	n|||f }	|||| | < | ||f ||| | < |	||| | < qVqJt|||ff||fd}
|
  |
 S )Nri   r   g        shape)	rk   zerosZint64float64rP   rr   r   eliminate_zerostocsr)rd   re   n_obsr&   rowscolsvalsrS   jvalresultr@   r@   rA   ._get_sparse_matrix_from_indices_distances_umapZ  s     r~         ?c           
   
   C   s   t    t jddd ddlm} W 5 Q R X tg g g ff|dfd}|||dd| |||d	}t|trp|d }t| |||}	|	|	 fS )
a      This is from umap.fuzzy_simplicial_set [McInnes18]_.

    Given a set of data X, a neighborhood size, and a measure of distance
    compute the fuzzy simplicial set (here represented as a fuzzy graph in
    the form of a sparse matrix) associated to the data. This is done by
    locally approximating geodesic distance at each point, creating a fuzzy
    simplicial set for each such point, and then combining all the local
    fuzzy simplicial sets into a global one via a fuzzy union.
    r[   r\   r]   r   )fuzzy_simplicial_setrL   rq   N)rd   re   set_op_mix_ratiolocal_connectivity)
r`   ra   rb   rc   r   r   
isinstancetupler~   rv   )
rd   re   rw   r&   r   r   r   rX   r1   r2   r@   r@   rA   _compute_connectivities_umaps  s.    

   r   c                 C   sL   || }t d|d |}t|  |   |f||fd}|  |S )Nr   rL   rq   )rk   aranger   r-   Zravelru   )rF   r2   rw   r&   Z	n_nonzeroindptrDr@   r@   rA   /_get_sparse_matrix_from_indices_distances_numpy  s    

r   )r&   c                 C   s  t j| jd |ftd}t j| jd |f| jd}|d }t|jd D ]}| |  }|||df< d||df< t|d |krt | | | j	d | }|d | ||dd f< | | |d | |d | f ||dd f< qH|d ||dd f< | | | ||dd f< qH||fS )Nr   ri   rL   )
rk   rs   rr   intrj   rP   ZnonzerorO   argsortA1)r   r&   rF   r2   Zn_neighbors_m1rS   r0   Zsorted_indicesr@   r@   rA   )_get_indices_distances_from_sparse_matrix  s     r   c                 C   sn   t | jd d d d f }t j| |d ddd d d |f }||t | ||f f }| ||f }||fS )Nr   rL   Zaxis)rk   r   rr   Zargpartitionr   )r   r&   Zsample_rangerF   r2   r@   r@   rA   (_get_indices_distances_from_dense_matrix  s
    $r   )r%   r.   c                 C   s@   d| j kr2tj| j d jd d d f | jd f S | jd S d S )N
X_diffmap0	X_diffmap)obsrk   Zc_valuesZobsmr%   r@   r@   rA   $_backwards_compat_get_full_X_diffmap  s    
(r   r   c                 C   s,   d| j krtjd| jd f S | jd S d S )Nr   rL   Zdiffmap_evals)r   rk   Zr_r>   r   r@   r@   rA   _backwards_compat_get_full_eval  s    
r   c                    s   i }d}|D ]ډ i | < t j fdd| D td}t ||  d<  dkrX| }n| t| d  jd f}t| d  j}t j||d}d}t	|D ]:\}}	||  d |< ||	 }
t| |  |||
< |
}q||  d	< q|S )
N)rC   rD   rE   rF   c                 3   s   | ]}t | jd  V  qdS )r   N)getattrrr   ).0rT   rU   r@   rA   	<genexpr>  s     z$_make_forest_dict.<locals>.<genexpr>ri   r?   rD   r   rL   rM   )
rk   Zfromiterr   Z
zeros_likesumr   rr   rj   empty	enumerate)rf   drR   sizesZdimsrj   Zdatr?   rS   sizerV   r@   r   rA   _make_forest_dict  s,     
r   c                	   @   sb   e Zd ZdZdeegejf ee	e	f e	e	e
eeejf  e
ej dddZdd	 Zd
d ZdS )OnFlySymMatrixz:Emulate a matrix where elements are calculated on the fly.r   rp   Nget_rowrr   DC_startDC_endrx   restrict_arrayc                 C   s4   || _ || _|| _|| _|d kr$i n|| _|| _d S Nr   )selfr   rr   r   r   rx   r   r@   r@   rA   __init__  s    	zOnFlySymMatrix.__init__c                 C   s   t |ttjfrh| jd kr |}n
| j| }|| jkrD| || j|< | j| }| jd kr\|S || j S nX| jd kr||\}}n| j|d  }| j|d  }|| jkr| || j|< | j| | S d S )Nr   rL   )r   r   rk   integerr   rx   r   )r   indexZ
glob_indexrowZglob_index_0Zglob_index_1r@   r@   rA   __getitem__  s"    







zOnFlySymMatrix.__getitem__c                 C   s0   |j d |j d f}t| j|| j| j| j|dS )z2Generate a view restricted to a subset of indices.r   )r   r   rx   r   )rr   r   r   r   r   rx   )r   Zindex_arrayZ	new_shaper@   r@   rA   restrict#  s    zOnFlySymMatrix.restrict)r   rp   NN)rG   rH   rI   __doc__r   r   rk   ndarrayr
   r   r   r   r   r   r   r@   r@   r@   rA   r     s       
r   c                   @   s  e Zd ZdZd6eee ee dddZe	ee
 dddZe	eejedf dd	d
Ze	eejedf dddZe	eejef dddZe	eejedf dddZe	dd Ze	dd Ze	dd Zdd Zeeedddddddddei f	eeee ee eeeee ee!f dd 
d!d"Z"d7d#d$Z#d8ed%d&d'Z$d9eee e%d* ed+d,d-Z&d.d/ Z'd0d1 Z(d2d3 Z)d4d5 Z*dS ):r<   as      Data represented as graph of nearest neighbors.

    Represent a data matrix as a graph of nearest neighbor relations (edges)
    among data points (nodes).

    Parameters
    ----------
    adata
        Annotated data object.
    n_dcs
        Number of diffusion components to use.
    neighbors_key
        Where to look in .uns and .obsp for neighbors data
    N)r%   n_dcsneighbors_keyc                 C   s  || _ |   d}d | _d | _d | _d | _d | _d | _|d krBd}||jkrdt	||}d|krxt
|d | _|d | _d|krt
|d | _|d | _d|kr|d | _d|kr|d d | _ndttjtf tdd	d
}| jd krt|| j| jjd  | _n t|| j| jjd  d | _|d7 }d| _t
| jrdddlm} || j| _| jd | _d| krt|| _t|| _|d k	r|t| jkrtd|| jd | | _| jd d d |f | _t| j| _|d7 }nd | _d | _d | _|dkrtd|  d S )N r0   r2   r1   r6   r5   r&   )ar.   c                 S   s   t | r|  S t| S r   )r   count_nonzerork   )r   r@   r@   rA   r   a  s    z)Neighbors.__init__.<locals>.count_nonzeror   r   z`.distances` `.connectivities` rL   connected_componentsr   zYCannot instantiate using `n_dcs`={}. Compute diffmap/spectrum with more components first.z/`.eigen_values` `.eigen_basis` `.distances_dpt`z    initialized ) _adata_init_irootr'   r4   r3   _transitions_sym_number_connected_components
_rp_forestr>   r   r   r&   r   rk   r   r   r   rr   scipy.sparse.csgraphr   _connected_componentsZ	obsm_keysr   _eigen_valuesr   _eigen_basisrO   
ValueErrorformatr   r:   debug)r   r%   r   r   Zinfo_strr0   r   r   r@   r@   rA   r   A  sx    









zNeighbors.__init__)r.   c                 C   s   | j S r   )r   r   r@   r@   rA   r6     s    zNeighbors.rp_forestc                 C   s   | j S )z.Distances between data points (sparse matrix).)r4   r   r@   r@   rA   r2     s    zNeighbors.distancesc                 C   s   | j S )z3Connectivities between data points (sparse matrix).)r3   r   r@   r@   rA   r1     s    zNeighbors.connectivitiesc                 C   s>   t | jr| jd}ntdt| j }| j| j | S )a  Transition matrix (sparse matrix).

        Is conjugate to the symmetrized transition matrix via::

            self.transitions = self.Z *  self.transitions_sym / self.Z

        where ``self.Z`` is the diagonal matrix storing the normalization of the
        underlying kernel matrix.

        Notes
        -----
        This has not been tested, in contrast to `transitions_sym`.
        rp   r   )r   Zpowerrk   diagtransitions_sym)r   ZZinvr@   r@   rA   transitions  s    
zNeighbors.transitionsc                 C   s   | j S )a(  Symmetrized transition matrix (sparse matrix).

        Is conjugate to the transition matrix via::

            self.transitions_sym = self.Z /  self.transitions * self.Z

        where ``self.Z`` is the diagonal matrix storing the normalization of the
        underlying kernel matrix.
        )r   r   r@   r@   rA   r     s    zNeighbors.transitions_symc                 C   s   | j S )z0Eigen values of transition matrix (numpy array).)r   r   r@   r@   rA   eigen_values  s    zNeighbors.eigen_valuesc                 C   s   | j S )z/Eigen basis of transition matrix (numpy array).)r   r   r@   r@   rA   eigen_basis  s    zNeighbors.eigen_basisc                 C   s   t | j| jjdS )zDPT distances (on-fly matrix).

        This is yields [Haghverdi16]_, Eq. 15 from the supplement with the
        extensions of [Wolf19]_, supplement on random-walk based distance
        measures.
        rq   )r   _get_dpt_rowr   rr   r   r@   r@   rA   distances_dpt  s    zNeighbors.distances_dptc                 C   s   t | jS )z#Generate igraph from connectiviies.)r   Zget_igraph_from_adjacencyr1   r   r@   r@   rA   	to_igraph  s    zNeighbors.to_igraphr"      Tr   r   Fr   )
r&   r'   r#   r$   r)   r(   write_knn_indicesr*   r+   r.   c
                 C   sR  ddl m}
 td}|| jjd krPdtd| jjd   }td| d |dkrd|sdtd	|d
krttd| jjd dkr|std d| _	|| _
|| _t| j||d}|dkr|jd dk p| }|r|
|fd|i|	}t||\}}|rt|||jd || _n|| _n|dkr<t|||d\}}nl|jd dk rd|
|fd|i|	}d}t|||||	d\}}}z|rt|| _	W n tk
r   Y nX |r|| _|| _tjd|d}|r|dkrt||| jjd | j
\| _| _|dkr
|   tjd|d d| _t| jrNddlm} || j| _| jd | _dS )a          Compute distances and connectivities of neighbors.

        Parameters
        ----------
        n_neighbors
             Use this number of nearest neighbors.
        knn
             Restrict result to `n_neighbors` nearest neighbors.
        {n_pcs}
        {use_rep}

        Returns
        -------
        Writes sparse graph attributes `.distances` and `.connectivities`.
        Also writes `.knn_indices` and `.knn_distances` if
        `write_knn_indices==True`.
        r   )pairwise_distancesr/   rL   g      ?z-n_obs too small: adjusting to `n_neighbors = `r   z(`method = 'umap' only with `knn = True`.>   r   r   r   z2`method` needs to be 'umap', 'gauss', or 'rapids'.i'  z<Using high n_obs without `knn=True` takes a lot of memory...N)r$   r#   r   i    r*   r   )r*   i   Zprecomputed)r*   r+   zcomputed neighborsr8   >   r   r   r   zcomputed connectivitiesr   )Zsklearn.metricsr   r:   r   r   rr   r   warningr   r   r&   r'   r   r   r   r4   ro   rg   r   	Exceptionrd   knn_distancesr   r3   _compute_connectivities_diffmapr   r   r   r   r   )r   r&   r'   r#   r$   r)   r(   r   r*   r+   r   Zstart_neighborsrX   Zuse_dense_distancesr4   rd   r   rf   start_connectr   r@   r@   rA   r=     s    

    
      

zNeighbors.compute_neighborsc              	   C   s  | j r$| jd}t|| j\}}nt| jd}t|| j\}}|d d dd f }|d d dd f }| j rtj|dd}n|d d df d }t|}t	| jsdtj
|| }tj||}t|| t| |  }	| j s|	dk}
d|	|
 < nxtj|jtd}
t|D ]T\}}d	|
||f< |D ]8}|t|| kr4|	||f |	||f< d	|
||f< q4qd|	|
 < n| }	tt|jd d D ]}|j|j| |j|d   }d||  ||  }|| ||  }t|| t|j|j| |j|d    |  |	j|j| |j|d  < q|	 }	t|D ]<\}}|D ],}|t|| krV|	||f |	||f< qVqJ|	 }	|	| _d S )
Nr   rL   r   rp      g+=r   ri   T)r'   r4   r   r   r&   rk   r   Zmediansqrtr   multiplyouteraddexprs   rr   boolr   setr-   rP   rO   r   rF   rM   Ztolilrv   r3   )r   density_normalizeZDsqrF   Zdistances_sqZ	sigmas_sqZsigmasNumZDenWmaskrS   r   r{   numZdenr@   r@   rA   r   =  s`     
 
"$z)Neighbors._compute_connectivities_diffmap)r   c                 C   s   t d}| j}|rnt|jdd}t|s>td| }n"tj	
d| d|jd |jd }|| | }n|}tt|jdd}t|std| | _n$tj	
d| d|jd |jd | _| j| | j | _t jd|d dS )ag          Compute transition matrix.

        Parameters
        ----------
        density_normalize
            The density rescaling of Coifman and Lafon (2006): Then only the
            geometry of the data matters, not the sampled density.

        Returns
        -------
        Makes attributes `.transitions_sym` and `.transitions` available.
        zcomputing transitionsr   r   r   r7   r   N)r:   r;   r3   rk   Zasarrayr   r   r   scipysparseZspdiagsrr   r   r   r   )r   r   r?   r   qQKzr@   r@   rA   compute_transitions  s    
"$zNeighbors.compute_transitionsr   decrease)r   Zincrease)n_compssymsortr(   c                 C   s6  t jdd | jdkrtd| j}|dkr>tj|\}}nt|jd d |}d}|dkrbdnd	}	|	t j
}t|}||jd }
tjjj|||	||
d
\}}|	t j|	t j }}|dkr|ddd }|dddddf }tdt|dd | jt|d kr&td || _|| _dS )a          Compute eigen decomposition of transition matrix.

        Parameters
        ----------
        n_comps
            Number of eigenvalues/vectors to be computed, set `n_comps = 0` if
            you need all eigenvectors.
        sym
            Instead of computing the eigendecomposition of the assymetric
            transition matrix, computed the eigendecomposition of the symmetric
            Ktilde matrix.
        random_state
            A numpy random seed

        Returns
        -------
        Writes the following attributes.

        eigen_values : numpy.ndarray
            Eigenvalues of transition matrix.
        eigen_basis : numpy.ndarray
             Matrix of eigenvectors (stored in columns).  `.eigen_basis` is
             projection of data matrix on right eigenvectors, that is, the
             projection on the diffusion components.  these are simply the
             components of the right eigenvectors and can directly be used for
             plotting.
        
   )	precisionNz!Run `.compute_transitions` first.r   rL   r   ZLMZSM)kwhichncvv0rp   z+    eigenvalues of transition matrix
    {}
z
    r   z3Transition matrix has many disconnected components!)rk   Zset_printoptionsr   r   r   ZlinalgZeighminrr   Zastypert   r   Zstandard_normalr   Zeigshrl   r:   r;   r   strreplacer   rO   r   r   r   )r   r   r   r   r(   matrixZevalsZevecsr   r   r   r@   r@   rA   compute_eigen  s@    #
    

zNeighbors.compute_eigenc                 C   s   d | _ d| jjkr^| jjd | jjkrLtd| jjd  d| jj d n| jjd | _ d S d }d| jjkr|| jjd }nd| jjkr| jjd }|d k	r|j| jjd kr| 	| d S )NirootzRoot cell index z does not exist for u    samples. It’s ignored.xrootrL   )
r   r   r>   rw   r:   r   varr   rr   _set_iroot_via_xroot)r   r   r@   r@   rA   r     s    zNeighbors._init_irootc                    s   d }j dkr*jd   }jd |k}t fddtdjjD }|t fddtdjjD 7 }|d k	rtj|| < t|S )NrL   c                 3   sX   | ]P}j | d k rj | dj |   j |f jdd|f   d V  qdS )s?rL   Nr   r   r   )r   r{   rS   r   r@   rA   r   
  s   z)Neighbors._get_dpt_row.<locals>.<genexpr>r   c                 3   s@   | ]8}j | d krj |f jdd|f  d V  qdS )r  Nr   r  )r   r   r  r@   rA   r     s   )	r   r   r   rP   r   r   rk   infr   )r   rS   r   labelr   r@   r  rA   r     s    

zNeighbors._get_dpt_rowc                 C   s8   | j | j  | _|  jt| j| jtjk    _dS )z-Return pseudotime with respect to root point.N)r   r   r-   Z
pseudotimerk   maxr  r   r@   r@   rA   _set_pseudotime#  s    zNeighbors._set_pseudotimec                 C   s   | j jd |jkrtdd}d}t| j jd D ]F}| j j|ddf | }|| }||k r2|}|}t|dk r2 qzq2t	d|  | j
dk	r|| j
krtd| j
 d	| d
 || _
dS )ac  Determine the index of the root cell.

        Given an expression vector, find the observation index that is closest
        to this vector.

        Parameters
        ----------
        xroot : np.ndarray
            Vector that marks the root cell, the vector storing the initial
            condition, only relevant for computing pseudotime.
        rL   zAThe root vector you provided does not have the correct dimension.g    _Br   Ng|=zsetting root index to zChanging index of iroot from z to .)r   rr   r   r   rP   rX   rk   r   r:   r   r   r   )r   r   Zdsqrootr   rS   diffZdsqr@   r@   rA   r  (  s$    zNeighbors._set_iroot_via_xroot)NN)T)T)r   Nr   r   )+rG   rH   rI   r   r   r   r   r   r   propertyRPForestDictr6   r   rk   r   r   r2   r1   r   r   r   r   r   r   r   r   r   r   r   _Methodr   _Metricr   r   r=   r   r   r   r   r   r   r  r  r@   r@   r@   rA   r<   0  s~     K


	

h
F)    Er<   )r   )r   r   )Atypesr   typingr   r   r   r   r   r   r	   r
   r`   numpyrk   r   Zanndatar   Zscipy.sparser   r   r   Zsklearn.utilsr   r   r   r:   r   r   r   r   Z_compatr   Ztools._utilsr   r   r   r   ZN_DCSZN_PCSr  r   floatZ	_MetricFnZ_MetricSparseCapableZ_MetricScipySpatialr  r   r   r   r0   rB   r  rW   rg   ro   r~   r   r   r   r   r   r   r   r   r<   r@   r@   r@   rA   <module>   s   (


 

`     
.8