U
    _»{j±F  ã                	   @   s¾  d Z ddlZddlZddlmZ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 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 m!Z! dZ"eddd�\Z#Z$ee#e$dd�\Z#Z$eƒ  %e#¡Z#ddddgZ&dhdd„ e '¡ D ƒB Z(ej) *de¡dd„ ƒZ+dd „ Z,ej) *d!ej-ej.g¡d"d#„ ƒZ/d$d%„ Z0ej) *d&e&¡ej) *d'e¡d(d)„ ƒƒZ1d*d+„ Z2ej) *d,d-¡d.d/„ ƒZ3d0d1„ Z4d2d3„ Z5d4d5„ Z6d6d7„ Z7d8d9„ Z8ej) *d:d;d<g¡d=d>„ ƒZ9d?d@„ Z:ej) *dAe&¡dBdC„ ƒZ;dDdE„ Z<dFdG„ Z=ej) *dHd'dIie >dJej?gej?dJgg¡fd'dIidJdKgdKdJggfi dJdKgddLggfg¡dMdN„ ƒZ@dOdP„ ZAdQdR„ ZBdSdT„ ZCdUdV„ ZDej) *dWdXdYg¡ej) *dZdd[g¡d\d]„ ƒƒZEd^d_„ ZFdS )`zF
Tests for HDBSCAN clustering algorithm
Based on the DBSCAN test code
é    N)ÚsparseÚstats)Údistance)ÚHDBSCAN)ÚCONDENSED_dtypeÚ_condense_treeÚ_do_labelling)Ú_OUTLIER_ENCODING)Ú
make_blobs)Úfowlkes_mallows_score)Ú_VALID_METRICSÚeuclidean_distances)ÚBallTreeÚKDTree)ÚStandardScaler)Úshuffle)Úassert_allcloseÚassert_array_equalé   éÈ   é
   )Ú	n_samplesÚrandom_stateé   )r   ÚkdtreeÚballtreeÚbruteÚautoéÿÿÿÿc                 C   s   h | ]\}}|d  ’qS )Úlabel© )Ú.0Ú_Úoutr    r    úa/var/www/html/bwave/python/venv/lib/python3.8/site-packages/sklearn/cluster/tests/test_hdbscan.pyÚ	<setcomp>%   s     r%   Úoutlier_typec                 C   sì   t jt jdœ|  }dd„ dd„ dœ|  }t|  d }t|  d }t ¡ }|dg|d< ||g|d	< tƒ  |¡}|j|k 	¡ \}t
|dd	gƒ ||j|ƒ 	¡ \}t
|dd	gƒ ttdd	ƒƒttd
dƒƒ }	tƒ  ||	 ¡}
t
|
j|j|	 ƒ dS )úO
    Tests if np.inf and np.nan data are each treated as special outliers.
    )ÚinfiniteÚmissingc                 S   s   | |kS ©Nr    ©ÚxÚyr    r    r$   Ú<lambda>2   ó    z#test_outlier_data.<locals>.<lambda>c                 S   s
   t  | ¡S r*   )ÚnpÚisnanr+   r    r    r$   r.   3   r/   r   Úprobé   r   é   é   r   N)r0   ÚinfÚnanr	   ÚXÚcopyr   ÚfitÚlabels_Znonzeror   Zprobabilities_ÚlistÚrange)r&   ZoutlierZ
prob_checkr   r2   Ú	X_outlierÚmodelÚmissing_labels_idxZmissing_probs_idxZclean_indicesÚclean_modelr    r    r$   Útest_outlier_data(   s.    þýþýrB   c               	   C   sÐ   t tƒ} |  ¡ }tddd� | ¡}t| |ƒ tt|ƒt ƒ}|t	ksHt
‚tt|ƒ}|dks^t
‚d}tjt|d�� tddd� t¡ W 5 Q R X d}d| d	< d
| d< tjt|d�� tdd� | ¡ W 5 Q R X dS )zy
    Tests that HDBSCAN works with precomputed distance matrices, and throws the
    appropriate errors when needed.
    ÚprecomputedT)Úmetricr9   ç\�Âõ(\ï?z*The precomputed distance matrix.*has shape©Úmatchz'The precomputed distance matrix.*valuesr   )r   r3   r3   )r3   r   ©rD   N)r   r8   r9   r   Úfit_predictr   ÚlenÚsetÚOUTLIER_SETÚn_clusters_trueÚAssertionErrorr   r-   ÚpytestÚraisesÚ
ValueError)ÚDZ
D_originalÚlabelsÚ
n_clustersÚscoreÚmsgr    r    r$   Útest_hdbscan_distance_matrixH   s     

