U
    ֽ|e=1                     @   s   d dl mZ d dl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mZ d dlmZmZ di fd	d
Zdi fddZdi fddZdS )    )warnN)SpectralEmbedding)pairwise_distances)_VALID_METRICS)pairwise_special_metricSPECIAL_METRICS)SPARSE_SPECIAL_METRICSsparse_named_distances	euclideanc                 C   s<  | dkrt jj||fdd S t j|| jd ft jd}|dkrt j||ft jd}|dd}	|	dkrpt j}	n,|	d	krt j}	n|	d
krt j	}	nt
d|	 t|D ]T}
| ||
k }t|
d |D ]4}|	|dd||kf }|||
|f< ||||
f< qqn
t|D ]}| ||k jdd||< qtj|rDtd | }|tkr^t|||d}n|tkr|t|t| |d}nt|rtj| rdd tttt @ D }z|| }W n tk
r   tdY nX t|fd|i|}nt|fd|i|}t |d  }t|d|d|}||  }|S )a  Provide a layout relating the separate connected components. This is done
    by taking the centroid of each component and then performing a spectral embedding
    of the centroids.

    Parameters
    ----------
    data: array of shape (n_samples, n_features)
        The source data -- required so we can generate centroids for each
        connected component of the graph.

    n_components: int
        The number of distinct components to be layed out.

    component_labels: array of shape (n_samples)
        For each vertex in the graph the label of the component to
        which the vertex belongs.

    dim: int
        The chosen embedding dimension.

    metric: string or callable (optional, default 'euclidean')
        The metric used to measure distances among the source data points.

    metric_kwds: dict (optional, default {})
        Keyword arguments to be passed to the metric function.
        If metric is 'precomputed', 'linkage' keyword can be used to specify
        'average', 'complete', or 'single' linkage. Default is 'average'

    Returns
    -------
    component_embedding: array of shape (n_components, dim)
        The ``dim``-dimensional embedding of the ``n_components``-many
        connected components.
    Nsize      $@   dtypeprecomputedlinkageaveragecompletesinglezPUnrecognized linkage '%s'. Please choose from 'average', 'complete', or 'single'r   axiszlForcing component centroids to dense; if you are running out of memory then consider increasing n_neighbors.)metrickwdsc                 S   s   i | ]}t | |qS  )r	   ).0kr   r   J/var/www/website-v5/atlas_env/lib/python3.8/site-packages/umap/spectral.py
<dictcomp>p   s    z$component_layout.<locals>.<dictcomp>zPMulticomponent layout for custom sparse metrics is not implemented at this time.r      )n_componentsZaffinityrandom_state)nprandomemptyshapefloat64zerosgetmeanmaxmin
ValueErrorrangescipysparse
isspmatrixr   toarrayr   r   r   callablesetSKLEARN_PAIRWISE_VALID_METRICSr	   keysKeyErrorNotImplementedErrorr   expr   fit_transform)datar    component_labelsdimr!   r   metric_kwdsZcomponent_centroidsdistance_matrixr   c_iZdm_iZc_jdistlabelZfunction_to_name_mappingmetric_nameZaffinity_matrixcomponent_embeddingr   r   r   component_layout   s    +



  rD   c                 C   s  t j|jd |ft jd}|d| kr>t| ||||||d}	nLtt |d }
t t |
t 	|
||
 fg}t 
|| gd| }	t|D ]}| ||kddf  }|dd||kf  }t|	| g|	}||dk  d }|jd d| k s|jd |d krF|j| ||jd |fd	|	|  |||k< qt |jdd
}tjj|jd t jd}tjdt | d|jd |jd }||| |  }|d }
td|
 d tt |jd }ztjjj||
d|dt |jd |jd d d\}}t |d|
 }|dd|f }|t t | }||9 }||	|  |||k< W q tjjj k
r   t!d |j| ||jd |fd	|	|  |||k< Y qX q|S )a\  Specialised layout algorithm for dealing with graphs with many connected components.
    This will first fid relative positions for the components by spectrally embedding
    their centroids, then spectrally embed each individual connected component positioning
    them according to the centroid embeddings. This provides a decent embedding of each
    component while placing the components in good relative positions to one another.

    Parameters
    ----------
    data: array of shape (n_samples, n_features)
        The source data -- required so we can generate centroids for each
        connected component of the graph.

    graph: sparse matrix
        The adjacency matrix of the graph to be emebdded.

    n_components: int
        The number of distinct components to be layed out.

    component_labels: array of shape (n_samples)
        For each vertex in the graph the label of the component to
        which the vertex belongs.

    dim: int
        The chosen embedding dimension.

    metric: string or callable (optional, default 'euclidean')
        The metric used to measure distances among the source data points.

    metric_kwds: dict (optional, default {})
        Keyword arguments to be passed to the metric function.


    Returns
    -------
    embedding: array of shape (n_samples, dim)
        The initial embedding of ``graph``.
    r   r   r   r   r=   g       @Ng        r   lowhighr   r         ?SM-C6?   whichncvtolv0maxiterWARNING: spectral initialisation failed! The eigenvector solver
failed. This is likely due to too small an eigengap. Consider
adding some noise or jitter to your data.

Falling back to random initialisation!)"r"   r$   r%   float32rD   intceilhstackeyer'   vstackr-   tocsrtocsctocoor   r+   uniformasarraysumr.   r/   identityr&   spdiagssqrtr*   linalgeigshonesargsortabsArpackErrorr   )r:   graphr    r;   r<   r!   r   r=   resultZmeta_embeddingr   baserA   Zcomponent_graph	distances
data_range	diag_dataIDLnum_lanczos_vectorseigenvalueseigenvectorsorderrC   	expansionr   r   r   multi_component_layout   s    0
"(
"
	
	rw   c              
   C   s  |j d }tjj|\}}|dkr<t| |||||||dS t|jdd}	tjj	|j d tj
d}
tjdt|	 d|j d |j d }|
|| |  }|d }td| d tt|j d }z|j d dk rtjjj||d	|d
t|j d |j d d d\}}n,tjjj||j|j d |fdddd\}}t|d| }|dd|f W S  tjjjk
r   td |jdd|j d |fd Y S X dS )a  Given a graph compute the spectral embedding of the graph. This is
    simply the eigenvectors of the laplacian of the graph. Here we use the
    normalized laplacian.

    Parameters
    ----------
    data: array of shape (n_samples, n_features)
        The source data

    graph: sparse matrix
        The (weighted) adjacency matrix of the graph as a sparse matrix.

    dim: int
        The dimension of the space into which to embed.

    random_state: numpy RandomState or equivalent
        A state capable being used as a numpy random state.

    Returns
    -------
    embedding: array of shape (n_vertices, dim)
        The spectral embedding of the graph.
    r   r   rE   r   r   rI   r   i rJ   rK   rL   rM   r   Fg:0yE>)largestrP   NrS   g      $r   rF   )r%   r.   r/   csgraphconnected_componentsrw   r"   r^   r_   r`   r&   ra   rb   r*   rU   rc   rd   re   lobpcgnormalrf   rh   r   r]   )r:   ri   r<   r!   r   r=   	n_samplesr    labelsrn   ro   rp   rq   r   rr   rs   rt   ru   r   r   r   spectral_layout  s`    
   "
   
r   )warningsr   numpyr"   scipy.sparser.   scipy.sparse.csgraphZsklearn.manifoldr   sklearn.metricsr   Zsklearn.metrics.pairwiser   r4   umap.distancesr   r   umap.sparser   r	   rD   rw   r   r   r   r   r   <module>   s"   	
 
 