
    0Phe                        d Z ddlZddlmZ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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mZm Z  ddl!m"Z"m#Z#  G d dee          Z$d Z%d Z& e ej'        dg eeddd           eeddd          g eeddd          g e e(e          dhz            e)g eeddd          dge*dg eh d          g eeddd          gedgd	d          d             Z+d Z, e ej'        gej'        gej'        g eeddd          gd d!          d"             Z- e ej'        gej'        gej'        g eeddd           eeddd          g eeddd           eeddd          dg eeddd          gd#gd$d!          dd%d!d&d'            Z.d( Z/d) Z0d* Z1d+ Z2d, Z3dS )-a}  Ordering Points To Identify the Clustering Structure (OPTICS)

These routines execute the OPTICS algorithm, and implement various
cluster extraction methods of the ordered list.

Authors: Shane Grigsby <refuge@rocktalus.com>
         Adrin Jalali <adrinjalali@gmail.com>
         Erich Schubert <erich@debian.org>
         Hanmin Qin <qinhanmin2005@sina.com>
License: BSD 3 clause
    N)IntegralReal)SparseEfficiencyWarningissparse   )BaseEstimatorClusterMixin_fit_context)DataConversionWarning)pairwise_distances)_VALID_METRICSPAIRWISE_BOOLEAN_FUNCTIONS)NearestNeighbors)gen_batches)get_chunk_n_rows)
HasMethodsInterval
RealNotInt
StrOptionsvalidate_params)check_memoryvalidate_datac                      e Zd ZU dZ eeddd           eeddd          g eeddd          g e e	e
          d	hz            eg eeddd          gedg ed