rW   Úsparse_constructorc                 C   sz   t  t  t¡¡}|t |¡ }t | ¡ d¡}d|||k< | |ƒ}| 	¡  t
dd� |¡}tt|ƒt ƒ}|tksvt‚dS )zA
    Tests that HDBSCAN works with sparse distance matrices.
    é2   ç        rC   rH   N)r   Z
squareformZpdistr8   r0   Úmaxr   ZscoreatpercentileÚflattenZeliminate_zerosr   rI   rJ   rK   rL   rM   rN   )rX   rR   Ú	thresholdrS   rT   r    r    r$   Ú#test_hdbscan_sparse_distance_matrixf   s    r^   c                  C   sB   t ƒ  t¡} tt| ƒt ƒ}|tks(t‚tt	| ƒ}|dks>t‚dS )z“
    Tests that HDBSCAN works with feature array, including an arbitrary
    goodness of fit check. Note that the check is a simple heuristic.
    rE   N)
r   rI   r8   rJ   rK   rL   rM   rN   r   r-   )rS   rT   rU   r    r    r$   Útest_hdbscan_feature_arrayy   s
    
r_   ÚalgorD   c              	   C   s  t | d� t¡}tt|ƒt ƒ}|tks,t‚| dkr8dS tt	dœ}dt
 tjd ¡idt
 tjd ¡iddidt
 tjd ¡d	œd
œ |d¡}t | ||d�}|||  jkrÌt t¡� | t¡ W 5 Q R X n4|dkröt t¡� | t¡ W 5 Q R X n
| t¡ dS )z
    Tests that HDBSCAN works with the expected combinations of algorithms and
    metrics, or raises the expected errors.
    )Ú	algorithm)r   r   N)r   r   ÚVr3   Úpé   )rc   Úw)ZmahalanobisÚ
