
    0Ph                        U d Z ddlmZmZ ddlmZ ddlZddlm	Z	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mZ ddlmZmZmZ ddl m!Z!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z)m*Z*  e+ej,        ej,        z             Z-ddddej.        ddZ/e0e1d<   d Z2d Z3	 	 	 	 	 d$dZ4	 	 	 	 	 d%dZ5d  Z6d! Z7 G d" d#ee          Z8dS )&z\
HDBSCAN: Hierarchical Density-Based Spatial Clustering
         of Applications with Noise
    )IntegralReal)warnN)csgraphissparse   )BaseEstimatorClusterMixin_fit_context)pairwise_distances)DistanceMetric)_VALID_METRICS)BallTreeKDTreeNearestNeighbors)Interval
StrOptions)_allclose_dense_sparse_assert_all_finitevalidate_data   )MST_edge_dtypemake_single_linkagemst_from_data_matrixmst_from_mutual_reachability)mutual_reachability_graph)HIERARCHY_dtypelabelling_at_cuttree_to_labels)labelprob)infinitemissing_OUTLIER_ENCODINGc                    t          |           st          |           S | j        | j        d         }t	          fdt          |          D                       rt          d d d          t          j        | dd          }|dk    rt          d	| d
          t          j	        |           }|
                                \  }}t          j                            |||j        gt                    }|S )aJ  
    Builds a minimum spanning tree (MST) from the provided mutual-reachability
    values. This function dispatches to a custom Cython implementation for
    dense arrays, and `scipy.sparse.csgraph.minimum_spanning_tree` for sparse
    arrays/matrices.

    Parameters
    ----------
    mututal_reachability_graph: {ndarray, sparse matrix} of shape             (n_samples, n_samples)
        Weighted adjacency matrix of the mutual reachability graph.

    min_samples : int, default=None
        The number of samples in a neighborhood for a point
        to be considered as a core point. This includes the point itself.

    Returns
    -------
    mst : ndarray of shape (n_samples - 1,), dtype=MST_edge_dtype
        The MST representation of the mutual-reachability graph. The MST is
        represented as a collection of edges.
    r   c              3   H   K   | ]}|d z            |         z
  k     V  dS )r   N ).0iindptrmin_sampless     `/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/cluster/_hdbscan/hdbscan.py	<genexpr>z_brute_mst.<locals>.<genexpr>x   s9      
P
PF1q5MF1I%4
P
P
P
P
P
P    z$There exists points with fewer than zV neighbors. Ensure your distance matrix has non-zero values for at least `min_sample`=z neighbors for each points (i.e. K-nn graph), or specify a `max_distance` in `metric_params` to use when distances are missing.F)directedreturn_labelsr   z&Sparse mutual reachability matrix has z connected components. HDBSCAN cannot be perfomed on a disconnected graph. Ensure that the sparse distance matrix has only one connected component.dtype)r   r   r,   shapeanyrange
ValueErrorr   connected_componentsminimum_spanning_treenonzeronprec
fromarraysdatar   )	mutual_reachabilityr-   
num_pointsn_componentssparse_min_spanning_treerowscolsmstr,   s	    `      @r.   
_brute_mstrG   Z   sY   . '(( A+,?@@@ !'F$*1-J

P
P
P
P
PeJ>O>O
P
P
PPP 
&; & &(& & &
 
 	
 /e5  L aQ\ Q Q Q
 
 	
  '<=PQQ)1133JD$
&

	t-23   C Jr0   c                 d    t          j        | d                   }| |         } t          |           S )a8  
    Builds a single-linkage tree (SLT) from the provided minimum spanning tree
    (MST). The MST is first sorted then processed by a custom Cython routine.

    Parameters
    ----------
    min_spanning_tree : ndarray of shape (n_samples - 1,), dtype=MST_edge_dtype
        The MST representation of the mutual-reachability graph. The MST is
        represented as a collection of edges.

    Returns
    -------
    single_linkage : ndarray of shape (n_samples - 1,), dtype=HIERARCHY_dtype
        The single-linkage tree tree (dendrogram) built from the MST.
    distance)r<   argsortr   )min_spanning_tree	row_orders     r.   _process_mstrM      s3    " 
