
    -i;                        % S r SSKJrJr  SSKJr  SSKrSSKJ	r	J
r
  SSKJrJrJr  SSKJr  SS	KJr  SS
KJr  SSKJrJrJr  SSKJrJr  SSKJrJrJr  SSK J!r!J"r"J#r#J$r$  SSK%J&r&  SSK'J(r(J)r)J*r*  \+" \RX                  \RX                  -   5      r-SSS.S\R\                  S.S.r/\0\1S'   S r2S r3     SS jr4     S S jr5S r6S r7 " S S\\5      r8g)!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                   ^^ [        U 5      (       d  [        U 5      $ U R                  mU R                  S   n[	        UU4S j[        U5       5       5      (       a  [        ST ST S35      e[        R                  " U SSS9nUS:  a  [        S	U S
35      e[        R                  " U 5      nUR                  5       u  pV[        R                  R                  XVUR                  /[        S9nU$ )a  
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   F   >#    U  H  nTUS -      TU   -
  T:  v   M     g7f)r   N ).0iindptrmin_sampless     S/var/www/html/venv/lib/python3.13/site-packages/sklearn/cluster/_hdbscan/hdbscan.py	<genexpr>_brute_mst.<locals>.<genexpr>q   s)     
P>OF1q5MF1I%4>Os   !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 performed 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   S   s   . '((+,?@@ !''F$**1-J