dh          g eeddd          dg eeddd          gdg eeddd           eeddd          dg eh d          g eeddd          ge ed          dgedgdZeed<   dej        ddddddddddddddZ ed          dd            ZdS )OPTICSu $  Estimate clustering structure from vector array.

    OPTICS (Ordering Points To Identify the Clustering Structure), closely
    related to DBSCAN, finds core sample of high density and expands clusters
    from them [1]_. Unlike DBSCAN, keeps cluster hierarchy for a variable
    neighborhood radius. Better suited for usage on large datasets than the
    current sklearn implementation of DBSCAN.

    Clusters are then extracted using a DBSCAN-like method
    (cluster_method = 'dbscan') or an automatic
    technique proposed in [1]_ (cluster_method = 'xi').

    This implementation deviates from the original OPTICS by first performing
    k-nearest-neighborhood searches on all points to identify core sizes, then
    computing only the distances to unprocessed points when constructing the
    cluster order. Note that we do not employ a heap to manage the expansion
    candidates, so the time complexity will be O(n^2).

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

    Parameters
    ----------
    min_samples : int > 1 or float between 0 and 1, default=5
        The number of samples in a neighborhood for a point to be considered as
        a core point. Also, up and down steep regions can't have more than
        ``min_samples`` consecutive non-steep points. Expressed as an absolute
        number or a fraction of the number of samples (rounded to be at least
        2).

    max_eps : float, default=np.inf
        The maximum distance between two samples for one to be considered as
        in the neighborhood of the other. Default value of ``np.inf`` will
        identify clusters across all scales; reducing ``max_eps`` will result
        in shorter run times.

    metric : str or callable, default='minkowski'
        Metric to use for distance computation. Any metric from scikit-learn
        or scipy.spatial.distance can be used.

        If metric is a callable function, it is called on each
        pair of instances (rows) and the resulting value recorded. The callable
        should take two arrays as input and return one value indicating the
        distance between them. This works for Scipy's metrics, but is less
        efficient than passing the metric name as a string. If metric is
        "precomputed", `X` is assumed to be a distance matrix and must be
        square.

        Valid values for metric are:

        - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
          'manhattan']

        - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
          'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
          'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao',
          'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
          'yule']

        Sparse matrices are only supported by scikit-learn metrics.
        See the documentation for scipy.spatial.distance for details on these
        metrics.

        .. note::
           `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11.

    p : float, default=2
        Parameter for the Minkowski metric from
        :class:`~sklearn.metrics.pairwise_distances`. When p = 1, this is
        equivalent to using manhattan_distance (l1), and euclidean_distance
        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.

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

    cluster_method : str, default='xi'
        The extraction method used to extract clusters using the calculated
        reachability and ordering. Possible values are "xi" and "dbscan".

    eps : float, default=None
        The maximum distance between two samples for one to be considered as
        in the neighborhood of the other. By default it assumes the same value
        as ``max_eps``.
        Used only when ``cluster_method='dbscan'``.

    xi : float between 0 and 1, default=0.05
        Determines the minimum steepness on the reachability plot that
        constitutes a cluster boundary. For example, an upwards point in the
        reachability plot is defined by the ratio from one point to its
        successor being at most 1-xi.
        Used only when ``cluster_method='xi'``.

    predecessor_correction : bool, default=True
        Correct clusters according to the predecessors calculated by OPTICS
        [2]_. This parameter has minimal effect on most datasets.
        Used only when ``cluster_method='xi'``.

    min_cluster_size : int > 1 or float between 0 and 1, default=None
        Minimum number of samples in an OPTICS cluster, expressed as an
        absolute number or a fraction of the number of samples (rounded to be
        at least 2). If ``None``, the value of ``min_samples`` is used instead.
        Used only when ``cluster_method='xi'``.

    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
        Algorithm used to compute the nearest neighbors:

        - 'ball_tree' will use :class:`~sklearn.neighbors.BallTree`.
        - 'kd_tree' will use :class:`~sklearn.neighbors.KDTree`.
        - 'brute' will use a brute-force search.
        - 'auto' (default) will attempt to decide the most appropriate
          algorithm based on the values passed to :meth:`fit` method.

        Note: fitting on sparse input will override the setting of
        this parameter, using brute force.

    leaf_size : int, default=30
        Leaf size passed to :class:`~sklearn.neighbors.BallTree` or
        :class:`~sklearn.neighbors.KDTree`. 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.

    memory : str or object with the joblib.Memory interface, default=None
        Used to cache the output of the computation of the tree.
        By default, no caching is done. If a string is given, it is the
        path to the caching directory.

    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.

    Attributes
    ----------
    labels_ : ndarray of shape (n_samples,)
        Cluster labels for each point in the dataset given to fit().
        Noisy samples and points which are not included in a leaf cluster
        of ``cluster_hierarchy_`` are labeled as -1.

    reachability_ : ndarray of shape (n_samples,)
        Reachability distances per sample, indexed by object order. Use
        ``clust.reachability_[clust.ordering_]`` to access in cluster order.

    ordering_ : ndarray of shape (n_samples,)
        The cluster ordered list of sample indices.

    core_distances_ : ndarray of shape (n_samples,)
        Distance at which each sample becomes a core point, indexed by object
        order. Points which will never be core have a distance of inf. Use
        ``clust.core_distances_[clust.ordering_]`` to access in cluster order.

    predecessor_ : ndarray of shape (n_samples,)
        Point that a sample was reached from, indexed by object order.
        Seed points have a predecessor of -1.

    cluster_hierarchy_ : ndarray of shape (n_clusters, 2)
        The list of clusters in the form of ``[start, end]`` in each row, with
        all indices inclusive. The clusters are ordered according to
        ``(end, -start)`` (ascending) so that larger clusters encompassing
        smaller clusters come after those smaller ones. Since ``labels_`` does
        not reflect the hierarchy, usually
        ``len(cluster_hierarchy_) > np.unique(optics.labels_)``. Please also
        note that these indices are of the ``ordering_``, i.e.
        ``X[ordering_][start:end + 1]`` form a cluster.
        Only available when ``cluster_method='xi'``.

    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
    --------
    DBSCAN : A similar clustering for a specified neighborhood radius (eps).
        Our implementation is optimized for runtime.

    References
    ----------
    .. [1] Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel,
       and Jörg Sander. "OPTICS: ordering points to identify the clustering
       structure." ACM SIGMOD Record 28, no. 2 (1999): 49-60.

    .. [2] Schubert, Erich, Michael Gertz.
       "Improving the Cluster Structure Extracted from OPTICS Plots." Proc. of
       the Conference "Lernen, Wissen, Daten, Analysen" (LWDA) (2018): 318-329.

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

    For a more detailed example see
    :ref:`sphx_glr_auto_examples_cluster_plot_optics.py`.
    r   Nleftclosedr      bothprecomputeddbscanxibooleanright>   autobrutekd_tree	ball_treecache)min_samplesmax_epsmetricpmetric_paramscluster_methodepsr"   predecessor_correctionmin_cluster_size	algorithm	leaf_sizememoryn_jobs_parameter_constraints   	minkowski皙?Tr%      c                    || _         || _        |
| _        || _        || _        || _        || _        || _        || _        || _	        || _
        |	| _        || _        || _        d S N)r+   r*   r2   r3   r,   r.   r-   r4   r/   r0   r"   r1   r5   r6   )selfr*   r+   r,   r-   r.   r/   r0   r"   r1   r2   r3   r4   r5   r6   s                  W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/sklearn/cluster/_optics.py__init__zOPTICS.__init__  so    $ & 0"*",&<#    Fprefer_skip_nested_validationc                    | j         t          v rt          nt          }|t          u r5|j        t          k    r%d| j          d}t          j        |t                     t          | ||d          }| j         dk    rt          |          r|
                                }t          j                    5  t          j        dt                     |                    |                                           ddd           n# 1 swxY w Y   t!          | j                  } |                    t&                    || j        | j        | j        | j         | j        | j        | j        | j        	  	        \  | _        | _        | _        | _        | j        d	k    rDtA          | j        | j        | j        | j        | j!        | j"        | j#        
          \  }}|| _$        ni| j        dk    r^| j%        | j        }n| j%        }|| j        k    rtM          d| j        d|d          tO          | j        | j        | j        |          }|| _(        | S )a  Perform OPTICS clustering.

        Extracts an ordered list of points and reachability distances, and
        performs initial clustering using ``max_eps`` distance specified at
        OPTICS object instantiation.

        Parameters
        ----------
        X : {ndarray, sparse matrix} of shape (n_samples, n_features), or                 (n_samples, n_samples) if metric='precomputed'
            A feature array, or array of distances between samples if
            metric='precomputed'. If a sparse matrix is provided, it will be
            converted into CSR format.

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

        Returns
        -------
        self : object
            Returns a fitted instance of self.
        z-Data will be converted to boolean for metric zG, to avoid this warning, you may convert the data prior to calling fit.csr)dtypeaccept_sparser    ignoreN)	Xr*   r3   r4   r,   r.   r-   r6   r+   r"   reachabilitypredecessororderingr*   r2   r"   r1   r!   z Specify an epsilon smaller than z. Got .rK   core_distancesrM   r0   ))r,   r   boolfloatrF   warningswarnr   r   r   copycatch_warningssimplefilterr   setdiagdiagonalr   r5   r)   compute_optics_graphr*   r3   r4   r.   r-   r6   r+   	ordering_core_distances_reachability_predecessor_r/   cluster_optics_xir2   r"   r1   cluster_hierarchy_r0   
ValueErrorcluster_optics_dbscanlabels_)	r>   rI   yrF   msgr5   rc   	clusters_r0   s	            r?   fitz
OPTICS.fit.  s   6 'AAAuD==QW__B;B B B 
 M#4555$eDDD;-''HQKK'A(** ( (%h0GHHH 		!**,,'''	( ( ( ( ( ( ( ( ( ( ( ( ( ( (
 dk** /FLL-..(nn;,f;L

 

 

	
N  $&&!2!/ - ,!%!67'+'B" " "GY '0D## H,,xlhT\!! jEI\\\SVSVSVW   ,!/#3	  G s   /AC==DDr=   )__name__
__module____qualname____doc__r   r   r   r   r   setr   callabledictstrr   r7   __annotations__npinfr@   r
   rg    rA   r?   r   r   '   s'        K K^ HXq$v666HZAf555
 HT1d6:::;:cc.11]OCDDhOhtQV4445%:x&6778q$v666=xa62223#,+HXq$v666HZAg666

 !j!J!J!JKKLhxD@@@A

7++T2T"+$ $D   6 
#!    B \&+  Z Z Z	 Z Z ZrA   r   c                 <    | |k    rt          d||| fz            d S )Nz=%s must be no greater than the number of samples (%d). Got %d)ra   )size	n_samples
param_names      r?   _validate_sizerx     s9    iK9d+,
 
 	
 rA   c                 8   | j         d         }t          j        |          }|                    t          j                   t          d|z  ||          }t          ||          }|D ]1}|                    | |         |          d         dddf         ||<   2|S )a  Compute the k-th nearest neighbor of each sample.

    Equivalent to neighbors.kneighbors(X, self.min_samples)[0][:, -1]
    but with more memory efficiency.

    Parameters
    ----------
    X : array-like of shape (n_samples, n_features)
        The data.
    neighbors : NearestNeighbors instance
        The fitted nearest neighbors estimator.
    working_memory : int, default=None
        The sought maximum memory for temporary distance matrix chunks.
        When None (default), the value of
        ``sklearn.get_config()['working_memory']`` is used.

    Returns
    -------
    core_distances : ndarray of shape (n_samples,)
        Distance at which each sample becomes a core point.
        Points which will never be core have a distance of inf.
    r      )	row_bytes
max_n_rowsworking_memoryN)shaperq   emptyfillnanr   r   
kneighbors)	rI   	neighborsr*   r}   rv   rP   chunk_n_rowsslicessls	            r?   _compute_core_distances_r     s    . 
IXi((N#{"y  L L11F P P&11!B%EEaHBOrrA   zsparse matrixr   r   r   r   r    r$   >   r%   r&   r'   r(   )	rI   r*   r+   r,   r-   r.   r3   r4   r6   FrB   c                   | j         d         }	t          ||	d           |dk    r t          dt          ||	z                      }t	          j        |	          }
|
                    t          j                   t	          j        |	t                    }|                    d           t          |||||||          }|	                    |            t          | ||d	          }t          j        |||k    <   t	          j        |t	          j        |j                  j        |
           t	          j        | j         d         t                     }t	          j        | j         d         t                    }t#          | j         d                   D ]z}t	          j        |dk              d         }|t	          j        |
|                            }d||<   |||<   ||         t          j        k    rt)          ||
|||| |||||           {t	          j        t	          j        |
                    rt/          j        dt2                     |||
|fS )u  Compute the OPTICS reachability graph.

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

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

    min_samples : int > 1 or float between 0 and 1
        The number of samples in a neighborhood for a point to be considered
        as a core point. Expressed as an absolute number or a fraction of the
        number of samples (rounded to be at least 2).

    max_eps : float, default=np.inf
        The maximum distance between two samples for one to be considered as
        in the neighborhood of the other. Default value of ``np.inf`` will
        identify clusters across all scales; reducing ``max_eps`` will result
        in shorter run times.

    metric : str or callable, default='minkowski'
        Metric to use for distance computation. Any metric from scikit-learn
        or scipy.spatial.distance can be used.

        If metric is a callable function, it is called on each
        pair of instances (rows) and the resulting value recorded. The callable
        should take two arrays as input and return one value indicating the
        distance between them. This works for Scipy's metrics, but is less
        efficient than passing the metric name as a string. If metric is
        "precomputed", X is assumed to be a distance matrix and must be square.

        Valid values for metric are:

        - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
          'manhattan']

        - from scipy.spatial.distance: ['braycurtis', 'canberra', 'chebyshev',
          'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski',
          'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao',
          'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean',
          'yule']

        See the documentation for scipy.spatial.distance for details on these
        metrics.

        .. note::
           `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11.

    p : float, default=2
        Parameter for the Minkowski metric from
        :class:`~sklearn.metrics.pairwise_distances`. When p = 1, this is
        equivalent to using manhattan_distance (l1), and euclidean_distance
        (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used.

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

    algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto'
        Algorithm used to compute the nearest neighbors:

        - 'ball_tree' will use :class:`~sklearn.neighbors.BallTree`.
        - 'kd_tree' will use :class:`~sklearn.neighbors.KDTree`.
        - 'brute' will use a brute-force search.
        - 'auto' will attempt to decide the most appropriate algorithm
          based on the values passed to `fit` method. (default)

        Note: fitting on sparse input will override the setting of
        this parameter, using brute force.

    leaf_size : int, default=30
        Leaf size passed to :class:`~sklearn.neighbors.BallTree` or
        :class:`~sklearn.neighbors.KDTree`. 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.

    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.

    Returns
    -------
    ordering_ : array of shape (n_samples,)
        The cluster ordered list of sample indices.

    core_distances_ : array of shape (n_samples,)
        Distance at which each sample becomes a core point, indexed by object
        order. Points which will never be core have a distance of inf. Use
        ``clust.core_distances_[clust.ordering_]`` to access in cluster order.

    reachability_ : array of shape (n_samples,)
        Reachability distances per sample, indexed by object order. Use
        ``clust.reachability_[clust.ordering_]`` to access in cluster order.

    predecessor_ : array of shape (n_samples,)
        Point that a sample was reached from, indexed by object order.
        Seed points have a predecessor of -1.

    References
    ----------
    .. [1] Ankerst, Mihael, Markus M. Breunig, Hans-Peter Kriegel,
       and Jörg Sander. "OPTICS: ordering points to identify the clustering
       structure." ACM SIGMOD Record 28, no. 2 (1999): 49-60.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.cluster import compute_optics_graph
    >>> X = np.array([[1, 2], [2, 5], [3, 6],
    ...               [8, 7], [8, 8], [7, 3]])
    >>> ordering, core_distances, reachability, predecessor = compute_optics_graph(
    ...     X,
    ...     min_samples=2,
    ...     max_eps=np.inf,
    ...     metric="minkowski",
    ...     p=2,
    ...     metric_params=None,
    ...     algorithm="auto",
    ...     leaf_size=30,
    ...     n_jobs=None,
    ... )
    >>> ordering
    array([0, 1, 2, 5, 3, 4])
    >>> core_distances
    array([3.16..., 1.41..., 1.41..., 1.        , 1.        ,
           4.12...])
    >>> reachability
    array([       inf, 3.16..., 1.41..., 4.12..., 1.        ,
           5.        ])
    >>> predecessor
    array([-1,  0,  1,  5,  3,  2])
    r   r*   r   r   rF   r~   )n_neighborsr3   r4   r,   r.   r-   r6   N)rI   r   r*   r}   decimalsoutT)r\   r]   r^   point_index	processedrI   nbrsr,   r.   r-   r+   z^All reachability values are inf. Set a larger max_eps or all data will be considered outliers.)r   rx   maxintrq   r   r   rr   r   rg   r   aroundfinforF   	precisionzerosrQ   rangewhereargmin_set_reach_distallisinfrS   rT   UserWarning)rI   r*   r+   r,   r-   r.   r3   r4   r6   rv   r]   r^   r   r\   r   rM   ordering_idxindexpoints                      r?   rZ   rZ     si   v 