,Z899I))40111r0      	euclideanFc                    |dk    rq| j         d         | j         d         k    rt          d| j          d          t          | | j                  st          d          |r|                                 n| }nt          | f||d|}||z  }|                    dd	          }t          |          r|j        d
k    r|	                                }t          |||          }	t          |	|          }
t          j        |
d                                                   rt          dt                      t#          |
          S )a  
    Builds a single-linkage tree (SLT) from the input data `X`. If
    `metric="precomputed"` then `X` must be a symmetric array of distances.
    Otherwise, the pairwise distances are calculated directly and passed to
    `mutual_reachability_graph`.

    Parameters
    ----------
    X : ndarray of shape (n_samples, n_features) or (n_samples, n_samples)
        Either the raw data from which to compute the pairwise distances,
        or the precomputed distances.

    min_samples : int, default=None
        The number of samples in a neighborhood for a point
        to be considered as a core point. This includes the point itself.

    alpha : float, default=1.0
        A distance scaling parameter as used in robust single linkage.

    metric : str or callable, default='euclidean'
        The metric to use when calculating distance between instances in a
        feature array.

        - If metric is a string or callable, it must be one of
          the options allowed by :func:`~sklearn.metrics.pairwise_distances`
          for its metric parameter.

        - If metric is "precomputed", X is assumed to be a distance matrix and
          must be square.

    n_jobs : int, default=None
        The number of jobs to use for computing the pairwise distances. This
        works by breaking down the pairwise matrix into n_jobs even slices and
        computing them in parallel. This parameter is passed directly to
        :func:`~sklearn.metrics.pairwise_distances`.

        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    copy : bool, default=False
        If `copy=True` then any time an in-place modifications would be made
        that would overwrite `X`, a copy will first be made, guaranteeing that
        the original data will be unchanged. Currently, it only applies when
        `metric="precomputed"`, when passing a dense array or a CSR sparse
        array/matrix.

    metric_params : dict, default=None
        Arguments passed to the distance metric.

    Returns
    -------
    single_linkage : ndarray of shape (n_samples - 1,), dtype=HIERARCHY_dtype
        The single-linkage tree tree (dendrogram) built from the MST.
    precomputedr   r   zRThe precomputed distance matrix is expected to be symmetric, however it has shape zC. Please verify that the distance matrix was constructed correctly.zThe precomputed distance matrix is expected to be symmetric, however its values appear to be asymmetric. Please verify that the distance matrix was constructed correctly.)metricn_jobsmax_distance        csr)r-   rT   )r-   rI   zThe minimum spanning tree contains edge weights with value infinity. Potentially, you are missing too many distances in the initial distance matrix for the given neighborhood size.)r5   r8   r   Tcopyr   getr   formattocsrr   rG   r<   isinfr6   r   UserWarningrM   )Xr-   alpharR   rS   rX   metric_paramsdistance_matrixrT   mutual_reachability_rK   s              r.   _hdbscan_bruterc      s   @ 71:##>!"> > >  
 &a-- 	5   '+1!&&(((,
V
 
/<
 
 uO $$^S99L   2_%;u%D%D *//11 5[|   ##7[QQQ	x!*-..2244 	

 	
 	
 	
 )***r0         ?(   c           	      X   t          j        | d          } t          ||||||d                              |           }|                    | |d          \  }	}
