
    >[g^`                        d Z ddlZddlmZmZmZ ddlmZmZm	Z	m
Z
mZ ddlmZ ddlmZmZmZmZ dd	lmZ d
 Zd Z eddeg eeddd      g e
ddh      g e
 e ej0                   ej2                                      eg ee	ddd      dgedgd e
dh      gedgdd      dddddddd       Z eddeg ee	ddd      g e
ddh      g e
 e ej0                   ej2                                      eg ee	ddd      dgedgd e
dh      gedgdd      dddddddd       Z G d deeee      Z G d  d!eeee      Zy)"z!Nearest Neighbors graph functions    N   )ClassNamePrefixFeaturesOutMixinTransformerMixin_fit_context)IntegralIntervalReal
StrOptionsvalidate_params)check_is_fitted   )VALID_METRICSKNeighborsMixinNeighborsBaseRadiusNeighborsMixin)NearestNeighborsc           
          t        g d|||g      }| j                         }|D ]%  \  }}|||   k7  st        d|d|d||   d       y)z*Check the validity of the input parameters)metricpmetric_paramszGot z for z, while the estimator has z for the same parameter.N)zip
get_params
ValueError)Xr   r   r   params
est_params
param_name
func_params           S/var/www/html/bid-api/venv/lib/python3.12/site-packages/sklearn/neighbors/_graph.py_check_paramsr       s\    1FA}3MNFJ"(
JJ//z:j+AC  #)    c                 "    |dk(  r|dk(  }|sd} | S )z,Return the query based on include_self paramautoconnectivityN )r   include_selfmodes      r   _query_include_selfr(   !   s#    v~- Hr!   z
array-likezsparse matrixleft)closedr$   distancerightbooleanr#   )r   n_neighborsr'   r   r   r   r&   n_jobsFprefer_skip_nested_validation	minkowski)r'   r   r   r   r&   r/   c                    t        | t              s t        |||||      j                  |       } nt	        | |||       t        | j                  ||      }| j                  |||      S )a	  Compute the (weighted) graph of k-Neighbors for points in X.

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

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        Sample data.

    n_neighbors : int
        Number of neighbors for each sample.

    mode : {'connectivity', 'distance'}, default='connectivity'
        Type of returned matrix: 'connectivity' will return the connectivity
        matrix with ones and zeros, and 'distance' will return the distances
        between neighbors according to the given metric.

    metric : str, default='minkowski'
        Metric to use for distance computation. Default is "minkowski", which
        results in the standard Euclidean distance when p = 2. See the
        documentation of `scipy.spatial.distance
        <https://docs.scipy.org/doc/scipy/reference/spatial.distance.html>`_ and
        the metrics listed in
        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
        values.

    p : float, default=2
        Power parameter for the Minkowski metric. 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. This parameter is expected
        to be positive.

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

    include_self : bool or 'auto', default=False
        Whether or not to mark each sample as the first nearest neighbor to
        itself. If 'auto', then True is used for mode='connectivity' and False
        for mode='distance'.

    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
    -------
    A : sparse matrix of shape (n_samples, n_samples)
        Graph where A[i, j] is assigned the weight of edge that
        connects i to j. The matrix is of CSR format.

    See Also
    --------
    radius_neighbors_graph: Compute the (weighted) graph of Neighbors for points in X.

    Examples
    --------
    >>> X = [[0], [3], [1]]
    >>> from sklearn.neighbors import kneighbors_graph
    >>> A = kneighbors_graph(X, 2, mode='connectivity', include_self=True)
    >>> A.toarray()
    array([[1., 0., 1.],
           [0., 1., 1.],
           [1., 0., 1.]])
    )r.   r   r   r   r/   )r   r.   r'   )