I;	=999a!Sy!899:: HY''Mrv8IS111Lb#
  D 	HHQKKK /
tT  O 24OOg-.I//00:    4000Ix
#...Hagaj))   a((+bie 4556	%!&5!RV++ /+)!#+    
vbh}%%&& 
D 	
 	
 	
 _m\AArA   c                 J   |||dz            }|                     ||
d          d         }t          j        t          j        ||           |          }|j        sd S |dk    rN||g|f         }t          |t          j                  rt          j        |          }|                                }n\|t                      n|
                                }|dk    r	d|vr|	|d<   t          |||         |fdd i|                                }t          j        || |                   }t          j        |t          j        |j                  j        |	           t          j        |t          j        ||          k               }||         |||         <   ||||         <   d S )
Nr   F)radiusreturn_distancer   r    r9   r-   r6   r   )radius_neighborsrq   compresstakeru   
isinstancematrixasarrayravelrn   rU   r   maximumr   r   rF   r   r   )r\   r]   r^   r   r   rI   r   r,   r.   r-   r+   Pindicesunprocdists_paramsrdistsimproveds                     r?   r   r     s    	
+a
'(A ##Agu#MMaPG ["')W555w??F;  ;-'(eRY'' 	&Ju%%E)1$&&&}7I7I7K7K[  S%7%7 GCL"1aiPPPPPVVXXZ{;<<FIfrx55?VLLLLx!?!??@@H&,X&6M&"#%0L!"""rA   rO   Tc                     t          |          }t          j        |t                    }| |k    }||k    }t          j        ||         ||         z            dz
  ||<   d||| z  <   |S )a  Perform DBSCAN extraction for an arbitrary epsilon.

    Extracting the clusters runs in linear time. Note that this results in
    ``labels_`` which are close to a :class:`~sklearn.cluster.DBSCAN` with
    similar settings and ``eps``, only if ``eps`` is close to ``max_eps``.

    Parameters
    ----------
    reachability : ndarray of shape (n_samples,)
        Reachability distances calculated by OPTICS (``reachability_``).

    core_distances : ndarray of shape (n_samples,)
        Distances at which points become core (``core_distances_``).

    ordering : ndarray of shape (n_samples,)
        OPTICS ordered point indices (``ordering_``).

    eps : float
        DBSCAN ``eps`` parameter. Must be set to < ``max_eps``. Results
        will be close to DBSCAN algorithm if ``eps`` and ``max_eps`` are close
        to one another.

    Returns
    -------
    labels_ : array of shape (n_samples,)
        The estimated labels.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.cluster import cluster_optics_dbscan, compute_optics_graph
    >>> X = np.array([[1, 2], [2, 5], [3, 6],
    ...               [8, 7], [8, 8], [7, 3]])
    >>> ordering, core_distances, reachability, predecessor = compute_optics_graph(
    ...     X,
    ...     min_samples=2,
    ...     max_eps=np.inf,
    ...     metric="minkowski",
    ...     p=2,
    ...     metric_params=None,
    ...     algorithm="auto",
    ...     leaf_size=30,
    ...     n_jobs=None,
    ... )
    >>> eps = 4.5
    >>> labels = cluster_optics_dbscan(
    ...     reachability=reachability,
    ...     core_distances=core_distances,
    ...     ordering=ordering,
    ...     eps=eps,
    ... )
    >>> labels
    array([0, 0, 0, 1, 1, 1])
    r   r   r~   )lenrq   r   r   cumsum)rK   rP   rM   r0   rv   labels	far_reach	near_cores           r?   rb   rb     sx    @ N##IXis+++Fs"I#%Iy8!4y7J!JKKaOF8%'F9	z!"MrA   r#   rJ   r:   )r2   r"   r1   c           	      n   t          |           }t          ||d           |dk    r t          dt          ||z                      }||}t          ||d           |dk    r t          dt          ||z                      }t	          | |         ||         |||||          }t          ||          }	|	|fS )a  Automatically extract clusters according to the Xi-steep method.

    Parameters
    ----------
    reachability : ndarray of shape (n_samples,)
        Reachability distances calculated by OPTICS (`reachability_`).

    predecessor : ndarray of shape (n_samples,)
        Predecessors calculated by OPTICS.

    ordering : ndarray of shape (n_samples,)
        OPTICS ordered point indices (`ordering_`).

    min_samples : int > 1 or float between 0 and 1
        The same as the min_samples given to OPTICS. Up and down steep regions
        can't have more then ``min_samples`` consecutive non-steep points.
        Expressed as an absolute number or a fraction of the number of samples
        (rounded to be at least 2).

    min_cluster_size : int > 1 or float between 0 and 1, default=None
        Minimum number of samples in an OPTICS cluster, expressed as an
        absolute number or a fraction of the number of samples (rounded to be
        at least 2). If ``None``, the value of ``min_samples`` is used instead.

    xi : float between 0 and 1, default=0.05
        Determines the minimum steepness on the reachability plot that
        constitutes a cluster boundary. For example, an upwards point in the
        reachability plot is defined by the ratio from one point to its
        successor being at most 1-xi.

    predecessor_correction : bool, default=True
        Correct clusters based on the calculated predecessors.

    Returns
    -------
    labels : ndarray of shape (n_samples,)
        The labels assigned to samples. Points which are not included
        in any cluster are labeled as -1.

    clusters : ndarray of shape (n_clusters, 2)
        The list of clusters in the form of ``[start, end]`` in each row, with
        all indices inclusive. The clusters are ordered according to ``(end,
        -start)`` (ascending) so that larger clusters encompassing smaller
        clusters come after such nested smaller clusters. Since ``labels`` does
        not reflect the hierarchy, usually ``len(clusters) >
        np.unique(labels)``.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.cluster import cluster_optics_xi, compute_optics_graph
    >>> X = np.array([[1, 2], [2, 5], [3, 6],
    ...               [8, 7], [8, 8], [7, 3]])
    >>> ordering, core_distances, reachability, predecessor = compute_optics_graph(
    ...     X,
    ...     min_samples=2,
    ...     max_eps=np.inf,
    ...     metric="minkowski",
    ...     p=2,
    ...     metric_params=None,
    ...     algorithm="auto",
    ...     leaf_size=30,
    ...     n_jobs=None
    ... )
    >>> min_samples = 2
    >>> labels, clusters = cluster_optics_xi(
    ...     reachability=reachability,
    ...     predecessor=predecessor,
    ...     ordering=ordering,
    ...     min_samples=min_samples,
    ... )
    >>> labels
    array([0, 0, 0, 1, 1, 1])
    >>> clusters
    array([[0, 2],
           [3, 5],
           [0, 5]])
    r*   r   r   Nr2   )r   rx   r   r   _xi_cluster_extract_xi_labels)