t          j        |	dddf                   }t          j        |fi |}t          | |||          }t          |          S )a  
    Builds a single-linkage tree (SLT) from the input data `X`. If
    `metric="precomputed"` then `X` must be a symmetric array of distances.
    Otherwise, the pairwise distances are calculated directly and passed to
    `mutual_reachability_graph`.

    Parameters
    ----------
    X : ndarray of shape (n_samples, n_features)
        The raw data.

    min_samples : int, default=None
        The number of samples in a neighborhood for a point
        to be considered as a core point. This includes the point itself.

    alpha : float, default=1.0
        A distance scaling parameter as used in robust single linkage.

    metric : str or callable, default='euclidean'
        The metric to use when calculating distance between instances in a
        feature array. `metric` must be one of the options allowed by
        :func:`~sklearn.metrics.pairwise_distances` for its metric
        parameter.

    n_jobs : int, default=None
        The number of jobs to use for computing the pairwise distances. This
        works by breaking down the pairwise matrix into n_jobs even slices and
        computing them in parallel. This parameter is passed directly to
        :func:`~sklearn.metrics.pairwise_distances`.

        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    copy : bool, default=False
        If `copy=True` then any time an in-place modifications would be made
        that would overwrite `X`, a copy will first be made, guaranteeing that
        the original data will be unchanged. Currently, it only applies when
        `metric="precomputed"`, when passing a dense array or a CSR sparse
        array/matrix.

    metric_params : dict, default=None
        Arguments passed to the distance metric.

    Returns
    -------
    single_linkage : ndarray of shape (n_samples - 1,), dtype=HIERARCHY_dtype
        The single-linkage tree tree (dendrogram) built from the MST.
    C)orderN)n_neighbors	algorithm	leaf_sizerR   r`   rS   pT)return_distance)
r<   asarrayr   fit
kneighborsascontiguousarrayr   
get_metricr   rM   )r^   algor-   r_   rR   rk   rS   r`   nbrsneighbors_distances_core_distancesdist_metricrK   s                 r.   _hdbscan_primsrz     s    x 	
1C   A #
   
c!ff 	 "__QT_RR)*=aaae*DEEN +FDDmDDK -QUSS)***r0   c                    t          |          }t          |          }t          |           D ]m\  }}| |         d         }| |         d         }||k     r||         | |         d<   n||z   | |         d<   ||k     r||         | |         d<   _||z   | |         d<   nt          j        t          |          t                    }	t          | | j        d         dz
           d         | | j        d         dz
           d                   }
| | j        d         dz
           d         }t          |          D ](\  }}||
dz   t          j        |dz   f|	|<   |
dz  }
|dz  })t          j        | |	g          } | S )ay  
    Takes an internal single_linkage_tree structure and adds back in a set of points
    that were initially detected as non-finite and returns that new tree.
    These points will all be merged into the final node at np.inf distance and
    considered noise points.

    Parameters
    ----------
    tree : ndarray of shape (n_samples - 1,), dtype=HIERARCHY_dtype
        The single-linkage tree tree (dendrogram) built from the MST.
    internal_to_raw: dict
        A mapping from internal integer index to the raw integer index
    non_finite : ndarray
        Boolean array of which entries in the raw data are non-finite
    	left_node
right_noder3   r   r   cluster_size)	len	enumerater<   zerosr   maxr5   infconcatenate)treeinternal_to_raw
non_finitefinite_countoutlier_countr+   rw   leftrightoutlier_treelast_cluster_idlast_cluster_sizeoutliers                r.   remap_single_linkage_treer   o  s     ''L
OOM$ : :1Aw{#Q%,#24#8DGK  #'-#7DGK <$3E$:DGL!!$)M$9DGL!!8C
OO?CCCLTZ]Q,d4:a=13D.El.S O TZ]Q./?
++  
7"Oa$7ARUVAVWQ1Q>4.//DKr0   c                 "   t          |           rCt          j        d t          |                                 j                  D                       }n<t          j        |                     d                                                    \  }|S )z_
    Returns the indices of the purely finite rows of a
    sparse matrix or dense ndarray
    c                 d    g | ]-\  }}t          j        t          j        |                    +|.S r)   )r<   allisfinite)r*   r+   rows      r.   
