a
    �ù»jN  ã                	   @   sD  d 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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dl!m"Z"m#Z# eddd�\Z$Z%ee$e%dd�\Z$Z%eƒ  &e$¡Z$g d¢Z'dhdd„ e (¡ D ƒB Z)dodd„Z*ej+ ,de¡dd„ ƒZ-dd „ Z.ej+ ,d!g e#¢e"¢¡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„ Z7ej+ ,d8d9d:g¡d;d<„ ƒZ8ej+ ,d=e#¡d>d?„ ƒZ9ej+ ,d@e'¡dAdB„ ƒZ:dCdD„ Z;dEdF„ Z<ej+ ,dGd'dHie =dIej>gej>dIgg¡fd'dHidIdJgdJdIggfi dIdJgdKdLggfg¡dMdN„ ƒZ?ej+ ,d=e#¡dOdP„ ƒZ@ej+ ,d=e#¡dQdR„ ƒZAdSdT„ ZBdUdV„ ZCdWdX„ ZDej+ ,dYdZd[g¡ej+ ,d\dd]g¡d^d_„ ƒƒZEd`da„ ZFej+ ,dbdcddg¡dedf„ ƒZGej+ ,dgdhdig¡djdk„ ƒZHej+ ,dld9d:g¡dmdn„ ƒZIdS )pzF
Tests for HDBSCAN clustering algorithm
Based on the DBSCAN test code
é    N)Ú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)ÚCSC_CONTAINERSÚCSR_CONTAINERSéÈ   é
   )Ú	n_samplesÚrandom_stateé   )r   )Úkd_treeÚ	ball_treeÚbruteÚautoéÿÿÿÿc                 C   s   h | ]\}}|d  ’qS )Úlabel© )Ú.0Ú_Úoutr    r    úHE:\soccer\ml_env\Lib\site-packages\sklearn/cluster/tests/test_hdbscan.pyÚ	<setcomp>&   ó    r%   ç®Gáz®ï?c                 C   s2   t t| ƒt ƒ}|dksJ ‚t| tƒ|ks.J ‚d S )Né   )ÚlenÚsetÚOUTLIER_SETr
   Úy)ÚlabelsÚ	thresholdÚ
n_clustersr    r    r$   Úcheck_label_quality)   s    r0   Ú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    ©Úxr,   r    r    r$   Ú<lambda>9   r&   z#test_outlier_data.<locals>.<lambda>c                 S   s
   t  | ¡S r5   )ÚnpÚisnanr6   r    r    r$   r8   :   r&   r   Úprobé   r   é   é   r   N)r9   ÚinfÚnanr   ÚXÚcopyr   ÚfitÚlabels_Znonzeror   Zprobabilities_ÚlistÚrange)r1   ZoutlierZ
prob_checkr   r;   Ú	X_outlierÚmodelÚmissing_labels_idxZmissing_probs_idxZclean_indicesÚclean_modelr    r    r$   Útest_outlier_data/   s.    þýþýrK   c                  C   sÎ   t tƒ} |  ¡ }tddd� | ¡}t| |ƒ t|ƒ d}tjt	|d��" tddd� t¡ W d  ƒ n1 sn0    Y  d}d| d	< d
| d< tjt	|d��  tdd� | ¡ W d  ƒ n1 sÀ0    Y  dS )zy
    Tests that HDBSCAN works with precomputed distance matrices, and throws the
    appropriate errors when needed.
    ÚprecomputedT)ÚmetricrB   z*The precomputed distance matrix.*has shape©ÚmatchNz'The precomputed distance matrix.*valuesr   )r   r<   r<   )r<   r   ©rM   )
r   rA   rB   r   Úfit_predictr   r0   ÚpytestÚraisesÚ
ValueError)ÚDZ
D_originalr-   Úmsgr    r    r$   Útest_hdbscan_distance_matrixO   s    
0rW   Úsparse_constructorc                 C   sf   t  t  t¡¡}|t |¡ }t | ¡ d¡}d|||k< | |ƒ}| 	¡  t
dd� |¡}t|ƒ dS )zA
    Tests that HDBSCAN works with sparse distance matrices.
    é2   ç        rL   rP   N)r   Z