rK   rL   rM   r*   r2   r"   r1   rv   clustersr   s
             r?   r_   r_     s    V L!!I;	=999a!Sy!899::&#Y0BCCC1q#&6&B"C"CDDXH
 H  (33F8rA   c                     t          |           }d}|}|}||k     r/| |         rd}|}n||         s|dz  }||k    rnn|S |dz  }||k     /|S )aQ  Extend the area until it's maximal.

    It's the same function for both upward and downward reagions, depending on
    the given input parameters. Assuming:

        - steep_{upward/downward}: bool array indicating whether a point is a
          steep {upward/downward};
        - upward/downward: bool array indicating whether a point is
          upward/downward;

    To extend an upward reagion, ``steep_point=steep_upward`` and
    ``xward_point=downward`` are expected, and to extend a downward region,
    ``steep_point=steep_downward`` and ``xward_point=upward``.

    Parameters
    ----------
    steep_point : ndarray of shape (n_samples,), dtype=bool
        True if the point is steep downward (upward).

    xward_point : ndarray of shape (n_samples,), dtype=bool
        True if the point is an upward (respectively downward) point.

    start : int
        The start of the xward region.

    min_samples : int
       The same as the min_samples given to OPTICS. Up and down steep
       regions can't have more then ``min_samples`` consecutive non-steep
       points.

    Returns
    -------
    index : int
        The current index iterating over all the samples, i.e. where we are up
        to in our search.

    end : int
        The end of the region, which can be behind the index. The region
        includes the ``end`` index.
    r   r   )r   )steep_pointxward_pointstartr*   rv   non_xward_pointsr   ends           r?   _extend_regionr     s    R K  IE