<listcomp>z+_get_finite_row_indices.<locals>.<listcomp>  s6    XXX61crvbkRUFVFV?W?WXQXXXr0   r   axis)	r   r<   arrayr   tolilr?   r   sumr;   )matrixrow_indicess     r.   _get_finite_row_indicesr     s    
  ChXXYv||~~':;;XXX
 
 VZZQZ%7%788@@BBr0   c                       e Zd ZdZ eeddd          g eeddd          dg eeddd          gd eeddd          g ee e	e
          z  dhz            egedg eeddd	          g eh d
          g eeddd          gedg eddh          gdgd eh d          gdgdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ ed          dd            ZddZd Zd dZ fdZ xZS )!HDBSCANa&  Cluster data using hierarchical density-based clustering.

    HDBSCAN - Hierarchical Density-Based Spatial Clustering of Applications
    with Noise. Performs :class:`~sklearn.cluster.DBSCAN` over varying epsilon
    values and integrates the result to find a clustering that gives the best
    stability over epsilon.
    This allows HDBSCAN to find clusters of varying densities (unlike
    :class:`~sklearn.cluster.DBSCAN`), and be more robust to parameter selection.
    Read more in the :ref:`User Guide <hdbscan>`.

    For an example of how to use HDBSCAN, as well as a comparison to
    :class:`~sklearn.cluster.DBSCAN`, please see the :ref:`plotting demo
    <sphx_glr_auto_examples_cluster_plot_hdbscan.py>`.

    .. versionadded:: 1.3

    Parameters
    ----------
    min_cluster_size : int, default=5
        The minimum number of samples in a group for that group to be
        considered a cluster; groupings smaller than this size will be left
        as noise.

    min_samples : int, default=None
        The parameter `k` used to calculate the distance between a point
        `x_p` and its k-th nearest neighbor.
        When `None`, defaults to `min_cluster_size`.

    cluster_selection_epsilon : float, default=0.0
        A distance threshold. Clusters below this value will be merged.
        See [5]_ for more information.

    max_cluster_size : int, default=None
        A limit to the size of clusters returned by the `"eom"` cluster
        selection algorithm. There is no limit when `max_cluster_size=None`.
        Has no effect if `cluster_selection_method="leaf"`.

    metric : str or callable, default='euclidean'
        The metric to use when calculating distance between instances in a
        feature array.

        - If metric is a string or callable, it must be one of
          the options allowed by :func:`~sklearn.metrics.pairwise_distances`
          for its metric parameter.

        - If metric is "precomputed", X is assumed to be a distance matrix and
          must be square.

    metric_params : dict, default=None
        Arguments passed to the distance metric.

    alpha : float, default=1.0
        A distance scaling parameter as used in robust single linkage.
        See [3]_ for more information.

    algorithm : {"auto", "brute", "kd_tree", "ball_tree"}, default="auto"
        Exactly which algorithm to use for computing core distances; By default
        this is set to `"auto"` which attempts to use a
        :class:`~sklearn.neighbors.KDTree` tree if possible, otherwise it uses
        a :class:`~sklearn.neighbors.BallTree` tree. Both `"kd_tree"` and
        `"ball_tree"` algorithms use the
        :class:`~sklearn.neighbors.NearestNeighbors` estimator.

        If the `X` passed during `fit` is sparse or `metric` is invalid for
        both :class:`~sklearn.neighbors.KDTree` and
        :class:`~sklearn.neighbors.BallTree`, then it resolves to use the
        `"brute"` algorithm.

    leaf_size : int, default=40
        Leaf size for trees responsible for fast nearest neighbour queries when
        a KDTree or a BallTree are used as core-distance algorithms. A large
        dataset size and small `leaf_size` may induce excessive memory usage.
        If you are running out of memory consider increasing the `leaf_size`
        parameter. Ignored for `algorithm="brute"`.

    n_jobs : int, default=None
        Number of jobs to run in parallel to calculate distances.
        `None` means 1 unless in a :obj:`joblib.parallel_backend` context.
        `-1` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    cluster_selection_method : {"eom", "leaf"}, default="eom"
        The method used to select clusters from the condensed tree. The
        standard approach for HDBSCAN* is to use an Excess of Mass (`"eom"`)
        algorithm to find the most persistent clusters. Alternatively you can
        instead select the clusters at the leaves of the tree -- this provides
        the most fine grained and homogeneous clusters.

    allow_single_cluster : bool, default=False
        By default HDBSCAN* will not produce a single cluster, setting this
        to True will override this and allow single cluster results in
        the case that you feel this is a valid result for your dataset.

    store_centers : str, default=None
        Which, if any, cluster centers to compute and store. The options are:

        - `None` which does not compute nor store any centers.
        - `"centroid"` which calculates the center by taking the weighted
          average of their positions. Note that the algorithm uses the
          euclidean metric and does not guarantee that the output will be
          an observed data point.
        - `"medoid"` which calculates the center by taking the point in the
          fitted data which minimizes the distance to all other points in
          the cluster. This is slower than "centroid" since it requires
          computing additional pairwise distances between points of the
          same cluster but guarantees the output is an observed data point.
          The medoid is also well-defined for arbitrary metrics, and does not
          depend on a euclidean metric.
        - `"both"` which computes and stores both forms of centers.

    copy : bool, default=False
        If `copy=True` then any time an in-place modifications would be made
        that would overwrite data passed to :term:`fit`, a copy will first be
        made, guaranteeing that the original data will be unchanged.
        Currently, it only applies when `metric="precomputed"`, when passing
        a dense array or a CSR sparse matrix and when `algorithm="brute"`.

    Attributes
    ----------
    labels_ : ndarray of shape (n_samples,)
        Cluster labels for each point in the dataset given to :term:`fit`.
        Outliers are labeled as follows:

        - Noisy samples are given the label -1.
        - Samples with infinite elements (+/- np.inf) are given the label -2.
        - Samples with missing data are given the label -3, even if they
          also have infinite elements.

    probabilities_ : ndarray of shape (n_samples,)
        The strength with which each sample is a member of its assigned
        cluster.

        - Clustered samples have probabilities proportional to the degree that
          they persist as part of the cluster.
        - Noisy samples have probability zero.
        - Samples with infinite elements (+/- np.inf) have probability 0.
        - Samples with missing data have probability `np.nan`.

    n_features_in_ : int
        Number of features seen during :term:`fit`.

    feature_names_in_ : ndarray of shape (`n_features_in_`,)
        Names of features seen during :term:`fit`. Defined only when `X`
        has feature names that are all strings.

    centroids_ : ndarray of shape (n_clusters, n_features)
        A collection containing the centroid of each cluster calculated under
        the standard euclidean metric. The centroids may fall "outside" their
        respective clusters if the clusters themselves are non-convex.

        Note that `n_clusters` only counts non-outlier clusters. That is to
        say, the `-1, -2, -3` labels for the outlier clusters are excluded.

    medoids_ : ndarray of shape (n_clusters, n_features)
        A collection containing the medoid of each cluster calculated under
        the whichever metric was passed to the `metric` parameter. The
        medoids are points in the original cluster which minimize the average
        distance to all other points in that cluster under the chosen metric.
        These can be thought of as the result of projecting the `metric`-based
        centroid back onto the cluster.

        Note that `n_clusters` only counts non-outlier clusters. That is to
        say, the `-1, -2, -3` labels for the outlier clusters are excluded.

    See Also
    --------
    DBSCAN : Density-Based Spatial Clustering of Applications
        with Noise.
    OPTICS : Ordering Points To Identify the Clustering Structure.
    Birch : Memory-efficient, online-learning algorithm.

    Notes
    -----
    The `min_samples` parameter includes the point itself, whereas the implementation in
    `scikit-learn-contrib/hdbscan <https://github.com/scikit-learn-contrib/hdbscan>`_
    does not. To get the same results in both versions, the value of `min_samples` here
    must be 1 greater than the value used in `scikit-learn-contrib/hdbscan
    <https://github.com/scikit-learn-contrib/hdbscan>`_.

    References
    ----------

    .. [1] :doi:`Campello, R. J., Moulavi, D., & Sander, J. Density-based clustering
      based on hierarchical density estimates.
      <10.1007/978-3-642-37456-2_14>`
    .. [2] :doi:`Campello, R. J., Moulavi, D., Zimek, A., & Sander, J.
       Hierarchical density estimates for data clustering, visualization,
       and outlier detection.<10.1145/2733381>`

    .. [3] `Chaudhuri, K., & Dasgupta, S. Rates of convergence for the
       cluster tree.
       <https://papers.nips.cc/paper/2010/hash/
       b534ba68236ba543ae44b22bd110a1d6-Abstract.html>`_

    .. [4] `Moulavi, D., Jaskowiak, P.A., Campello, R.J., Zimek, A. and
       Sander, J. Density-Based Clustering Validation.
       <https://www.dbs.ifi.lmu.de/~zimek/publications/SDM2014/DBCV.pdf>`_

    .. [5] :arxiv:`Malzer, C., & Baum, M. "A Hybrid Approach To Hierarchical
       Density-based Cluster Selection."<1911.02282>`.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.cluster import HDBSCAN
    >>> from sklearn.datasets import load_digits
    >>> X, _ = load_digits(return_X_y=True)
    >>> hdb = HDBSCAN(min_cluster_size=20)
    >>> hdb.fit(X)
    HDBSCAN(min_cluster_size=20)
    >>> hdb.labels_.shape == (X.shape[0],)
    True
    >>> np.unique(hdb.labels_).tolist()
    [-1, 0, 1, 2, 3, 4, 5, 6, 7]
       Nr   )r   r   closedr   r   rQ   neither>   autobrutekd_tree	ball_treeeomleafboolean>   bothmedoidcentroid)min_cluster_sizer-   cluster_selection_epsilonmax_cluster_sizerR   r`   r_   rj   rk   rS   cluster_selection_methodallow_single_clusterstore_centersrX   rN   rU   rO   rd   r   re   Fc                     || _         || _        || _        || _        || _        || _        || _        || _        |	| _        |
| _	        || _
        || _        || _        || _        d S N)r   r-   r_   r   r   rR   r`   rj   rk   rS   r   r   r   rX   )selfr   r-   r   r   rR   r`   r_   rj   rk   rS   r   r   r   rX   s                  r.   __init__zHDBSCAN.__init__  sr    " !1&
 0)B&*""(@%$8!*			r0   )prefer_skip_nested_validationc           
      
   | j         dk    r| j        t          d          | j        pi | _        | j         dk    rt          | |ddgdt          j                  }|| _        d}	 t          t          |          r|j        n|           n# t          $ r d}Y nw xY w|s|                    d	
          }t          j        |                                          d         }t          j        |                                          d         }t!          |          }d t#          |          D             }||         }nt          |          r!t          | |ddgt          j        d          }nSt          | |dt          j        d          }t          j        |                                          rt          d          |j        d         d	k    rt          d          | j        | j        n| j        | _        | j        |j        d         k    r&t          d| j         d|j        d          d          d}	t/          d%|| j        | j        | j         | j        d| j        }
| j        dk    r*| j         t6          j        vrt          | j          d          | j        dk    r*| j         t:          j        vrt          | j          d          | j        dk    r| j         dk    r)t          |          r| j        dk    rt          d          | j        dk    rt<          }	| j        |
d<   n| j        dk    rt@          }	d|
d<   | j!        |
d<   nt@          }	d|
d<   | j!        |
d<   not          |          s| j         tD          vrt<          }	| j        |
d<   n@| j         t6          j        v rt@          }	d|
d<   | j!        |
d<   nt@          }	d|
d<   | j!        |
d<    |	d%i |
| _#        tI          | j#        | j        | j%        | j&        | j'        | j(                  \  | _)        | _*        | j         dk    r|stW          | j#        |tY          t          j-        ||g                              | _#        t          j.        | j        j        d         t          j/                   }| j)        ||<   t`          d!         d"         ||<   t`          d#         d"         ||<   || _)        t          j1        | j        j        d         t          j                   }| j*        ||<   t`          d!         d$         ||<   t`          d#         d$         ||<   || _*        | j        r| 2                    |           | S )&a  Find clusters based on hierarchical density-based clustering.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features), or                 ndarray of shape (n_samples, n_samples)
            A feature array, or array of distances between samples if
            `metric='precomputed'`.

        y : None
            Ignored.

        Returns
        -------
        self : object
            Returns self.
        rQ   Nz>Cannot store centers when using a precomputed distance matrix.rV   lilF)accept_sparseensure_all_finiter4   Tr   r   r   c                     i | ]\  }}||	S r)   r)   )r*   xys      r.   