isinstancer   r   fitr    r(   _fit_Xkneighbors_graph)	r   r.   r'   r   r   r   r&   r/   querys	            r   r7   r7   -   sp    t a)#'
 #a& 	
 	aM2,=E;TJJr!   both)r   radiusr'   r   r   r   r&   r/   c                    t        | t              s t        |||||      j                  |       } nt	        | |||       t        | j                  ||      }| j                  |||      S )a!
  Compute the (weighted) graph of Neighbors for points in X.

    Neighborhoods are restricted the points at a distance lower than
    radius.

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

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples, n_features)
        Sample data.

    radius : float
        Radius of neighborhoods.

    mode : {'connectivity', 'distance'}, default='connectivity'
        Type of returned matrix: 'connectivity' will return the connectivity
        matrix with ones and zeros, and 'distance' will return the distances
        between neighbors according to the given metric.

    metric : str, default='minkowski'
        Metric to use for distance computation. Default is "minkowski", which
        results in the standard Euclidean distance when p = 2. See the
        documentation of `scipy.spatial.distance
        <https://docs.scipy.org/doc/scipy/reference/spatial.distance.html>`_ and
        the metrics listed in
        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
        values.

    p : float, default=2
        Power parameter for the Minkowski metric. 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.

    include_self : bool or 'auto', default=False
        Whether or not to mark each sample as the first nearest neighbor to
        itself. If 'auto', then True is used for mode='connectivity' and False
        for mode='distance'.

    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
    -------
    A : sparse matrix of shape (n_samples, n_samples)
        Graph where A[i, j] is assigned the weight of edge that connects
        i to j. The matrix is of CSR format.

    See Also
    --------
    kneighbors_graph: Compute the weighted graph of k-neighbors for points in X.

    Examples
    --------
    >>> X = [[0], [3], [1]]
    >>> from sklearn.neighbors import radius_neighbors_graph
    >>> A = radius_neighbors_graph(X, 1.5, mode='connectivity',
    ...                            include_self=True)
    >>> A.toarray()
    array([[1., 0., 1.],
           [0., 1., 0.],
           [1., 0., 1.]])
    )r:   r   r   r   r/   )r4   r   r   r5   r    r(   r6   radius_neighbors_graph)	r   r:   r'   r   r   r   r&   r/   r8   s	            r   r<   r<      sn    z a-.'
 #a& 	
 	aM2,=E##E6488r!   c            	            e Zd ZU dZi ej
                  d eddh      giZeed<   ej                  d       dddd	d
dddd fd
Z
 ed      dd       Zd ZddZ xZS )KNeighborsTransformera  Transform X into a (weighted) graph of k nearest neighbors.

    The transformed data is a sparse graph as returned by kneighbors_graph.

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

    .. versionadded:: 0.22

    Parameters
    ----------
    mode : {'distance', 'connectivity'}, default='distance'
        Type of returned matrix: 'connectivity' will return the connectivity
        matrix with ones and zeros, and 'distance' will return the distances
        between neighbors according to the given metric.

    n_neighbors : int, default=5
        Number of neighbors for each sample in the transformed sparse graph.
        For compatibility reasons, as each sample is considered as its own
        neighbor, one extra neighbor will be computed when mode == 'distance'.
        In this case, the sparse graph contains (n_neighbors + 1) neighbors.

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

        - 'ball_tree' will use :class:`BallTree`
        - 'kd_tree' will use :class:`KDTree`
        - 'brute' will use a brute-force search.
        - 'auto' 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 BallTree or 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.

    metric : str or callable, default='minkowski'
        Metric to use for distance computation. Default is "minkowski", which
        results in the standard Euclidean distance when p = 2. See the
        documentation of `scipy.spatial.distance
        <https://docs.scipy.org/doc/scipy/reference/spatial.distance.html>`_ and
        the metrics listed in
        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
        values.

        If metric is a callable function, it takes two arrays representing 1D
        vectors as inputs and must return one value indicating the distance
        between those vectors. This works for Scipy's metrics, but is less
        efficient than passing the metric name as a string.

        Distance matrices are not supported.

    p : float, default=2
        Parameter for the Minkowski metric from
        sklearn.metrics.pairwise.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.
        This parameter is expected to be positive.

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

    n_jobs : int, default=None
        The number of parallel jobs to run for neighbors search.
        If ``-1``, then the number of jobs is set to the number of CPU cores.

    Attributes
    ----------
    effective_metric_ : str or callable
        The distance metric used. It will be same as the `metric` parameter
        or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to
        'minkowski' and `p` parameter set to 2.

    effective_metric_params_ : dict
        Additional keyword arguments for the metric function. For most metrics
        will be same with `metric_params` parameter, but may also contain the
        `p` parameter value if the `effective_metric_` attribute is set to
        'minkowski'.

    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

    n_samples_fit_ : int
        Number of samples in the fitted data.

    See Also
    --------
    kneighbors_graph : Compute the weighted graph of k-neighbors for
        points in X.
    RadiusNeighborsTransformer : Transform X into a weighted graph of
        neighbors nearer than a radius.

    Notes
    -----
    For an example of using :class:`~sklearn.neighbors.KNeighborsTransformer`
    in combination with :class:`~sklearn.manifold.TSNE` see
    :ref:`sphx_glr_auto_examples_neighbors_approximate_nearest_neighbors.py`.

    Examples
    --------
    >>> from sklearn.datasets import load_wine
    >>> from sklearn.neighbors import KNeighborsTransformer
    >>> X, _ = load_wine(return_X_y=True)
    >>> X.shape
    (178, 13)
    >>> transformer = KNeighborsTransformer(n_neighbors=5, mode='distance')
    >>> X_dist_graph = transformer.fit_transform(X)
    >>> X_dist_graph.shape
    (178, 178)
    r'   r+   r$   _parameter_constraintsr:      r#      r2   r   N)r'   r.   	algorithm	leaf_sizer   r   r   r/   c          
      J    t         t        |   |d ||||||       || _        y N)r.   r:   rB   rC   r   r   r   r/   )superr>   __init__r'   )