C
)

u 	 CCU# 	!  +-- . J
 )

 JrA   c                     t          j                  rg S fd| D             }|D ]}t          |d                   |d<   |S )zUpdate steep down areas (SDAs) using the new maximum in between (mib)
    value, and the given complement of xi, i.e. ``1 - xi``.
    c                 >    g | ]}|d                   z  k    |S )r   rs   ).0sdamibreachability_plotxi_complements     r?   
<listcomp>z'_update_filter_sdas.<locals>.<listcomp>  s9       s&7G&E&UUUUUUrA   r   )rq   r   r   )sdasr   r   r   resr   s    ```  r?   _update_filter_sdasr     s}     
x}} 	       C  * *US))E

JrA   c                     ||k     rN| |         | |         k    r||fS ||         }t          ||          D ]}|||         k    r||fc S |dz  }||k     NdS )aN  Correct for predecessors.

    Applies Algorithm 2 of [1]_.

    Input parameters are ordered by the computer OPTICS ordering.

    .. [1] Schubert, Erich, Michael Gertz.
       "Improving the Cluster Structure Extracted from OPTICS Plots." Proc. of
       the Conference "Lernen, Wissen, Daten, Analysen" (LWDA) (2018): 318-329.
    r   )NN)r   )r   predecessor_plotrM   sep_eis          r?   _correct_predecessorr     s     a%%Q"3A"666a4Kq!q! 	 	Ahqk!!!t "	Q a%% :rA   c           
         t          j        | t           j        f          } d|z
  }g }g }	d}