<dictcomp>zHDBSCAN.fit.<locals>.<dictcomp>  s    "L"L"LDAq1a"L"L"Lr0   )r   r4   force_writeable)r   r4   r   z(np.nan values found in precomputed-densez7n_samples=1 while HDBSCAN requires more than one samplezmin_samples (z.) must be at most the number of samples in X ())r^   r-   r_   rR   rS   r   zV is not a valid metric for a KDTree-based algorithm. Please select a different metric.r   zX is not a valid metric for a BallTree-based algorithm. Please select a different metric.r   r   z4Sparse data matrices only support algorithm `brute`.rX   rt   rk   )r   r3   r$   r!   r%   r"   r)   )3rR   r   r8   r`   _metric_paramsr   r<   float64	_raw_datar   r   r?   r   isnanr;   r\   r   r   r6   r5   r-   r   _min_samplesdictr_   rS   rj   r   valid_metricsr   rc   rX   rz   rk   FAST_METRICS_single_linkage_tree_r   r   r   r   r   labels_probabilities_r   sethstackemptyint32r&   r   _weighted_cluster_center)r   r^   r   
all_finite	reduced_Xmissing_indexinfinite_indexfinite_indexr   mst_funckwargs
new_labelsnew_probabilitiess                r.   rp   zHDBSCAN.fit  s   , ;-''D,>,JP   #06B;-''$en"'j  A DNJ#"Xa[[#?166a@@@@ # # #"


