U
    mdU$                     @   s   d dl 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mZ ddl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 ed Zde	eeeee eeeeeejdf eee ee eed ee ee	 dddZdS )    )OptionalUnionN)version)AnnData)check_random_statecheck_array   )get_init_pos_from_paga_choose_representation   )logging)settings)Literal)	AnyRandomNeighborsView)pagaspectralrandom      ?      ?   r   Fumap)r   rapids)adatamin_distspreadn_componentsmaxiteralphagammanegative_sample_rateinit_posrandom_stateabcopymethodneighbors_keyreturnc                 C   s  |r|   n| } |dkrd}|| jkr6td| dtd}t| |}d|ksb|d d dkrxtd	|d
  d t  tj	ddd ddl
}W 5 Q R X t|jtdkrdd }nddlm} ddlm} |
dks|dkr|||\}
}n|
}
|}d|
|di| jd< t|tr>|| j kr>| j| }n*t|trd|dkrdt| |	|d}n|}t|drt|tjdd}|	dkr|	| jd d d< t|	}	|d }t| |dd|dddd}|dkrL|d  jd d!krd"nd#}|dkr|n|}|||d   |||
||||||	|d$d%|d&i tj d'kd(}n|d)kr|d$d%}|d%kr|td*|d+dd,l!m"} |d d- }|dkrd"n|}tj#|tjd.}||||||||||
|tj d'k|	d/}|$|}|| jd0< tjd1|d2d3 |r
| S dS )4a9      Embed the neighborhood graph using UMAP [McInnes18]_.

    UMAP (Uniform Manifold Approximation and Projection) is a manifold learning
    technique suitable for visualizing high-dimensional data. Besides tending to
    be faster than tSNE, it optimizes the embedding such that it best reflects
    the topology of the data, which we represent throughout Scanpy using a
    neighborhood graph. tSNE, by contrast, optimizes the distribution of
    nearest-neighbor distances in the embedding such that these best match the
    distribution of distances in the high-dimensional space.  We use the
    implementation of `umap-learn <https://github.com/lmcinnes/umap>`__
    [McInnes18]_. For a few comparisons of UMAP with tSNE, see this `preprint
    <https://doi.org/10.1101/298430>`__.

    Parameters
    ----------
    adata
        Annotated data matrix.
    min_dist
        The effective minimum distance between embedded points. Smaller values
        will result in a more clustered/clumped embedding where nearby points on
        the manifold are drawn closer together, while larger values will result
        on a more even dispersal of points. The value should be set relative to
        the ``spread`` value, which determines the scale at which embedded
        points will be spread out. The default of in the `umap-learn` package is
        0.1.
    spread
        The effective scale of embedded points. In combination with `min_dist`
        this determines how clustered/clumped the embedded points are.
    n_components
        The number of dimensions of the embedding.
    maxiter
        The number of iterations (epochs) of the optimization. Called `n_epochs`
        in the original UMAP.
    alpha
        The initial learning rate for the embedding optimization.
    gamma
        Weighting applied to negative samples in low dimensional embedding
        optimization. Values higher than one will result in greater weight
        being given to negative samples.
    negative_sample_rate
        The number of negative edge/1-simplex samples to use per positive
        edge/1-simplex sample in optimizing the low dimensional embedding.
    init_pos
        How to initialize the low dimensional embedding. Called `init` in the
        original UMAP. Options are:

        * Any key for `adata.obsm`.
        * 'paga': positions from :func:`~scanpy.pl.paga`.
        * 'spectral': use a spectral embedding of the graph.
        * 'random': assign initial embedding positions at random.
        * A numpy array of initial embedding positions.
    random_state
        If `int`, `random_state` is the seed used by the random number generator;
        If `RandomState` or `Generator`, `random_state` is the random number generator;
        If `None`, the random number generator is the `RandomState` instance used
        by `np.random`.
    a
        More specific parameters controlling the embedding. If `None` these
        values are set automatically as determined by `min_dist` and
        `spread`.
    b
        More specific parameters controlling the embedding. If `None` these
        values are set automatically as determined by `min_dist` and
        `spread`.
    copy
        Return a copy instead of writing to adata.
    method
        Use the original 'umap' implementation, or 'rapids' (experimental, GPU only)
    neighbors_key
        If not specified, umap looks .uns['neighbors'] for neighbors settings
        and .obsp['connectivities'] for connectivities
        (default storage places for pp.neighbors).
        If specified, umap looks .uns[neighbors_key] for neighbors settings and
        .obsp[.uns[neighbors_key]['connectivities_key']] for connectivities.

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

    **X_umap** : `adata.obsm` field
        UMAP coordinates of data.
    N	neighborszDid not find .uns["z "]. Run `sc.pp.neighbors` first.zcomputing UMAPparamsr&   r   z.obsp["Zconnectivities_keyz$"] have not been computed using umapignorezTensorflow not installed)messager   z0.5.0c                  _   s*   ddl m} || di dd|\}}|S )Nr   simplicial_set_embeddingF)ZdensmapZdensmap_kwdsZoutput_dens)
umap.umap_r.   )argskwargsr.   X_umap_ r4   K/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scanpy/tools/_umap.pyr.      s    
z&umap.<locals>.simplicial_set_embeddingr-   )find_ab_params)r#   r$   r   )r"   r'   dtypeF)r7   Zaccept_sparser"   Zuse_repZn_pcsT)ZsilentZconnectivitiesi'  i     metricZ	euclideanZmetric_kwds   )verboser   z+`sc.pp.neighbors` was called with `metric` zB, but umap `method` 'rapids' only supports the 'euclidean' metric.)UMAPn_neighbors)r7   )r=   r   n_epochsZlearning_rateinitr   r   r    r#   r$   r;   r"   r2   z    finishedz1added
    'X_umap', UMAP coordinates (adata.obsm))timedeep)%r%   Zuns
ValueErrorlogginfor   warningwarningscatch_warningsfilterwarningsr   r   parse__version__r/   r.   r6   
isinstancestrZobsmkeysr	   hasattrr   npZfloat32r   r
   getshapeZtocoor   	verbosityZcumlr<   ZascontiguousarrayZfit_transform)r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   startr)   r   r.   r6   Zinit_coordsZneigh_paramsXZdefault_epochsr>   r2   r9   r<   r=   ZX_contiguousr4   r4   r5   r      s    d





  











)r   r   r   Nr   r   r   r   r   NNFr   N) typingr   r   rF   numpyrO   	packagingr   Zanndatar   Zsklearn.utilsr   r   _utilsr	   r
    r   rC   Z	_settingsr   Z_compatr   r   r   Z_InitPosfloatintZndarrayboolrL   r   r4   r4   r4   r5   <module>   sV                 