
    -iaH                         S r SSKrSSKJrJr  SSKrSSK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JrJr  SS
KJrJr  SSKJr  \" SS/SS/S.SS9 SSSSSSSSSS.S jj5       r " S S\\
5      rg)zE
DBSCAN: Density-Based Spatial Clustering of Applications with Noise
    N)IntegralReal)sparse   )BaseEstimatorClusterMixin_fit_context)_VALID_METRICS)NearestNeighbors)Interval
StrOptionsvalidate_params)_check_sample_weightvalidate_data   )dbscan_innerz
array-likezsparse matrix)Xsample_weightFprefer_skip_nested_validation   	minkowskiauto   )min_samplesmetricmetric_params	algorithm	leaf_sizepr   n_jobsc                p    [        UUUUUUUU	S9n
U
R                  XS9  U
R                  U
R                  4$ )aS  Perform DBSCAN clustering from vector array or distance matrix.

Read more in the :ref:`User Guide <dbscan>`.

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

eps : float, default=0.5
    The maximum distance between two samples for one to be considered
    as in the neighborhood of the other. This is not a maximum bound
    on the distances of points within a cluster. This is the most
    important DBSCAN parameter to choose appropriately for your data set
    and distance function.

min_samples : int, default=5
    The number of samples (or total weight) in a neighborhood for a point
    to be considered as a core point. This includes the point itself.

metric : str or callable, default='minkowski'
    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 during fit.
    X may be a :term:`sparse graph <sparse graph>`,
    in which case only "nonzero" elements may be considered neighbors.

metric_params : dict, default=None
    Additional keyword arguments for the metric function.

    .. versionadded:: 0.19

algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
    The algorithm to be used by the NearestNeighbors module
    to compute pointwise distances and find nearest neighbors.
    See NearestNeighbors module documentation for details.

leaf_size : int, default=30
    Leaf size passed to BallTree or cKDTree. This can affect the speed
    of the construction and query, as well as the memory required
    to store the tree. The optimal value depends
    on the nature of the problem.

p : float, default=2
    The power of the Minkowski metric to be used to calculate distance
    between points.

sample_weight : array-like of shape (n_samples,), default=None
    Weight of each sample, such that a sample with a weight of at least
    ``min_samples`` is by itself a core sample; a sample with negative
    weight may inhibit its eps-neighbor from being core.
    Note that weights are absolute, and default to 1.

n_jobs : int, default=None
    The number of parallel jobs to run for neighbors search. ``None`` means
    1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means
    using all processors. See :term:`Glossary <n_jobs>` for more details.
    If precomputed distance are used, parallel execution is not available
    and thus n_jobs will have no effect.

Returns
-------
core_samples : ndarray of shape (n_core_samples,)
    Indices of core samples.

labels : ndarray of shape (n_samples,)
    Cluster labels for each point.  Noisy samples are given the label -1.

See Also
--------
DBSCAN : An estimator interface for this clustering algorithm.
OPTICS : A similar estimator interface clustering at multiple values of
    eps. Our implementation is optimized for memory usage.

Notes
-----
For an example, see :ref:`sphx_glr_auto_examples_cluster_plot_dbscan.py`.

This implementation bulk-computes all neighborhood queries, which increases
the memory complexity to O(n.d) where d is the average number of neighbors,
while original DBSCAN had memory complexity O(n). It may attract a higher
memory complexity when querying these nearest neighborhoods, depending
on the ``algorithm``.

One way to avoid the query complexity is to pre-compute sparse
neighborhoods in chunks using
:func:`NearestNeighbors.radius_neighbors_graph
<sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with
``mode='distance'``, then using ``metric='precomputed'`` here.

Another way to reduce memory and computation time is to remove
(near-)duplicate points and use ``sample_weight`` instead.

:class:`~sklearn.cluster.OPTICS` provides a similar clustering with lower
memory usage.

References
----------
Ester, M., H. P. Kriegel, J. Sander, and X. Xu, `"A Density-Based
Algorithm for Discovering Clusters in Large Spatial Databases with Noise"
<https://www.dbs.ifi.lmu.de/Publikationen/Papers/KDD-96.final.frame.pdf>`_.
In: Proceedings of the 2nd International Conference on Knowledge Discovery
and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996

Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017).
:doi:`"DBSCAN revisited, revisited: why and how you should (still) use DBSCAN."
<10.1145/3068335>`
ACM Transactions on Database Systems (TODS), 42(3), 19.

Examples
--------
>>> from sklearn.cluster import dbscan
>>> X = [[1, 2], [2, 2], [2, 3], [8, 7], [8, 8], [25, 80]]
>>> core_samples, labels = dbscan(X, eps=3, min_samples=2)
>>> core_samples
array([0, 1, 2, 3, 4])
>>> labels
array([ 0,  0,  0,  1,  1, -1])
epsr   r   r   r   r   r    r!   r   )DBSCANfitcore_sample_indices_labels_)r   r$   r   r   r   r   r   r    r   r!   ests              J/var/www/html/venv/lib/python3.13/site-packages/sklearn/cluster/_dbscan.pydbscanr,      sL    b #
	C GGAG+##S[[00    c                     ^  \ rS rSr% Sr\" \SSSS9/\" \SSSS9/\" \	" \