#  $ EEqEMM	 !# 3 3 ; ; = =a @ "$)!4!4!<!<!>!>q!A  7q99"L"LIl4K4K"L"L"LlOa[[ 	M$enj $  AA a5
TX  A x{{   M !!KLLL71:??VWWW%)%5%=D!!4CS 	 qwqz))0 1 0 0"#'!*0 0 0  
  
)*;;
 
 !
 
 >Y&&4;f>R+R+R; 5 5 5  
 Nk))dkAW.W.W; 5 5 5  
 >V##},,QKK -Ng-- !WXXX~(()!%v9,,)!*v&*n{##)!,v&*n{##{{ 5dk==)!%v 444)!*v&*n{## *!,v&*n{#%-X%7%7%7%7",:&!)%*!-
 -
)d) ;-''
' *C*ry.-)HIIJJ	* * *D& $."6q"9JJJJ'+|J|$)::)Fw)OJ~&(9)(DW(MJ}%%DL ")=a)@
 S S S.2.Al+ 1B*0Mf0Un-/@/KF/Sm,"3D 	-))!,,,s   &%B BBc                 :    |                      |           | j        S )a  Cluster X and return the associated cluster labels.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features), or                 ndarray of shape (n_samples, n_samples)
            A feature array, or array of distances between samples if
            `metric='precomputed'`.

        y : None
            Ignored.

        Returns
        -------
        y : ndarray of shape (n_samples,)
            Cluster labels.
        )rp   r   )r   r^   r   s      r.   fit_predictzHDBSCAN.fit_predict}  s    $ 	|r0   c                    t          t          | j                  ddhz
            }t          j        |j        d         ft          j                  }| j        dv }| j        dv }|r2t          j        ||j        d         ft          j                  | _	        |r2t          j        ||j        d         ft          j                  | _
        t          |          D ]}| j        |k    }||         }| j        |         }|rt          j        ||d          | j	        |<   |rVt          |fd	| j        i| j        }	|	|z  }	t          j        |	                    d
                    }