selfr'   r.   rB   rC   r   r   r   r/   	__class__s
            r   rG   zKNeighborsTransformer.__init__  s;     	#T3#' 	4 		
 	r!   Fr0   c                 J    | j                  |       | j                  | _        | S )a  Fit the k-nearest neighbors transformer from the training dataset.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features) or                 (n_samples, n_samples) if metric='precomputed'
            Training data.
        y : Ignored
            Not used, present for API consistency by convention.

        Returns
        -------
        self : KNeighborsTransformer
            The fitted k-nearest neighbors transformer.
        _fitn_samples_fit__n_features_outrH   r   ys      r   r5   zKNeighborsTransformer.fit  s"    ( 			!#22r!   c                     t        |        | j                  dk(  }| j                  || j                  | j                  |z         S )  Compute the (weighted) graph of Neighbors for points in X.

        Parameters
        ----------
        X : array-like of shape (n_samples_transform, n_features)
            Sample data.

        Returns
        -------
        Xt : sparse matrix of shape (n_samples_transform, n_samples_fit)
            Xt[i, j] is assigned the weight of edge that connects i to j.
            Only the neighbors have an explicit value.
            The diagonal is always explicit.
            The matrix is of CSR format.
        r+   )r'   r.   )r   r'   r7   r.   )rH   r   add_ones      r   	transformzKNeighborsTransformer.transform  sH      	))z)$$DII4+;+;g+E % 
 	
r!   c                 B    | j                  |      j                  |      S a  Fit to data, then transform it.

        Fits transformer to X and y with optional parameters fit_params
        and returns a transformed version of X.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Training set.

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

        Returns
        -------
        Xt : sparse matrix of shape (n_samples, n_samples)
            Xt[i, j] is assigned the weight of edge that connects i to j.
            Only the neighbors have an explicit value.
            The diagonal is always explicit.
            The matrix is of CSR format.
        r5   rT   rO   s      r   fit_transformz#KNeighborsTransformer.fit_transform      , xx{$$Q''r!   N__name__
__module____qualname____doc__r   r?   r
   dict__annotations__poprG   r   r5   rT   rX   __classcell__rI   s   @r   r>   r>     s    xt$