5      S	1-  5      \/\S/\" 1 S
k5      /\" \SSSS9/\" \SSSS9S/\S/S.r\\S'    SSSSSSSSS.S jjr\" SS9SS j5       rSS jrU 4S jrSrU =r$ )r&      a  Perform DBSCAN clustering from vector array or distance matrix.

DBSCAN - Density-Based Spatial Clustering of Applications with Noise.
Finds core samples of high density and expands clusters from them.
Good for data which contains clusters of similar density.

This implementation has a worst case memory complexity of :math:`O({n}^2)`,
which can occur when the `eps` param is large and `min_samples` is low,
while the original DBSCAN only uses linear memory.
For further details, see the Notes below.

Read more in the :ref:`User Guide <dbscan>`.

Parameters
----------
eps : float, default=0.5
    The maximum distance between two samples for one to be considered
    as in the neighborhood of the other. This is not a maximum bound
    on the distances of points within a cluster. This is the most
    important DBSCAN parameter to choose appropriately for your data set
    and distance function.

min_samples : int, default=5
    The number of samples (or total weight) in a neighborhood for a point to
    be considered as a core point. This includes the point itself. If
    `min_samples` is set to a higher value, DBSCAN will find denser clusters,
    whereas if it is set to a lower value, the found clusters will be more
    sparse.

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. X may be a :term:`sparse graph`, in which
    case only "nonzero" elements may be considered neighbors for DBSCAN.

    .. versionadded:: 0.17
       metric *precomputed* to accept precomputed sparse matrix.

metric_params : dict, default=None
    Additional keyword arguments for the metric function.

    .. versionadded:: 0.19

algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
    The algorithm to be used by the NearestNeighbors module
    to compute pointwise distances and find nearest neighbors.
    See NearestNeighbors module documentation for details.

leaf_size : int, default=30
    Leaf size passed to BallTree or cKDTree. This can affect the speed
    of the construction and query, as well as the memory required
    to store the tree. The optimal value depends
    on the nature of the problem.

p : float, default=None
    The power of the Minkowski metric to be used to calculate distance
    between points. If None, then ``p=2`` (equivalent to the Euclidean
    distance).

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

Attributes
----------
core_sample_indices_ : ndarray of shape (n_core_samples,)
    Indices of core samples.

components_ : ndarray of shape (n_core_samples, n_features)
    Copy of each core sample found by training.

labels_ : ndarray of shape (n_samples)
    Cluster labels for each point in the dataset given to fit().
    Noisy samples are given the label -1.

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

    .. versionadded:: 0.24

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.

    .. versionadded:: 1.0

See Also
--------
OPTICS : A similar clustering at multiple values of eps. Our implementation
    is optimized for memory usage.

Notes
-----
This implementation bulk-computes all neighborhood queries, which increases
the memory complexity to O(n.d) where d is the average number of neighbors,
while original DBSCAN had memory complexity O(n). It may attract a higher
memory complexity when querying these nearest neighborhoods, depending
on the ``algorithm``.

One way to avoid the query complexity is to pre-compute sparse
neighborhoods in chunks using
:func:`NearestNeighbors.radius_neighbors_graph
<sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with
``mode='distance'``, then using ``metric='precomputed'`` here.

Another way to reduce memory and computation time is to remove
(near-)duplicate points and use ``sample_weight`` instead.

:class:`~sklearn.cluster.OPTICS` provides a similar clustering with lower memory
usage.

References
----------
Ester, M., H. P. Kriegel, J. Sander, and X. Xu, `"A Density-Based
Algorithm for Discovering Clusters in Large Spatial Databases with Noise"
<https://www.dbs.ifi.lmu.de/Publikationen/Papers/KDD-96.final.frame.pdf>`_.
In: Proceedings of the 2nd International Conference on Knowledge Discovery
and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996

Schubert, E., Sander, J., Ester, M., Kriegel, H. P., & Xu, X. (2017).
:doi:`"DBSCAN revisited, revisited: why and how you should (still) use DBSCAN."
<10.1145/3068335>`
ACM Transactions on Database Systems (TODS), 42(3), 19.

Examples
--------
>>> from sklearn.cluster import DBSCAN
>>> import numpy as np
>>> X = np.array([[1, 2], [2, 2], [2, 3],
...               [8, 7], [8, 8], [25, 80]])
>>> clustering = DBSCAN(eps=3, min_samples=2).fit(X)
>>> clustering.labels_
array([ 0,  0,  0,  1,  1, -1])
>>> clustering
DBSCAN(eps=3, min_samples=2)

For an example, see
:ref:`sphx_glr_auto_examples_cluster_plot_dbscan.py`.