||
         | j
        |<   dS )a8  Calculate and store the centroids/medoids of each cluster.

        This requires `X` to be a raw feature array, not precomputed
        distances. Rather than return outputs directly, this helper method
        instead stores them in the `self.{centroids, medoids}_` attributes.
        The choice for which attributes are calculated and stored is mediated
        by the value of `self.store_centers`.

        Parameters
        ----------
        X : ndarray of shape (n_samples, n_features)
            The feature array that the estimator was fit with.

        rn   r    r   r3   )r   r   )r   r   r   )weightsr   rR   r   N)r   r   r   r<   r   r5   bool_r   r   
centroids_medoids_r7   r   averager   rR   r   argminr   )r   r^   
n_clustersmaskmake_centroidsmake_medoidsidxr?   strengthdist_matmedoid_indexs              r.   r   z HDBSCAN._weighted_cluster_center  s     T\**b"X566
xRX666+/CC)-?? 	S h
AGAJ'?rzRRRDO 	QHj!'!*%=RZPPPDM $$ 	8 	8C<3&DT7D*40H R')z$q'Q'Q'Q$ 8- !%040C  $h.!y1)=)=>>%),%7c"r0   c                     t          | j        ||          }| j        t          d         d         k    }| j        t          d         d         k    }t          d         d         ||<   t          d         d         ||<   |S )a  Return clustering given by DBSCAN without border points.

        Return clustering that would be equivalent to running DBSCAN* for a
        particular cut_distance (or epsilon) DBSCAN* can be thought of as
        DBSCAN without the border points.  As such these results may differ
        slightly from `cluster.DBSCAN` due to the difference in implementation
        over the non-core points.

        This can also be thought of as a flat clustering derived from constant
        height cut through the single linkage tree.

        This represents the result of selecting a cut value for robust single linkage
        clustering. The `min_cluster_size` allows the flat clustering to declare noise
        points (and cluster smaller than `min_cluster_size`).

        Parameters
        ----------
        cut_distance : float
            The mutual reachability distance cut value to use to generate a
            flat clustering.

        min_cluster_size : int, default=5
            Clusters smaller than this value with be called 'noise' and remain
            unclustered in the resulting flat clustering.

        Returns
        -------
        labels : ndarray of shape (n_samples,)
            An array of cluster labels, one per datapoint.
            Outliers are labeled as follows:

            - Noisy samples are given the label -1.
            - Samples with infinite elements (+/- np.inf) are given the label -2.
            - Samples with missing data are given the label -3, even if they
              also have infinite elements.
        r$   r!   r%   )r   r   r   r&   )r   cut_distancer   labelsr   r   s         r.   dbscan_clusteringzHDBSCAN.dbscan_clustering  s~    J "&6F
 
 )::)Fw)OO(9)(DW(MM "3:!>w!G~ 1) <W E}r0   c                     t                                                      }d|j        _        | j        dk    |j        _        |S )NTrQ   )super__sklearn_tags__
input_tagssparserR   	allow_nan)r   tags	__class__s     r.   r   zHDBSCAN.__sklearn_tags__  s8    ww''))!%$(K=$@!r0   )rN   NrU   NrO   Nrd   r   re   Nr   FNFr   )rN   )__name__
__module____qualname____doc__r   r   r   r   r   r   r   callabler   _parameter_constraintsr   r   rp   r   r   r   r   __classcell__)r   s   @r.   r   r     s7       V Vr &XhQd6RRRS fMMMtTHTf===&
 HXAT&AAA

 J|cc.&9&99]OKLL
 (4atIFFFG j!J!J!JKKLhxatFKKKLT"%/Z%@%@$A!*

+I+I+I J JK- 6 "%!&"   @ \&+  { { {	 {z   ** * *X/ / / /b        r0   r   )rN   NrO   NF)rN   rd   rO   re   N)9r   numbersr   r   warningsr   numpyr<   scipy.sparser   r   baser	   r
   r   metricsr   metrics._dist_metricsr   metrics.pairwiser   	neighborsr   r   r   utils._param_validationr   r   utils.validationr   r   r   _linkager   r   r   r   _reachabilityr   _treer   r   r   r   r   r   nanr&   r   __annotations__rG   rM   rc   rz   r   r   r   r)   r0   r.   <module>r     s    R # " " " " " " "           * * * * * * * * = = = = = = = = = = ) ) ) ) ) ) 3 3 3 3 3 3 . . . . . . ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;         
            5 4 4 4 4 4 D D D D D D D D D Ds6'(*@@AA     	   4   ": : :z2 2 22 
	l+ l+ l+ l+d 
O+ O+ O+ O+d* * *Z  I	 I	 I	 I	 I	lM I	 I	 I	 I	 I	r0   