PeJ>O
PPP2;- @(M *&&
 	
 //e5L a4\N CQ Q
 	
  '<<=PQ)113JD
&&

	-223  C J    c                 R    [         R                  " U S   5      nX   n [        U 5      $ )a  
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_mstrN      s-    " 

,Z89I)4011rH   c                 Z   US:X  ax  U R                   S   U R                   S   :w  a  [        SU R                    S35      e[        X R                  5      (       d  [        S5      eU(       a  U R	                  5       OU nO[        U 4X4S.UD6nXr-  nUR                  SS	5      n[        U5      (       a   UR                  S
:w  a  UR                  5       n[        XqUS9n	[        XS9n
[        R                  " U
S   5      R                  5       (       a  [        S[         5        [#        U
5      $ )aL  
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-   rS   )r-   rJ   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   UserWarningrN   )Xr-   alpharQ   rR   rW   metric_paramsdistance_matrixrS   mutual_reachability_rL   s              r.   _hdbscan_bruterb      s=   @ 771:#!!"	 *>> 
 &a--5  '+!&&(,

/<
 O $$^S9L  _%;%;u%D *//1 5| ##7Q	xx!*-.2244
 	
 )**rH   c           
      "   [         R                  " U SS9n [        UUUUUUSS9R                  U 5      nUR	                  XSS9u  p[         R
                  " U	SS2S4   5      n[        R                  " U40 UD6n[        XX5      n[        U5      $ )aR  
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_sizerQ   r_   rR   pT)return_distance)
r<   asarrayr   fit
kneighborsascontiguousarrayr   
get_metricr   rN   )r]   algor-   r^   rQ   rh   rR   r_   nbrsneighbors_distances_core_distancesdist_metricrL   s                 r.   _hdbscan_primsrw     s    x 	

1C A #
 
c!f 	 "__QT_R))*=ae*DEN ++FDmDK -QS)**rH   c                 V   [        U5      n[        U5      n[        U 5       HD  u  pVX   S   nX   S   nXs:  a
  X   X   S'   O	Xt-   X   S'   X:  a  X   X   S'   M;  X-   X   S'   MF     [        R                  " [        U5      [        S9n	[        X R                  S   S-
     S   X R                  S   S-
     S   5      n
X R                  S   S-
     S   n[        U5       H*  u  p\XS-   [        R                  US-   4X'   U
S-  n
US-  nM,     [        R                  " X	/5      n U $ )aE  
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+   rt   leftrightoutlier_treelast_cluster_idlast_cluster_sizeoutliers                r.   remap_single_linkage_treer   h  sO     'L
OM$w{#%#2#8DGK #'#7DGK $3$:DGL!$)$9DGL!   88C
O?CLZZ]Q,d::a=13D.El.SO ZZ]Q./?
+
"a$7ARUVAVW1Q , >>4./DKrH   c                    [        U 5      (       a  [        R                  " [        U R	                  5       R
                  5       VVs/ s H8  u  p[        R                  " [        R                  " U5      5      (       d  M6  UPM:     snn5      nU$ [        R                  " U R                  SS95      R                  5       u  nU$ s  snnf )zS
Returns the indices of the purely finite rows of a
sparse matrix or dense ndarray
r   axis)
r   r<   arrayr}   tolilr?   allisfinitesumr;   )matrixr+   rowrow_indicess       r.   _get_finite_row_indicesr     s    
 hh&v||~':':;X;61rvvbkkRUFV?WQ;X

  VZZQZ%78@@B	 Ys   5C
 C
c                   |  ^  \ rS rSrSr\" \SSSS9/\" \SSSS9S/\" \SSSS9/S\" \SSSS9/\" \	\
" \5      -  S	1-  5      \/\S/\" \SSS
S9/\" 1 Sk5      /\" \SSSS9/\S/\" SS15      /S/S\" 1 Sk5      /S/S.r              SS jr\" SS9SS j5       rSS jrS rSS jrU 4S jrSrU =r$ )HDBSCANi  aV#  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>`.

.. 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   rP   neither>   autobrutekd_tree	ball_treeeomleafboolean>   bothmedoidcentroid)min_cluster_sizer-   cluster_selection_epsilonmax_cluster_sizerQ   r_   r^   rg   rh   rR   cluster_selection_methodallow_single_clusterstore_centersrW   Fc                     Xl         X l        Xpl        X@l        X0l        XPl        X`l        Xl        Xl        Xl	        Xl
        Xl        Xl        Xl        g N)r   r-   r^   r   r   rQ   r_   rg   rh   rR   r   r   r   rW   )selfr   r-   r   r   rQ   r_   r^   rg   rh   rR   r   r   r   rW   s                  r.   __init__HDBSCAN.__init__  sR    " !1&
 0)B&*""(@%$8!*	rH   )prefer_skip_nested_validationc           
      8   U R                   S:X  a  U R                  b  [        S5      eU R                  =(       d    0 U l        U R                   S:w  a  [        U USS/S[        R                  S9nXl        Sn [        [        U5      (       a  UR                  OU5        U(       d  UR                  S	S
9n[        R                  " U5      R                  5       S   n[        R                  " U5      R                  5       S   n[!        U5      n[#        U5       VVs0 s H  u  pX_M	     n	nnX   nO|[        U5      (       a  [        U USS/[        R                  SS9nON[        XS[        R                  SS9n[        R                  " U5      R%                  5       (       a  [        S5      eUR&                  S   S	:X  a  [        S5      eU R(                  c  U R*                  OU R(                  U l        U R,                  UR&                  S   :  a)  [        SU R,                   SUR&                  S    S35      eSn
[/        S$UU R,                  U R0                  U R                   U R2                  S.U R                  D6nU R4                  S:X  a6  U R                   [6        R8                  ;  a  [        U R                    S35      eU R4                  S:X  a6  U R                   [:        R8                  ;  a  [        U R                    S35      eU R4                  S:w  a  U R                   S:w  a+  [        U5      (       a  U R4                  S:w  a  [        S5      eU R4                  S:X  a  [<        n
U R>                  US'   OU R4                  S:X  a  [@        n
SUS'   U RB                  US'   O[@        n
SUS'   U RB                  US'   O[        U5      (       d  U R                   [D        ;  a  [<        n
U R>                  US'   OSU R                   [6        R8                  ;   a  [@        n
SUS'   U RB                  US'   O[@        n
SUS'   U RB                  US'   U
" S$0 UD6U l#        [I        U RF                  U R*                  U RJ                  U RL                  U RN                  U RP                  5      u  U l)        U l*        U R                   S:w  Ga  W(       Gd  [W        U RF                  W	[Y        [        RZ                  " WW/5      5      S9U l#        [        R\                  " U R                  R&                  S   [        R^                  S9nU RR                  UW'   [`        S    S!   X'   [`        S"   S!   X'   Xl)        [        Rb                  " U R                  R&                  S   [        R                  S9nU RT                  X'   [`        S    S#   X'   [`        S"   S#   X'   Xl*        U R                  (       a  U Re                  U5        U $ ! [         a    Sn GNrf = fs  snnf )%at  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.
rP   Nz>Cannot store centers when using a precomputed distance matrix.rU   lilF)accept_sparseensure_all_finiter4   Tr   r   r   )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^   rQ   rR   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`.rW   rq   rh   )r   r3   r$   r!   r%   r"   r)   )3rQ   r   r8   r_   _metric_paramsr   r<   float64	_raw_datar   r   r?   r   isnanr;   r[   r   r}   r6   r5   r-   r   _min_samplesdictr^   rR   rg   r   valid_metricsr   rb   rW   rw   rh   FAST_METRICS_single_linkage_tree_r   r   r   r   r   labels_probabilities_r   sethstackemptyint32r&   r~   _weighted_cluster_center)r   r]   y
all_finite	reduced_Xmissing_indexinfinite_indexfinite_indexxr   mst_funckwargs
new_labelsnew_probabilitiess                 r.   rm   HDBSCAN.fit  ss   , ;;-'D,>,>,JP  #006B;;-'$en"'jjA NJ#"Xa[[166a@  EEqEM	 !# 3 ; ; =a @ "$)!4!<!<!>q!A  7q94=l4K"L4KDA144K"LOa[[$enjj $A 5

TXA xx{   !!KLL771:?VWW%)%5%5%=D!!4CSCS 	 qwwqz) 1 12 3""#''!*Q0 
  
))**;;;;
 !!
 >>Y&4;;f>R>R+R;;-  5 5 
 NNk)dkkAWAW.W;;-  5 5 
 >>V#},QKKNNg- !WXX~~()!%v9,)!*v&*nn{#)!,v&*nn{#{{dkk=)!%v 4 44)!*v&*nn{# *!,v&*nn{#%-%7%7",:&&!!))%%**!!-
)d) ;;-'
 *C**ryy.-)HIJ	*D& $.."6"6q"9JJ'+||J|$)::)Fw)OJ&(9)(DW(MJ%%L ")=)=a)@

 S.2.A.A+ 1B*0Mf0U-/@/KF/S,"3))!,m  #"
#* #Ms   9'X XXXc                 <    U R                  U5        U R                  $ )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.
)rm   r   )r   r]   r   s      r.   fit_predictHDBSCAN.fit_predictr  s    $ 	||rH   c                 \   [        [        U R                  5      SS1-
  5      n[        R                  " UR
                  S   4[        R                  S9nU R                  S;   nU R                  S;   nU(       a6  [        R                  " X!R
                  S   4[        R                  S9U l	        U(       a6  [        R                  " X!R
                  S   4[        R                  S9U l
        [        U5       H  nU R                  U:H  nX   nU R                  U   nU(       a"  [        R                  " XxSS9U R                  U'   U(       d  MW  [        U4S	U R                  0U R                   D6n	X-  n	[        R"                  " U	R%                  SS
95      n
Xz   U R                  U'   M     g)a  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.

rk   r    r   r3   )r   r   )r   r   r   )weightsr   rQ   r   N)r|   r   r   r<   r   r5   bool_r   r   
centroids_medoids_r7   r   averager   rQ   r   argminr   )r   r]   
n_clustersmaskmake_centroidsmake_medoidsidxr?   strengthdist_matmedoid_indexs              r.   r    HDBSCAN._weighted_cluster_center  s_     T\\*b"X56
xxRXX6++/CC))-?? hh
GGAJ'?rzzRDOHHj''!*%=RZZPDM $C<<3&D7D**40H')zz$q'Q$|-!%040C0C $.!yy1)=>%)%7c" % 	rH   c                     [        U R                  X5      nU R                  [        S   S   :H  nU R                  [        S   S   :H  n[        S   S   X4'   [        S   S   X5'   U$ )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_clusteringHDBSCAN.dbscan_clustering  sy    J "&&
 )::)Fw)OO(9)(DW(MM "3:!>w!G 1) <W ErH   c                    > [         TU ]  5       nSUR                  l        U R                  S:g  UR                  l        U$ )NTrP   )super__sklearn_tags__
input_tagssparserQ   	allow_nan)r   tags	__class__s     r.   r   HDBSCAN.__sklearn_tags__  s6    w')!%$(KK=$@!rH   )r   r   r   r   rg   r   r^   r   r   r   rW   r   rh   r   r   rQ   r_   r   r-   rR   r   r   )   NrT   N	euclideanN      ?r   (   Nr   FNFr   )r   )__name__
__module____qualname____firstlineno____doc__r   r   r   r   r   r   r   callabler   _parameter_constraintsr   r   rm   r   r   r   r   __static_attributes____classcell__)r   s   @r.   r   r     sX   Rj &hQd6RS fMtTTf=&
 XAT&A

 |c.&99]OKL
 4atIFG !JKLxatFKLT"%/%@$A!*
+I JK-6 "%!&"@ &+{	{z**X/b rH   r   )r   Nr   NF)r   r   r   r   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   rN   rb   rw   r   r   r   r)   rH   r.   <module>r     s   D #   * = = ) 3 . ; ; ; 
  5 D D6''(*@*@@A    	 4 ":z22 
	l+d 
O+d*ZE	lM E	rH   