For a comparison of DBSCAN with other clustering algorithms, see
:ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py`
g        Nneither)closedr   leftprecomputed>   r   brutekd_tree	ball_treer#   _parameter_constraintsr   	euclideanr   r   )r   r   r   r   r   r    r!   c                d    Xl         X l        X0l        X@l        XPl        X`l        Xpl        Xl        g )Nr#   )	selfr$   r   r   r   r   r   r    r!   s	            r+   __init__DBSCAN.__init__X  s.     &*""r-   Fr   c           
      d   [        XSS9nUb  [        X15      nU R                  S:X  a  [        R                  " U5      (       ar  UR                  5       n[        R                  " 5          [        R                  " S[        R                  5        UR                  UR                  5       5        SSS5        [        U R                  U R                  U R                  U R                  U R                   U R"                  U R$                  S9nUR'                  U5        UR)                  USS9nUc1  [*        R,                  " U Vs/ s H  n[/        U5      PM     sn5      nO=[*        R,                  " U Vs/ s H  n[*        R0                  " X6   5      PM     sn5      n[*        R2                  " UR4                  S	   S
[*        R6                  S9n[*        R8                  " XpR:                  :  [*        R<                  S9n	[?        XU5        [*        R@                  " U	5      S	   U l!        Xl"        [/        U RB                  5      (       a#  XRB                     R                  5       U l#        U $ [*        RH                  " S	UR4                  S   45      U l#        U $ ! , (       d  f       GN= fs  snf s  snf )aG  Perform DBSCAN clustering from features, or distance matrix.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), or             (n_samples, n_samples)
    Training instances to cluster, or distances between instances if
    ``metric='precomputed'``. If a sparse matrix is provided, it will
    be converted into a sparse ``csr_matrix``.

y : Ignored
    Not used, present here for API consistency by convention.

sample_weight : array-like of shape (n_samples,), default=None
    Weight of each sample, such that a sample with a weight of at least
    ``min_samples`` is by itself a core sample; a sample with a
    negative weight may inhibit its eps-neighbor from being core.
    Note that weights are absolute, and default to 1.

Returns
-------
self : object
    Returns a fitted instance of self.
csr)accept_sparseNr3   ignore)radiusr   r   r   r   r    r!   F)return_distancer   )dtyper   )%r   r   r   r   issparsecopywarningscatch_warningssimplefilterSparseEfficiencyWarningsetdiagdiagonalr   r$   r   r   r   r    r!   r'   radius_neighborsnparraylensumfullshapeintpasarrayr   uint8r   wherer(   r)   components_empty)
r:   r   yr   neighbors_modelneighborhoods	neighborsn_neighborslabelscore_sampless
             r+   r'   
DBSCAN.fitm  s   : $7$0BM
 ;;-'FOOA,>,> A((*%%h0N0NO		!**,' + +88nnnn;;,,ff;;
 	A'88E8R ((M#RMyC	NM#RSK((CPQ=i01=QK
 Rrww7 zz+1A1A"AR\&9$&HH\$:1$=!t(()) !:!:;@@BD   "xxAGGAJ8DQ +*$ $S Rs   )AJJ(4"J-
J%c                 8    U R                  XS9  U R                  $ )az  Compute clusters from a data or distance matrix and predict labels.

Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features), or             (n_samples, n_samples)
    Training instances to cluster, or distances between instances if
    ``metric='precomputed'``. If a sparse matrix is provided, it will
    be converted into a sparse ``csr_matrix``.

y : Ignored
    Not used, present here for API consistency by convention.

sample_weight : array-like of shape (n_samples,), default=None
    Weight of each sample, such that a sample with a weight of at least
    ``min_samples`` is by itself a core sample; a sample with a
    negative weight may inhibit its eps-neighbor from being core.
    Note that weights are absolute, and default to 1.

Returns
-------
labels : ndarray of shape (n_samples,)
    Cluster labels. Noisy samples are given the label -1.
r%   )r'   r)   )r:   r   rZ   r   s       r+   fit_predictDBSCAN.fit_predict  s    2 	0||r-   c                    > [         TU ]  5       nU R                  S:H  UR                  l        SUR                  l        U$ )Nr3   T)super__sklearn_tags__r   
input_tagspairwiser   )r:   tags	__class__s     r+   rg   DBSCAN.__sklearn_tags__  s6    w')#';;-#? !%r-   )r   rX   r(   r$   r)   r   r   r   r   r!   r    g      ?)NN)__name__
__module____qualname____firstlineno____doc__r   r   r   r   setr
   callabledictr7   __annotations__r;   r	   r'   rc   rg   __static_attributes____classcell__)rk   s   @r+   r&   r&      s    Rj sD;< 1d6BCs>*m_<=
  !JKLxD@AtS$v6=T"$D    
* &+M	M^8 r-   r&   rm   )rr   rG   numbersr   r   numpyrN   scipyr   baser   r   r	   metrics.pairwiser
   r]   r   utils._param_validationr   r   r   utils.validationr   r   _dbscan_innerr   r,   r&    r-   r+   <module>r      s     "   < < - ( K K B ' O,&- #( 	U1 U1U1pk\= kr-   