seuclideanZ	minkowskiÚ
wminkowski©ra   rD   Úmetric_paramsrg   )r   rI   r8   rJ   rK   rL   rM   rN   r   r   r0   ÚeyeÚshapeÚonesÚgetÚvalid_metricsrO   rP   rQ   r:   ZwarnsÚFutureWarning)r`   rD   rS   rT   ZALGOS_TREESri   Úhdbr    r    r$   Útest_hdbscan_algorithmsˆ   s8    þü ûýrq   c                  C   s6   t ƒ  t¡} |  d¡}tt|ƒt ƒ}|tks2t‚dS )zØ
    Tests that HDBSCAN can generate a sufficiently accurate dbscan clustering.
    This test is more of a sanity check than a rigorous evaluation.

    TODO: Improve and strengthen this test if at all possible.
    ç333333Ó?N)	r   r:   r8   Údbscan_clusteringrJ   rK   rL   rM   rN   )Z	clustererrS   rT   r    r    r$   Útest_dbscan_clustering²   s    
rt   Úcut_distance)çš™™™™™¹?ç      à?r3   c                 C   sä   t d d }t d d }t ¡ }tjdg|d< dtjg|d< tjtjg|d< tƒ  |¡}|j| d�}t 	||k¡}t
|ddgƒ t 	||k¡}t
|dgƒ tttd	ƒƒt|| ƒ ƒ}tƒ  || ¡}	|	j| d�}
t
|
|| ƒ d
S )r'   r)   r   r(   r3   r   rd   r4   )ru   r   N)r	   r8   r9   r0   r6   r7   r   r:   rs   Zflatnonzeror   r<   rK   r=   )ru   Zmissing_labelZinfinite_labelr>   r?   rS   r@   Zinfinite_labels_idxZ	clean_idxrA   Zclean_labelsr    r    r$   Ú#test_dbscan_clustering_outlier_data¿   s     rx   c                  C   sb   t dddd�\} }tƒ  | ¡} tdddt | jd ¡id	� | ¡}tt	|ƒt
 ƒ}|tks^t‚d
S )zQ
    Tests that HDBSCAN using `BallTree` works with higher-dimensional data.
    rY   r   é@   )r   r   Z
n_featuresr   rf   rb   r3   rh   N)r
   r   Úfit_transformr   r0   rl   rk   rI   rJ   rK   rL   rM   rN   )ÚHr-   rS   rT   r    r    r$   Útest_hdbscan_high_dimensionalÚ   s    ýür|   c                  C   sB   t ddt tjd ¡id� t¡} tt| ƒt ƒ}|t	ks>t
‚dS )z4
    Tests that HDBSCAN using `BallTree` works.
    rf   rb   r3   )rD   ri   N)r   r0   rl   r8   rk   rI   rJ   rK   rL   rM   rN   ©rS   rT   r    r    r$   Ú!test_hdbscan_best_balltree_metricé   s     ÿþr~   c                  C   s8   t ttƒd d� t¡} tt| ƒt ƒ}|dks4t‚dS )zƒ
    Tests that HDBSCAN correctly does not generate a valid cluster when the
    `min_cluster_size` is too large for the data.
    r3   ©Úmin_cluster_sizer   N)r   rJ   r8   rI   rK   rL   rN   r}   r    r    r$   Útest_hdbscan_no_clustersô   s    r�   c                  C   s\   t dttƒdƒD ]F} t| d� t¡}dd„ |D ƒ}t|ƒdkrt t |¡¡| kst‚qdS )zb
    Test that the smallest non-noise cluster has at least `min_cluster_size`
    many points
    rd   r3   r   c                 S   s   g | ]}|d kr|‘qS )r   r    )r!   r   r    r    r$   Ú
<listcomp>  s      z1test_hdbscan_min_cluster_size.<locals>.<listcomp>r   N)	r=   rJ   r8   r   rI   r0   ÚminZbincountrN   )r€   rS   Ztrue_labelsr    r    r$   Útest_hdbscan_min_cluster_sizeþ   s
    r„   c                  C   s6   t j} t| d� t¡}tt|ƒt ƒ}|tks2t	‚dS )zA
    Tests that HDBSCAN works when passed a callable metric.
    rH   N)
r   Ú	euclideanr   rI   r8   rJ   rK   rL   rM   rN   )rD   rS   rT   r    r    r$   Útest_hdbscan_callable_metric
  s    r†   ÚtreeÚkdZballc              	   C   s8   t dd| › d�d�}t t¡� | t¡ W 5 Q R X dS )z�
    Tests that HDBSCAN correctly raises an error when passing precomputed data
    while requesting a tree-based algorithm.
    rC   Zprims_r‡   ©rD   ra   N)r   rO   rP   rQ   r:   r8   )r‡   rp   r    r    r$   Ú"test_hdbscan_precomputed_non_brute  s    rŠ   c            	   	   C   s   t ƒ  t¡j} tt| ƒt ƒ}|dks*t‚t 	t¡}| 
¡ }t ƒ  |¡j}t| |ƒ tjdftjdffD ]‚\}}t 
¡ }||d< t ƒ  |¡j} tt| ƒt ƒ}|dksªt‚| d t| d ksÂt‚| 
¡ }||d< t ƒ  |¡j}t| |ƒ qhd}tjt|d�� t d	d
d� |¡ W 5 Q R X dS )z¨
    Tests that HDBSCAN works correctly when passing sparse feature data.
    Evaluates correctness by comparing against the same data passed as a dense
    array.
    r   r(   r)   ©r   r   r   r   z4Sparse data matrices only support algorithm `brute`.rF   r…   r   r‰   N)r   r:   r8   r;   rJ   rK   rL   rN   r   Ú
csr_matrixr9   r   r0   r6   r7   r	   rO   rP   rQ   )	Zdense_labelsrT   Z	_X_sparseZX_sparseZsparse_labelsZoutlier_valr&   ZX_denserV   r    r    r$   Útest_hdbscan_sparse  s*    

r�   ra   c                 C   s®   ddg}t dd|dd�\}}tdd� |¡}t||j|jƒD ]*\}}}t||d	d
d� t||d	d
d� q<t| dtjd d� t¡}|jjd dks–t	‚|jjd dksªt	‚dS )zj
    Tests that HDBSCAN centers are calculated and stored properly, and are
    accurate to the data.
    )rZ   rZ   )ç      @rŽ   iè  r   rw   )r   r   ÚcentersÚcluster_stdZboth)Ústore_centersr3   gš™™™™™©?)ZrtolZatol)ra   r‘   r€   N)
r
   r   r:   ÚzipZ
centroids_Zmedoids_r   r8   rk   rN   )ra   r�   r{   r"   rp   ÚcenterZcentroidZmedoidr    r    r$   Útest_hdbscan_centersC  s      ÿþr”   c                  C   s¶   t j d¡} |  dd¡}tddddd� |¡}t j|dd	�\}}t|ƒdksPt‚||d
k dksdt‚tdddddd� |¡}t j|dd	�\}}t|ƒdksžt‚||d
k dks²t‚dS )zS
    Tests that HDBSCAN single-cluster selection with epsilon works correctly.
    r   é–   rd   r4   rZ   ZeomT)r€   Úcluster_selection_epsilonÚcluster_selection_methodÚallow_single_cluster)Zreturn_countsr   é   g
×£p=
Ç?r   )r€   r–   r—   r˜   ra   N)	r0   ÚrandomZRandomStateZrandr   rI   ÚuniquerJ   rN   )ÚrngZno_structurerS   Zunique_labelsÚcountsr    r    r$   Ú.test_hdbscan_allow_single_cluster_with_epsilonY  s2    üûûúrž   c                  C   sp   ddgddgddgddgg} t d| ddddgd	d
�\}}tƒ  |¡}tt|jƒƒtd|jkƒ }|dkslt‚dS )zœ
    Validate that HDBSCAN can properly cluster this difficult synthetic
    dataset. Note that DBSCAN fails on this (see HDBSCAN plotting
    example)
    g333333ë¿g333333ë?r   éýÿÿÿiî  çš™™™™™É?gffffffÖ?gš™™™™™õ?r   )r   r�   r�   r   r   é   N)r
   r   r:   rJ   rK   r;   ÚintrN   )r�   r8   r"   rp   rT   r    r    r$   Útest_hdbscan_better_than_dbscanz  s    
ü
r£   z	kwargs, XrC   r3   rd   r¡   c                 C   s   t f ddi|—Ž | ¡ dS )zo
    Tests that HDBSCAN works correctly for array-likes and precomputed inputs
    with non-finite points.
    Úmin_samplesr3   N)r   r:   )r8   Úkwargsr    r    r$   Útest_hdbscan_usable_inputsŒ  s    r¦   c               	   C   sB   t  t d¡¡} d}tjt|d�� tdd� | ¡ W 5 Q R X dS )zd
    Tests that HDBSCAN raises the correct error when there are too few
    non-zero distances.
    )r   r   z#There exists points with fewer thanrF   rC   rH   N)	r   rŒ   r0   ZzerosrO   rP   rQ   r   r:   )r8   rV   r    r    r$   Ú-test_hdbscan_sparse_distances_too_few_nonzeroœ  s    r§   c               	   C   s¼   dd„ } d}t jt|d�� td| d� t¡ W 5 Q R X t jt|d�� td| d� t¡ W 5 Q R X tttj	ƒtt
j	ƒ ƒ}t|ƒdkr¸t jt|d�� td|d d� t¡ W 5 Q R X d	S )
zR
    Tests that HDBSCAN correctly raises an error for invalid metric choices.
    c                 S   s   | S r*   r    )r,   r    r    r$   r.   ¬  r/   z2test_hdbscan_tree_invalid_metric.<locals>.<lambda>zV.* is not a valid metric for a .*-based algorithm\. Please select a different metric\.rF   r   )ra   rD   r   r   N)rO   rP   rQ   r   r:   r8   r<   rK   r   rn   r   rJ   )Zmetric_callablerV   Zmetrics_not_kdr    r    r$   Ú test_hdbscan_tree_invalid_metric¨  s    ÿr¨   c               	   C   s>   t ttƒd d�} d}tjt|d�� |  t¡ W 5 Q R X dS )zx
    Tests that HDBSCAN correctly raises an error when setting `min_samples`
    larger than the number of samples.
    r3   )r¤   z min_samples (.*) must be at mostrF   N)r   rJ   r8   rO   rP   rQ   r:   )rp   rV   r    r    r$   Ú!test_hdbscan_too_many_min_samplesÀ  s    r©   c               	   C   sH   t  ¡ } tj| d< d}tdd�}tjt|d�� | | ¡ W 5 Q R X dS )zu
    Tests that HDBSCAN correctly raises an error when providing precomputed
    distances with `np.nan` values.
    r‹   z(np.nan values found in precomputed-denserC   rH   rF   N)	r8   r9   r0   r7   r   rO   rP   rQ   r:   )ZX_nanrV   rp   r    r    r$   Ú"test_hdbscan_precomputed_dense_nanË  s    

rª   r˜   TFÚepsilonrv   c                    sÜ   d}t || ddgddgddggd�\}‰tƒ  |¡}t|j|jd�}|d |d |d h}|d d|d d	|d di}t|||||d
�‰‡fdd„ttˆƒƒD ƒ‰ ‡ ‡fdd„ttˆƒƒD ƒ}	t	 
|	j¡ˆƒ}
tˆ|
ƒ dS )zR
    Tests that the `_do_labelling` helper function correctly assigns labels.
    é0   r   r   )r   r�   r   rd   r   r¡   r3   ©Úcondensed_treeÚclustersÚcluster_label_mapr˜   r–   c                    s$   i | ]}|t  ˆ |k¡d  d  “qS )r   )r0   Úwhere©r!   Z_y)r-   r    r$   Ú
<dictcomp>ø  s      z+test_labelling_distinct.<locals>.<dictcomp>c                    s   i | ]}|ˆˆ |  “qS r    r    r²   )Úfirst_with_labelrS   r    r$   r³   ù  s      N)r
   r   r:   r   Z_single_linkage_tree_r€   r   r<   rK   r0   Z	vectorizerm   r   )Zglobal_random_seedr˜   r«   r   r8   Zestr®   r¯   r°   Zy_to_labelsZaligned_targetr    )r´   rS   r-   r$   Útest_labelling_distinctØ  s6    ýü
 ÿûrµ   c                  C   s¼   d} d}t jdd|dfddd|dfddgtd	�}t|| h| d| d did
dd�}|d dk }t|ƒt|dkƒkstt‚t|| h| d| d did
dd�}|d |k }t|ƒt|dkƒks¸t‚dS )zž
    Tests that the `_do_labelling` helper function correctly thresholds the
    incoming lambda values given various `cluster_selection_epsilon` values.
    r4   g      ø?rd   r3   )r4   r3   rv   r3   r   )r4   r   r    r3   )r4   r¡   rr   r3   )ZdtypeTr­   Úvaluer   N)r0   Úarrayr   r   ÚsumrN   )r   Z
MAX_LAMBDAr®   rS   Z	num_noiser    r    r$   Útest_labelling_thresholdingþ  s:    

ûø
ûû
r¹   )GÚ__doc__Únumpyr0   rO   Zscipyr   r   Zscipy.spatialr   Zsklearn.clusterr   Zsklearn.cluster._hdbscan._treer   r   r   Z sklearn.cluster._hdbscan.hdbscanr	   Zsklearn.datasetsr
   Zsklearn.metricsr   Zsklearn.metrics.pairwiser   r   Zsklearn.neighborsr   r   Zsklearn.preprocessingr   Zsklearn.utilsr   Zsklearn.utils._testingr   r   rM   r8   r-   rz   Z
ALGORITHMSÚitemsrL   ÚmarkZparametrizerB   rW   rŒ   Z
csc_matrixr^   r_   rq   rt   rx   r|   r~   r�   r„   r†   rŠ   r�   r”   rž   r£   r·   r6   r¦   r§   r¨   r©   rª   rµ   r¹   r    r    r    r$   Ú<module>   s€   ü

(




$
! ýþ
$