d}t          j        d          5  | dd         | dd         z  }||k    }|d|z  k    }|dk    }|dk     }ddd           n# 1 swxY w Y   t	          t          j        ||z                      D ]}||
k     r
t          |t          j        | |
|dz                                }||         rOt          ||||           }|}t          ||||          }||dd}|	                    |           |dz   }
| |
         }t          ||||           }|}t          ||||          }|dz   }
| |
         }g }|D ]*}|d	         }|}| |dz            |z  |d
         k     r&| |d	                  }||z  | |dz            k    rN| |dz            | |dz            k    r5||d         k     r)|dz  }| |dz            | |dz            k    r||d         k     )nA| |dz            |z  |k    r/| |dz
           |k    r ||k    r|dz  }| |dz
           |k    r||k    |rt          | ||||          \  }}|||z
  dz   |k     r||d         k    r||k     r|	                    ||f           ,|                                 |	                    |           t          j        |	          S )a  Automatically extract clusters according to the Xi-steep method.

    This is rouphly an implementation of Figure 19 of the OPTICS paper.

    Parameters
    ----------
    reachability_plot : array-like of shape (n_samples,)
        The reachability plot, i.e. reachability ordered according to
        the calculated ordering, all computed by OPTICS.

    predecessor_plot : array-like of shape (n_samples,)
        Predecessors ordered according to the calculated ordering.

    xi : float, between 0 and 1
        Determines the minimum steepness on the reachability plot that
        constitutes a cluster boundary. For example, an upwards point in the
        reachability plot is defined by the ratio from one point to its
        successor being at most 1-xi.

    min_samples : int > 1
        The same as the min_samples given to OPTICS. Up and down steep regions
        can't have more then ``min_samples`` consecutive non-steep points.

    min_cluster_size : int > 1
        Minimum number of samples in an OPTICS cluster.

    predecessor_correction : bool
        Correct clusters based on the calculated predecessors.

    Returns
    -------
    clusters : ndarray of shape (n_clusters, 2)
        The list of clusters in the form of [start, end] in each row, with all
        indices inclusive. The clusters are ordered in a way that larger
        clusters encompassing smaller clusters come after those smaller
        clusters.
    r   r   g        rH   )invalidNr~   )r   r   r   r   r   r   )rq   hstackrr   errstateiterflatnonzeror   r   r   appendr   reverseextendarray)r   r   rM   r"   r*   r2   r1   r   r   r   r   r   ratiosteep_upwardsteep_downwarddownwardupwardsteep_indexD_startD_endDU_startU_end