.
.$Z89:$D  x(
 
0 &+	(
,(r!   r>   c            	            e Zd ZU dZi ej
                  d eddh      giZeed<   ej                  d       dddd	d
dddd fd
Z
 ed      dd       Zd ZddZ xZS )RadiusNeighborsTransformera-  Transform X into a (weighted) graph of neighbors nearer than a radius.

    The transformed data is a sparse graph as returned by
    `radius_neighbors_graph`.

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

    .. versionadded:: 0.22

    Parameters
    ----------
    mode : {'distance', 'connectivity'}, default='distance'
        Type of returned matrix: 'connectivity' will return the connectivity
        matrix with ones and zeros, and 'distance' will return the distances
        between neighbors according to the given metric.

    radius : float, default=1.0
        Radius of neighborhood in the transformed sparse graph.

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

        - 'ball_tree' will use :class:`BallTree`
        - 'kd_tree' will use :class:`KDTree`
        - 'brute' will use a brute-force search.
        - 'auto' 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 BallTree or 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.

    metric : str or callable, default='minkowski'
        Metric to use for distance computation. Default is "minkowski", which
        results in the standard Euclidean distance when p = 2. See the
        documentation of `scipy.spatial.distance
        <https://docs.scipy.org/doc/scipy/reference/spatial.distance.html>`_ and
        the metrics listed in
        :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric
        values.

        If metric is a callable function, it takes two arrays representing 1D
        vectors as inputs and must return one value indicating the distance
        between those vectors. This works for Scipy's metrics, but is less
        efficient than passing the metric name as a string.

        Distance matrices are not supported.

    p : float, default=2
        Parameter for the Minkowski metric from
        sklearn.metrics.pairwise.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.
        This parameter is expected to be positive.

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

    n_jobs : int, default=None
        The number of parallel jobs to run for neighbors search.
        If ``-1``, then the number of jobs is set to the number of CPU cores.

    Attributes
    ----------
    effective_metric_ : str or callable
        The distance metric used. It will be same as the `metric` parameter
        or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to
        'minkowski' and `p` parameter set to 2.

    effective_metric_params_ : dict
        Additional keyword arguments for the metric function. For most metrics
        will be same with `metric_params` parameter, but may also contain the
        `p` parameter value if the `effective_metric_` attribute is set to
        'minkowski'.

    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

    n_samples_fit_ : int
        Number of samples in the fitted data.

    See Also
    --------
    kneighbors_graph : Compute the weighted graph of k-neighbors for
        points in X.
    KNeighborsTransformer : Transform X into a weighted graph of k
        nearest neighbors.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.datasets import load_wine
    >>> from sklearn.cluster import DBSCAN
    >>> from sklearn.neighbors import RadiusNeighborsTransformer
    >>> from sklearn.pipeline import make_pipeline
    >>> X, _ = load_wine(return_X_y=True)
    >>> estimator = make_pipeline(
    ...     RadiusNeighborsTransformer(radius=42.0, mode='distance'),
    ...     DBSCAN(eps=25.0, metric='precomputed'))
    >>> X_clustered = estimator.fit_predict(X)
    >>> clusters, counts = np.unique(X_clustered, return_counts=True)
    >>> print(counts)
    [ 29  15 111  11  12]
    r'   r+   r$   r?   r.   g      ?r#   rA   r2   r   N)r'   r:   rB   rC   r   r   r   r/   c          
      J    t         t        |   d |||||||       || _        y rE   )rF   rf   rG   r'   )
rH   r'   r:   rB   rC   r   r   r   r/   rI   s
            r   rG   z#RadiusNeighborsTransformer.__init__f  s;     	($8' 	9 		
 	r!   Fr0   c                 J    | j                  |       | j                  | _        | S )a  Fit the radius neighbors transformer from the training dataset.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features) or                 (n_samples, n_samples) if metric='precomputed'
            Training data.

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

        Returns
        -------
        self : RadiusNeighborsTransformer
            The fitted radius neighbors transformer.
        rK   rO   s      r   r5   zRadiusNeighborsTransformer.fit~  s"    * 			!#22r!   c                 T    t        |        | j                  || j                  d      S )rR   T)r'   sort_results)r   r<   r'   )rH   r   s     r   rT   z$RadiusNeighborsTransformer.transform  s(      	**14994*PPr!   c                 B    | j                  |      j                  |      S rV   rW   rO   s      r   rX   z(RadiusNeighborsTransformer.fit_transform  rY   r!   rZ   r[   rd   s   @r   rf   rf     s    tl$

.
.$Z89:$D  }-
 
0 &+	*Q&(r!   rf   ) r_   	itertoolsbaser   r   r   utils._param_validationr   r   r	   r
   r   utils.validationr   _baser   r   r   r   _unsupervisedr   r    r(   setchainvaluescallabler`   r7   r<   r>   rf   r%   r!   r   <module>rv      s   '
  R R  / V V +		 O_= 1d6BC^Z89:c/)//3G=3G3G3I"JKLhWtQW5t<"Jx$89T"	 #(" 
YKYKx O-ABD!T&9:^Z89:c/)//3G=3G3G3I"JKLhWtQW5t<"Jx$89T"	 #(" 
\9\9~_(#_6F_(D\(#	\(r!   