squareformZpdistrA   r9   Úmaxr   ZscoreatpercentileÚflattenZeliminate_zerosr   rQ   r0   )rX   rU   r.   r-   r    r    r$   Ú#test_hdbscan_sparse_distance_matrixg   s    r]   c                  C   s   t ƒ  t¡} 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.
    N)r   rQ   rA   r0   ©r-   r    r    r$   Útest_hdbscan_feature_arrayy   s    r_   ÚalgorM   c                 C   s  t | d� t¡}t|ƒ | dv r$d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vrÌt t¡� | t¡ W d  ƒ n1 sÀ0    Y  nL|dk�rt t¡� | t¡ W d  ƒ n1 �s0    Y  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   ÚVr<   Úpé   )rc   Úw)ZmahalanobisÚ
seuclideanZ	minkowskiÚ
wminkowski)ra   rM   Úmetric_paramsrg   )r   rQ   rA   r0   r   r   r9   ÚeyeÚshapeÚonesÚgetÚvalid_metricsrR   rS   rT   rC   ZwarnsÚFutureWarning)r`   rM   r-   ZALGOS_TREESrh   Úhdbr    r    r$   Útest_hdbscan_algorithms…   s4    þüûý*
,rp   c                  C   s&   t ƒ  t¡} |  d¡}t|dd� 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.
    ç333333Ó?gq=
×£pí?)r.   N)r   rC   rA   Údbscan_clusteringr0   )Z	clustererr-   r    r    r$   Útest_dbscan_clustering®   s    
rs   Úcut_distance)çš™™™™™¹?ç      à?r<   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 )r2   r4   r   r3   r<   r   rd   r=   )rt   r   N)r   rA   rB   r9   r?   r@   r   rC   rr   Zflatnonzeror   rE   r*   rF   )rt   Zmissing_labelZinfinite_labelrG   rH   r-   rI   Zinfinite_labels_idxZ	clean_idxrJ   Zclean_labelsr    r    r$   Ú#test_dbscan_clustering_outlier_data»   s     rw   c                  C   s.   t ddt tjd ¡id� t¡} t| ƒ dS )z4
    Tests that HDBSCAN using `BallTree` works.
    rf   rb   r<   )rM   rh   N)r   r9   rk   rA   rj   rQ   r0   r^   r    r    r$   Ú!test_hdbscan_best_balltree_metricÖ   s    ÿþrx   c                  C   s.   t ttƒd d� t¡} t| ƒ t¡s*J ‚dS )zƒ
    Tests that HDBSCAN correctly does not generate a valid cluster when the
    `min_cluster_size` is too large for the data.
    r<   ©Úmin_cluster_sizeN)r   r)   rA   rQ   r*   Úissubsetr+   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J ‚qdS )zb
    Test that the smallest non-noise cluster has at least `min_cluster_size`
    many points
    rd   r<   ry   c                 S   s   g | ]}|d kr|‘qS )r   r    )r!   r   r    r    r$   Ú
<listcomp>ð   r&   z1test_hdbscan_min_cluster_size.<locals>.<listcomp>r   N)rF   r)   rA   r   rQ   r9   ÚminZbincount)rz   r-   Ztrue_labelsr    r    r$   Útest_hdbscan_min_cluster_sizeé   s
    r   c                  C   s"   t j} t| d� t¡}t|ƒ dS )zA
    Tests that HDBSCAN works when passed a callable metric.
    rP   N)r   Ú	euclideanr   rQ   rA   r0   )rM   r-   r    r    r$   Útest_hdbscan_callable_metricõ   s    r�   Útreer   r   c                 C   sL   t d| d�}d}tjt|d�� | t¡ W d  ƒ n1 s>0    Y  dS )z�
    Tests that HDBSCAN correctly raises an error when passing precomputed data
    while requesting a tree-based algorithm.
    rL   ©rM   ra   z%precomputed is not a valid metric forrN   N)r   rR   rS   rT   rC   rA   )r‚   ro   rV   r    r    r$   Ú"test_hdbscan_precomputed_non_bruteþ   s    r„   Úcsr_containerc           	      C   s
  t ƒ  t¡j}t|ƒ | tƒ}| ¡ }t ƒ  |¡j}t||ƒ tjdftj	dffD ]n\}}t ¡ }||d< t ƒ  |¡j}t|ƒ |d t
| d ks˜J ‚| ¡ }||d< t ƒ  |¡j}t||ƒ qRd}tjt|d��" t dd	d
� |¡ W d  ƒ n1 sü0    Y  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.
    r3   r4   ©r   r   r   r   z4Sparse data matrices only support algorithm `brute`.rN   r€   r   rƒ   N)r   rC   rA   rD   r0   rB   r   r9   r?   r@   r   rR   rS   rT   )	r…   Zdense_labelsZ	_X_sparseZX_sparseZsparse_labelsZoutlier_valr1   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–J ‚|jjd dksªJ ‚dS )zj
    Tests that HDBSCAN centers are calculated and stored properly, and are
    accurate to the data.
    )rZ   rZ   )ç      @rˆ   iÐ  r   rv   )r   r   ÚcentersÚcluster_stdZboth)Ústore_centersr<   gš™™™™™©?)ZrtolZatol)ra   r‹   rz   N)	r	   r   rC   ÚzipZ
centroids_Zmedoids_r   rA   rj   )ra   r‰   ÚHr"   ro   ÚcenterÚcentroidÚmedoidr    r    r$   Útest_hdbscan_centers-  s    ÿþr‘   c                  C   s¶   t j d¡} |  dd¡}tddddd� |¡}t j|dd	�\}}t|ƒdksPJ ‚||d
k dksdJ ‚tdddddd� |¡}t j|dd	�\}}t|ƒdksžJ ‚||d
k dks²J ‚dS )zS
    Tests that HDBSCAN single-cluster selection with epsilon works correctly.
    r   é–   rd   r=   rZ   ZeomT)rz   Úcluster_selection_epsilonÚcluster_selection_methodÚallow_single_cluster)Zreturn_countsr   é   g
×£p=
Ç?r   )rz   r“   r”   r•   ra   N)r9   ÚrandomÚRandomStateZrandr   rQ   Úuniquer)   )ÚrngZno_structurer-   Zunique_labelsÚcountsr    r    r$   Ú.test_hdbscan_allow_single_cluster_with_epsilonC  s2    üûûúrœ   c                  C   sx   ddgddgddgddgg} t d| g d¢dd�\}}tƒ  |¡j}tt|ƒƒtd	|v ƒ }|d
ksfJ ‚t||ƒdk 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Ö?çš™™™™™õ?rŸ   r   )r   r‰   rŠ   r   r   é   r'   N)r	   r   rC   rD   r)   r*   Úintr
   )r‰   rA   r,   r-   r/   r    r    r$   Útest_hdbscan_better_than_dbscand  s    ü
r¢   z	kwargs, XrL   r<   rd   r(   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_samplesr<   N)r   rC   )rA   Úkwargsr    r    r$   Útest_hdbscan_usable_inputsx  s    r¥   c                 C   sT   | t  d¡ƒ}d}tjt|d��  tdd� |¡ W d  ƒ n1 sF0    Y  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 thanrN   rL   rP   N)r9   ÚzerosrR   rS   rT   r   rC   ©r…   rA   rV   r    r    r$   Ú-test_hdbscan_sparse_distances_too_few_nonzeroˆ  s    r¨   c                 C   sŠ   t  d¡}d|dd…dd…f< d|dd…dd…f< ||j }| |ƒ}d}tjt|d��  tdd	� |¡ W d  ƒ n1 s|0    Y  dS )
zu
    Tests that HDBSCAN raises the correct error when the distance matrix
    has multiple connected components.
    )é   r©   r<   Nr=   é   z2HDBSCAN cannot be perfomed on a disconnected graphrN   rL   rP   )r9   r¦   ÚTrR   rS   rT   r   rC   r§   r    r    r$   Ú0test_hdbscan_sparse_distances_disconnected_graph•  s    

r¬   c                  C   sø   dd„ } d}t jt|d��" td| d� t¡ W d  ƒ n1 sB0    Y  t jt|d��" td| d� t¡ W d  ƒ n1 s‚0    Y  tttj	ƒtt
j	ƒ ƒ}t|ƒd	krôt jt|d��& td|d	 d� t¡ W d  ƒ n1 sê0    Y  dS )
zR
    Tests that HDBSCAN correctly raises an error for invalid metric choices.
    c                 S   s   | S r5   r    )r7   r    r    r$   r8   ª  r&   z2test_hdbscan_tree_invalid_metric.<locals>.<lambda>zV.* is not a valid metric for a .*-based algorithm\. Please select a different metric\.rN   r   )ra   rM   Nr   r   )rR   rS   rT   r   rC   rA   rE   r*   r   rm   r   r)   )Zmetric_callablerV   Zmetrics_not_kdr    r    r$   Ú test_hdbscan_tree_invalid_metric¦  s    ÿ00r­   c                  C   sR   t ttƒd d�} d}tjt|d�� |  t¡ W d  ƒ n1 sD0    Y  dS )zx
    Tests that HDBSCAN correctly raises an error when setting `min_samples`
    larger than the number of samples.
    r<   )r£   z min_samples (.*) must be at mostrN   N)r   r)   rA   rR   rS   rT   rC   )ro   rV   r    r    r$   Ú!test_hdbscan_too_many_min_samples¾  s    r®   c                  C   s\   t  ¡ } tj| d< d}tdd�}tjt|d�� | | ¡ W d  ƒ n1 sN0    Y  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-denserL   rP   rN   N)	rA   rB   r9   r@   r   rR   rS   rT   rC   )ZX_nanrV   ro   r    r    r$   Ú"test_hdbscan_precomputed_dense_nanÉ  s    

r¯   r•   TFÚepsilonru   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‰   ry   rd   r(   r    r<   ©Úcondensed_treeÚclustersÚcluster_label_mapr•   r“   c                    s$   i | ]}|t  ˆ |k¡d  d  “qS )r   )r9   Úwhere©r!   Z_y)r,   r    r$   Ú
<dictcomp>ö  r&   z+test_labelling_distinct.<locals>.<dictcomp>c                    s   i | ]}|ˆˆ |  “qS r    r    r·   )Úfirst_with_labelr-   r    r$   r¸   ÷  r&   N)r	   r   rC   r   Z_single_linkage_tree_rz   r   rE   r*   r9   Z	vectorizerl   r   )Zglobal_random_seedr•   r°   r   rA   Zestr³   r´   rµ   Zy_to_labelsZaligned_targetr    )r¹   r-   r,   r$   Útest_labelling_distinctÖ  s4    ýü
ÿû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stJ ‚t|| h| d| d did
dd�}|d |k }t|ƒt|dkƒks¸J ‚dS )zž
    Tests that the `_do_labelling` helper function correctly thresholds the
    incoming lambda values given various `cluster_selection_epsilon` values.
    r=   g      ø?rd   r<   )r=   r<   ru   r<   r   )r=   r(   rž   r<   )r=   r    rq   r<   )ZdtypeTr²   Úvaluer   N)r9   Úarrayr   r   Úsum)r   Z
MAX_LAMBDAr³   r-   Z	num_noiser    r    r$   Útest_labelling_thresholdingü  s:    

ûø
ûû
r¾   r‹   r�   r�   c                 C   sf   t j d¡}| d¡}t|ƒ}d}tjt|d��" td| d� |¡ W d  ƒ n1 sX0    Y  dS )zÈCheck that we raise an error if the centers are requested together with
    a precomputed input matrix.

    Non-regression test for:
    https://github.com/scikit-learn/scikit-learn/issues/27893
    r   )éd   rd   z>Cannot store centers when using a precomputed distance matrix.rN   rL   )rM   r‹   N)	r9   r—   r˜   r   rR   rS   rT   r   rC   )r‹   rš   rA   ZX_distÚerr_msgr    r    r$   Ú0test_hdbscan_error_precomputed_and_store_centers%  s    
rÁ   Ú
valid_algor   r   c                 C   s   t d| d� t¡ dS )z“Test that HDBSCAN works with the "cosine" metric when the algorithm is set
    to "brute" or "auto".

    Non-regression test for issue #28631
    Úcosinerƒ   N)r   rQ   rA   )rÂ   r    r    r$   Ú*test_hdbscan_cosine_metric_valid_algorithm5  s    rÄ   Úinvalid_algoc                 C   sH   t d| d�}tjtdd�� | t¡ W d  ƒ n1 s:0    Y  dS )z€Test that HDBSCAN raises an informative error is raised when an unsupported
    algorithm is used with the "cosine" metric.
    rÃ   rƒ   zcosine is not a valid metricrN   N)r   rR   rS   rT   rQ   rA   )rÅ   Zhdbscanr    r    r$   Ú,test_hdbscan_cosine_metric_invalid_algorithm?  s    rÆ   )r'   )JÚ__doc__Únumpyr9   rR   Zscipyr   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   Zsklearn.utils.fixesr   r   rA   r,   Zfit_transformZ
ALGORITHMSÚitemsr+   r0   ÚmarkZparametrizerK   rW   r]   r_   rp   rs   rw   rx   r|   r   r�   r„   r‡   r‘   rœ   r¢   r¼   r?   r¥   r¨   r¬   r­   r®   r¯   rº   r¾   rÁ   rÄ   rÆ   r    r    r    r$   Ú<module>   sŒ   


'

		

"
! ýþ


$)

	