U_clustersc_startc_endD_maxs                              r?   r   r     s   d 	#4bf"=>>FMDHE
C 
X	&	&	&  !#2#&):122)>>-!m"3319               BN<.+HIIJJ O( O( #rv/a0GHIIJJ +& F	(&tS-ARSSD!G">67KPPE!%<<AKKNNNAIE#E*CC 'tS-ARSSD!G"<7KPPEAIE#E*CJ 04 04G* %UQY/-?!E(JJ *!G*5=(,=eai,HHH *'A+69J5ST99UUU#ah..1 *'A+69J5ST99UUU#ah.. 'uqy1MAUJJ ,EAI6>>57??
 ,EAI6>>57?? * %9)+;XwPU& &NGU ? 7?Q&)999 QuX%% 7??!!7E"23333    OOJ''''8Hs   1B  BBc                 (   t          j        t          |           dt                    }d}|D ]L}t          j        ||d         |d         dz            dk              s|||d         |d         dz   <   |dz  }M|                                || <   |S )a  Extracts the labels from the clusters returned by `_xi_cluster`.
    We rely on the fact that clusters are stored
    with the smaller clusters coming before the larger ones.

    Parameters
    ----------
    ordering : array-like of shape (n_samples,)
        The ordering of points calculated by OPTICS

    clusters : array-like of shape (n_clusters, 2)
        List of clusters i.e. (start, end) tuples,
        as returned by `_xi_cluster`.

    Returns
    -------
    labels : ndarray of shape (n_samples,)
    r~   r   r   r   )rq   fullr   r   anyrU   )rM   r   r   labelcs        r?   r   r     s    & WS]]Bc222FE  vfQqTQqTAX./2566 	(-F1Q41Q4!8$%QJE{{}}F8MrA   )4rk   rS   numbersr   r   numpyrq   scipy.sparser   r   baser   r	   r
   
exceptionsr   metricsr   metrics.pairwiser   r   r   r   utilsr   utils._chunkingr   utils._param_validationr   r   r   r   r   utils.validationr   r   r   rx   r   ndarrayrl   rm   rn   rZ   r   rb   r_   r   r   r   r   r   rs   rA   r?   <module>r     s~  
 
  " " " " " " " "     : : : : : : : : < < < < < < < < < < . . . . . . ( ( ( ( ( ( I I I I I I I I ( ( ( ( ( (       . . . . . .              ; : : : : : : :e e e e e\= e e eP
 
 
! ! !H j/*HXq$v666HZAf555
 HT1d6:::;:cc.11]OCDDhOhtQW555t< j!J!J!JKKLhxD@@@AT"  #(  "RB RB# "RBj+1 +1 +1\ :,ZLq$v6667	  #'  > > >B 
|ZLHXq$v666HZAf555

 HXq$v666HZAf555

 xa62223#,+   #'#  2 l l l l' &l^< < <~    ,X X Xv    rA   