
    >[g              	          d Z ddlZddlZddlZddlmZmZ ddlmZ ddlm	Z	m
Z
 ddlZddlmZ ddlmZmZ dd	lmZmZmZ dd
lmZmZ ddlmZmZ ddlmZmZ ddlm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z( ddl)m*Z*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8 g dZ9e+ e*d      k  re9dgz  Z9e+ e*d      k  re9dgz  Z9e+ e*d      k  re9dgz  Z9 e:e6jv                  e8jv                   e< e=e       j}                  e9                  Z? e:g g  e j                         dd hz
        ZAd! ZBd" ZCd# ZD e(d$gd%gd%gd&d'(      d3d)       ZEd* ZFd+ ZG G d, d-eee.      ZH G d/ d0      ZI G d1 d2      ZJy)4z-Base and mixin classes for nearest neighbors.    N)ABCMetaabstractmethod)partial)IntegralReal)effective_n_jobs)
csr_matrixissparse   )BaseEstimatorMultiOutputMixinis_classifier)DataConversionWarningEfficiencyWarning)DistanceMetricpairwise_distances_chunked)ArgKminRadiusNeighbors)PAIRWISE_DISTANCE_FUNCTIONS)check_arraygen_even_slicesget_tags)Interval
StrOptionsvalidate_params)parse_versionsp_base_version)check_classification_targets)Paralleldelayed)_to_object_arraycheck_is_fittedvalidate_data   )BallTree)KDTree)
braycurtiscanberra	chebyshevcorrelationcosinedicehammingjaccardmahalanobis	minkowskirogerstanimoto
russellrao
seuclideansokalsneathsqeuclideanyulez1.17sokalmichenerz1.11	kulsinskiz1.9matching)	ball_treekd_treebrute	haversinenan_euclideanc                    |dv ry|dk(  r| j                   t        j                   t              u r6t        |       D ]&  \  }}t	        |d      rd|v r	|dk(  | |<   d|z  | |<   ( | S t        j
                  d      5  d| z  } ddd       t        j                  |       }t        j                  |d	
      }||   | |<   | S t        |      r ||       S y# 1 sw Y   SxY w)a  Get the weights from an array of distances and a parameter ``weights``.

    Assume weights have already been validated.

    Parameters
    ----------
    dist : ndarray
        The input distances.

    weights : {'uniform', 'distance'}, callable or None
        The kind of weighting used.

    Returns
    -------
    weights_arr : array of the same shape as ``dist``
        If ``weights == 'uniform'``, then returns None.
    )NuniformNdistance__contains__g        g      ?ignore)divider$   axis)	dtypenpobject	enumeratehasattrerrstateisinfanycallable)distweightspoint_dist_i
point_distinf_maskinf_rows         R/var/www/html/bid-api/venv/lib/python3.12/site-packages/sklearn/neighbors/_base.py_get_weightsrW   Q   s    $ ##* ::&)),5dO(j :~63*;L)3s):D&),z)9D& -<  H-Tz .xx~HffXA.G$W-DMt}  .-s   <CCc                    | j                   dk(  sJ | j                  dd | j                  dd kD  }t        j                  | j                  dd dz
        }|||j
                  d   k     }|j                         ||   j                         k(  S )a  Return whether the graph's non-zero entries are sorted by data.

    The non-zero entries are stored in graph.data and graph.indices.
    For each row (or sample), the non-zero entries can be either:
        - sorted by indices, as after graph.sort_indices();
        - sorted by data, as after _check_precomputed(graph);
        - not sorted.

    Parameters
    ----------
    graph : sparse matrix of shape (n_samples, n_samples)
        Neighbors graph as given by `kneighbors_graph` or
        `radius_neighbors_graph`. Matrix should be of format CSR format.

    Returns
    -------
    res : bool
        Whether input graph is sorted by data.
    csrNr$   r   )formatdatarH   uniqueindptrshapesum)graphout_of_orderline_changes      rV   _is_sorted_by_datard      s    ( <<5   ::cr?UZZ^3L))ELL2.23KkL,>,>q,AABKk!:!>!>!@@@    c                     t        |       st        | dd      } | S | }|j                  dvr$t        dj                  |j                              |j                  dk7  }t        |ddd      }t	        || d	      }|S )
a  Check precomputed distance matrix.

    If the precomputed distance matrix is sparse, it checks that the non-zero
    entries are sorted by distances. If not, the matrix is copied and sorted.

    Parameters
    ----------
    X : {sparse matrix, array-like}, (n_samples, n_samples)
        Distance matrix to other samples. X may be a sparse matrix, in which
        case only non-zero elements may be considered neighbors.

    Returns
    -------
    X : {sparse matrix, array-like}, (n_samples, n_samples)
        Distance matrix to other samples. X may be a sparse matrix, in which
        case only non-zero elements may be considered neighbors.
    TX)ensure_non_negative
input_namerY   csccoolilzSSparse matrix in {!r} format is not supported due to its handling of explicit zerosrY   zprecomputed distance matrix)accept_sparserh   ri   )copywarn_when_not_sorted)r
   r   r[   	TypeErrorsort_graph_by_row_values)rg   ra   copieds      rV   _check_precomputedrt      s    $ A;tD||77--3VELL-A
 	
 \\U"F 0	E %UVRVWELre   zsparse matrixboolean)ra   ro   rp   T)prefer_skip_nested_validationc                     | j                   dk(  rt        |       r| S |rt        j                  dt               | j                   dvrt        d| j                   d      | j                   dk7  r|st        d      | j                  d      } n|r| j                         } t        j                  | j                        }|j                         |j                         k(  r| j                  d   }| j                  j!                  |d      }t        j"                  |d	
      }|t        j$                  |      dddf   |d   z  z  }|j'                         }| j                  |   | _        | j(                  |   | _        | S t+        | j                  | j                  dd       D ]g  \  }}t        j"                  | j                  || d	
      }| j                  || |   | j                  || | j(                  || |   | j(                  || i | S )a{  Sort a sparse graph such that each row is stored with increasing values.

    .. versionadded:: 1.2

    Parameters
    ----------
    graph : sparse matrix of shape (n_samples, n_samples)
        Distance matrix to other samples, where only non-zero elements are
        considered neighbors. Matrix is converted to CSR format if not already.

    copy : bool, default=False
        If True, the graph is copied before sorting. If False, the sorting is
        performed inplace. If the graph is not of CSR format, `copy` must be
        True to allow the conversion to CSR format, otherwise an error is
        raised.

    warn_when_not_sorted : bool, default=True
        If True, a :class:`~sklearn.exceptions.EfficiencyWarning` is raised
        when the input graph is not sorted by row values.

    Returns
    -------
    graph : sparse matrix of shape (n_samples, n_samples)
        Distance matrix to other samples, where only non-zero elements are
        considered neighbors. Matrix is in CSR format.

    Examples
    --------
    >>> from scipy.sparse import csr_matrix
    >>> from sklearn.neighbors import sort_graph_by_row_values
    >>> X = csr_matrix(
    ...     [[0., 3., 1.],
    ...      [3., 0., 2.],
    ...      [1., 2., 0.]])
    >>> X.data
    array([3., 1., 3., 2., 1., 2.])
    >>> X_ = sort_graph_by_row_values(X)
    >>> X_.data
    array([1., 3., 2., 3., 1., 2.])
    rY   zPrecomputed sparse input was not sorted by row values. Use the function sklearn.neighbors.sort_graph_by_row_values to sort the input by row values, with warn_when_not_sorted=False to remove this warning.rj   zSparse matrix in z> format is not supported due to its handling of explicit zeroszZThe input graph is not in CSR format. Use copy=True to allow the conversion to CSR format.r   rZ   	mergesortkindNr$   )r[   rd   warningswarnr   rq   
ValueErrorasformatro   rH   diffr^   maxminr_   r\   reshapeargsortarangeravelindiceszip)	ra   ro   rp   row_nnz	n_samples	distancesorderstartstops	            rV   rr   rr      s   b ||u!3E!:
 	
 ||77/ 0- -
 	
 
	0  u%	

ggell#G{{}%KKN	JJ&&y"5	

9;79%ag.;;ZZ&
e, L u||U\\!"-=>KE4JJuzz%5KHE%*ZZd%;E%BEJJuT"(-eD(A%(HEMM%% ?
 Lre   c                 Z     j                   d    j                  dk(  sJ t        j                   j                        j                         k  rt        dfz         fd}|r$ | j                         | j                        fS  | j                        S )a  Decompose a nearest neighbors sparse graph into distances and indices.

    Parameters
    ----------
    graph : sparse matrix of shape (n_samples, n_samples)
        Neighbors graph as given by `kneighbors_graph` or
        `radius_neighbors_graph`. Matrix should be of format CSR format.

    n_neighbors : int
        Number of neighbors required for each sample.

    return_distance : bool
        Whether or not to return the distances.

    Returns
    -------
    neigh_dist : ndarray of shape (n_samples, n_neighbors)
        Distances to nearest neighbors. Only present if `return_distance=True`.

    neigh_ind : ndarray of shape (n_samples, n_neighbors)
        Indices of nearest neighbors.
    r   rY   z%d neighbors per samples are required, but some samples have only %d neighbors in precomputed graph matrix. Decrease number of neighbors used or recompute the graph with more neighbors.c                 (   j                         k(  r| j                  d      d d d f   S t        j                  t        j                        df      }|j
                  d dd f   z  }| j                  |d      j                        S )NrZ   r$   clip)mode)r   r   rH   tiler   r^   take)aidxra   n_neighborsr   r   row_nnz_mins     rV   extractz'_kneighbors_from_graph.<locals>.extractK  s    ;;=K'99Y+A||O<<''"))K09a.AC5<<T	**C66#F6+33I{KKre   )	r_   r[   rH   r   r^   r   r}   r\   r   )ra   r   return_distancer   r   r   r   s   ``  @@@rV   _kneighbors_from_graphr   &  s    . AI<<5    ggell#G++-K;#<I K()
 	
L L uzz"GEMM$:::u}}%%re   c                    | j                   dk(  sJ t        | j                  j                         |k        }|r%| j                  | j                  | j
                  }}}n| j                  |k  }|r t        j                  || j                        }t        j                  || j                        }t        j                  dgt        j                  |      f      | j
                     }|j                  t        j                  |      }|r"t        t        j                  |dd             }t        t        j                  ||dd             }	|r|	fS |	S )a  Decompose a nearest neighbors sparse graph into distances and indices.

    Parameters
    ----------
    graph : sparse matrix of shape (n_samples, n_samples)
        Neighbors graph as given by `kneighbors_graph` or
        `radius_neighbors_graph`. Matrix should be of format CSR format.

    radius : float
        Radius of neighborhoods which should be strictly positive.

    return_distance : bool
        Whether or not to return the distances.

    Returns
    -------
    neigh_dist : ndarray of shape (n_samples,) of arrays
        Distances to nearest neighbors. Only present if `return_distance=True`.

    neigh_ind : ndarray of shape (n_samples,) of arrays
        Indices of nearest neighbors.
    rY   r   )ro   r$   rZ   )r[   boolr\   r   r   r^   rH   compressconcatenatecumsumastypeintpr!   split)
ra   radiusr   no_filter_neededr\   r   r^   mask
neigh_dist	neigh_inds
             rV   _radius_neighbors_from_graphr   Z  s   . <<5   EJJNN,67 %

EMM5<<vgzzV#;;tUZZ0D++dEMM2!biio 67EnnRWW+;n<G%bhhtVAb\&BC
 '6!B<!@AI9$$re   c                   >    e Zd ZU dZ eeddd      dg eeddd      dg eh d      g eeddd      g eeddd	      dg e e e	j                  ej                                      egedgedgd
Zeed<   e	 	 	 	 	 	 	 	 dd       Zd ZddZ fdZ xZS )NeighborsBasez,Base class for nearest neighbors estimators.r$   Nleft)closedr   both>   autor<   r;   r:   right)r   r   	algorithm	leaf_sizepmetricmetric_paramsn_jobs_parameter_constraintsc	                 t    || _         || _        || _        || _        || _        || _        || _        || _        y N)r   r   r   r   r   r   r   r   )	selfr   r   r   r   r   r   r   r   s	            rV   __init__zNeighborsBase.__init__  s>     '""*re   c                    | j                   dk(  r\| j                  dk(  rd}nVt        | j                        s/| j                  t        d   v st	        | j                  t
              rd}nd}n| j                   }t        | j                        r'| j                   dk(  rct        d| j                  z        | j                  t        |   vr6t	        | j                  t
              st        d| j                  d|d	      | j                  9d
| j                  v r*| j                  t        j                  dt        d       y y y y )Nr   precomputedr<   r:   r;   zhkd_tree does not support callable metric '%s'Function call overhead will resultin very poor performance.zMetric 'z9' not valid. Use sorted(sklearn.neighbors.VALID_METRICS['zA']) to get valid options. Metric can also be a callable function.r   z\Parameter p is found in metric_params. The corresponding parameter from __init__ is ignored.   
stacklevel)r   r   rO   VALID_METRICS
isinstancer   r}   r   r   r{   r|   SyntaxWarning)r   	alg_checks     rV   _check_algorithm_metricz%NeighborsBase._check_algorithm_metric  s$   >>V#{{m+#	%;;-"<<dkk>:'	#	IDKK ~~* 026++> 
 [[i 88KKB
  >B[[)U  )cT5G5G.Gvv!& "  " /H)re   c           	         t        |       j                  j                  rdnd}| j                         j                  j
                  rt        |t        t        t        f      st        | ||ddd|      \  }}t        |       ru|j                  dk(  s!|j                  dk(  rV|j                  d   dk(  rD|j                  dk7  rt        j                  dt         d	       d
| _        |j%                  d      }nd| _        t'        |       g | _        t+        j,                  |j                  t*        j.                        | _        t3        | j0                  j                  d         D ]O  }t+        j4                  |d d |f   d      \  }| j0                  d d |f<   | j(                  j7                  |       Q | j"                  sg| j(                  d   | _        | j0                  j9                         | _        n3|| _        n+t        |t        t        t        f      st        | ||dd      }| j;                          | j<                  i | _        n| j<                  jA                         | _        | j>                  jC                  d| jD                        }| jF                  dk(  r|| j>                  d<   | jF                  | _$        | jF                  dk(  r| j>                  jK                  dd      }| j>                  jK                  dd       }|dk(  r
|d| _$        nJ|dk(  r
|d| _$        n;|t*        jL                  k(  r
|d| _$        n|| j>                  d<   || j>                  d<   t        |t              rF|jN                  | _'        |jP                  | _(        |jR                  | _)        |jT                  | _*        | S t        |t              r?|jV                  | _'        || _(        d| _)        |jV                  j                  d   | _*        | S t        |t              r?|jV                  | _'        || _(        d| _)        |jV                  j                  d   | _*        | S | jF                  dk(  rstY        |      }|j                  d   |j                  d   k7  r5t[        dj]                  |j                  d   |j                  d               |j                  d   | _/        |j                  d   }	|	dk(  rt[        d      ta        |      r| jb                  dvrt        j                  d       | jH                  td        d   vrGtg        | jH                        s2t        | jH                  th              st[        d| jH                  z        |jA                         | _'        d | _(        d| _)        |j                  d   | _*        | S | jb                  | _)        || _'        |j                  d   | _*        | jR                  dk(  r| jF                  dk(  sQ| jN                  j                  d   d kD  s5| jj                  1| jj                  | jN                  j                  d   dz  k\  rd| _)        n| jH                  dk(  r| j>                  d   dk  rd| _)        n| jH                  dk(  r#| j>                  jC                  d      d| _)        nV| jH                  tl        d   v rd| _)        n9tg        | jH                        s| jH                  tl        d   v rd| _)        nd| _)        | jH                  dk(  rP| j>                  d   dk  r>| jR                  dk(  rt        j                  d!       nt[        d"| jR                   d#      | jR                  dk(  r4t        || jn                  fd$| jH                  i| j>                  | _(        | S | jR                  dk(  ri| jH                  dk(  r&| j>                  jC                  d      t[        d%      t        || jn                  fd$| jH                  i| j>                  | _(        | S | jR                  dk(  rd | _(        | S )&N	allow-nanTrY   C)rn   multi_outputr   ensure_all_finiter$   r   zA column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples,), for example using ravel().r   F)rZ   r$   rG   )return_inverser   )r   rn   r   r   r0   w	manhattan	euclideanr)   r:   r;   r   z;Precomputed matrix must be square. Input is a {}x{} matrix.z n_samples must be greater than 0)r   r<   z4cannot use tree with sparse input: using brute forcer<   zMetric '%s' not valid for sparse input. Use sorted(sklearn.neighbors.VALID_METRICS_SPARSE['brute']) to get valid options. Metric can also be a callable function.r      zwMind that for 0 < p < 1, Minkowski metrics are not distance metrics. Continuing the execution with `algorithm='brute'`.zalgorithm="zv" does not support 0 < p < 1 for the Minkowski metric. To resolve this problem either set p >= 1 or algorithm="brute".r   zalgorithm='kd_tree' is not valid for metric='minkowski' with a weight parameter 'w': try algorithm='ball_tree' or algorithm='brute' instead.)8r   
input_tags	allow_nan__sklearn_tags__target_tagsrequiredr   r&   r%   r   r#   r   ndimr_   r{   r|   r   outputs_2d_r   r   classes_rH   emptyr   _yranger]   appendr   r   r   effective_metric_params_ro   getr   r   effective_metric_popinf_fit_X_tree_fit_methodn_samples_fit_r\   rt   r}   r[   n_features_in_r
   r   VALID_METRICS_SPARSErO   r   r   r   r   )
r   rg   yr   kclasseseffective_pr   r   r   s
             rV   _fitzNeighborsBase._fit  sV   +3D>+D+D+N+NKTX  "..77a&(M!BC$"'!%&71 T"66Q;!&&A+!''!*/vv{ !9
 2'(	 (-D$		'*A'+D$,Q/ " ((177"'':tww}}Q/0A-/YYqAwt-T*GTWWQT]MM((1 1 ''$(MM!$4DM"ggmmoDG a&(M!BC!&7"' 	$$&%,.D),0,>,>,C,C,ED)3377TVVD;;+%1<D))#.!%;;+%--11#q9A--11#t<AAv!))4&aAI)4&bff)4& 67--c256--c2a'((DKDJ }}D"#"2"2DK8$&&DKDJ*D"#&&,,q/DK6"&&DKDJ(D"#&&,,q/DK;;-'"1%AwwqzQWWQZ' 006qwwqz1771:0N  #$''!*DGGAJ	>?@@A;~~%66TU &&.B7.KK !7!78"4#9#9>J > BFAWAW	Y  &&(DKDJ&D"#''!*DK>>ggajv% },;;$$Q'",$$0((DKK,=,=a,@A,EE $+  **k955c:Q>'.D$**k95599#>J (3D$++}Y/GG'0D$T334--{1KK'2D$'.D$ ""k1--c2Q6 7*S
 !!$"2"2!3 47 7  {*! -- //	DJ4 ) *&&+51155c:F 4    -- //	DJ  (DJre   c                     t         |          }| j                  dk(  |j                  _        |j                  j                  |j                  _        | j                  dk(  |j                  _        |S )Nr   r>   )superr   r   r   pairwisepositive_onlyr   r   tags	__class__s     rV   r   zNeighborsBase.__sklearn_tags__  sU    w')#';;-#? (,(@(@%$(KK?$B!re   )NNr      r0   r   NNr   )__name__
__module____qualname____doc__r   r   r   r   set	itertoolschainr   valuesrO   dictr   __annotations__r   r   r   r   r   __classcell__r   s   @rV   r   r     s    6 !1d6BDID!T&94@ !JKLxD@AtQW5t<c/)//=3G3G3I"JKLhWT"	$D 	  
 (+ZhT re   r   )	metaclassc                   &    e Zd ZdZd ZddZddZy)KNeighborsMixinzMixin for k-neighbors searches.c                 Z   t        j                  |j                  d         dddf   }t        j                  ||dz
  d      }|ddd|f   }||t        j                  |||f         f   }|r8| j
                  dk(  rt        j                  |||f         |f}|S |||f   |f}|S |}|S )a  Reduce a chunk of distances to the nearest neighbors.

        Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`

        Parameters
        ----------
        dist : ndarray of shape (n_samples_chunk, n_samples)
            The distance matrix.

        start : int
            The index in X which the first row of dist corresponds to.

        n_neighbors : int
            Number of neighbors required for each sample.

        return_distance : bool
            Whether or not to return the distances.

        Returns
        -------
        dist : array of shape (n_samples_chunk, n_neighbors)
            Returned only if `return_distance=True`.

        neigh : array of shape (n_samples_chunk, n_neighbors)
            The neighbors indices.
        r   Nr$   rE   r   )rH   r   r_   argpartitionr   r   sqrt)r   rP   r   r   r   sample_ranger   results           rV   _kneighbors_reduce_funcz'KNeighborsMixin._kneighbors_reduce_func  s    6 yyA/48OOD+/B	a+o.	lBJJtL)<S7T,UUV	%%4lI&=!>?J
  lI56	A  Fre   Nc                 ~    t                 j                  nDdk  rt        dz        t        t        j
                        st        dt              z        t               j                  j                  rdnd}du }|r j                  dz  n, j                  dk(  rt              nt         |d	d
d       j                  }|kD  r0|rdz  d}nd}t        d| d d| dj                   d          t#         j$                        }d}	 j&                  dk(  xr9 t)        j*                  n j                   j                   j,                        }
|
r<t)        j.                   j                   j,                   j0                  d      }n! j&                  dk(  r) j                  dk(  rt3              rt5              }n j&                  dk(  rgt7         j8                        } j,                  dk(  rddi}n j0                  }t;        t=         j                  f| j,                  |d|      }	ns j&                  dv rZt3              rt        d j&                  z         t?        |d       fdtA        j                   d   |      D              }	nt        d      |	Mr6tC        |	 \  }}tE        jF                  |      tE        jF                  |      f}ntE        jF                  |	      }|sS r\  }}n}j                   \  }}tE        jH                  |      dddf   }||k7  }tE        jJ                  |d       }d
|dddf   |<   tE        jL                  ||   |dz
  f      }r"tE        jL                  |   |dz
  f      }||fS |S )!a  Find the K-neighbors of a point.

        Returns indices of and distances to the neighbors of each point.

        Parameters
        ----------
        X : {array-like, sparse matrix}, shape (n_queries, n_features),             or (n_queries, n_indexed) if metric == 'precomputed', default=None
            The query point or points.
            If not provided, neighbors of each indexed point are returned.
            In this case, the query point is not considered its own neighbor.

        n_neighbors : int, default=None
            Number of neighbors required for each sample. The default is the
            value passed to the constructor.

        return_distance : bool, default=True
            Whether or not to return the distances.

        Returns
        -------
        neigh_dist : ndarray of shape (n_queries, n_neighbors)
            Array representing the lengths to points, only present if
            return_distance=True.

        neigh_ind : ndarray of shape (n_queries, n_neighbors)
            Indices of the nearest points in the population matrix.

        Examples
        --------
        In the following example, we construct a NearestNeighbors
        class from an array representing our data set and ask who's
        the closest point to [1,1,1]

        >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]
        >>> from sklearn.neighbors import NearestNeighbors
        >>> neigh = NearestNeighbors(n_neighbors=1)
        >>> neigh.fit(samples)
        NearestNeighbors(n_neighbors=1)
        >>> print(neigh.kneighbors([[1., 1., 1.]]))
        (array([[0.5]]), array([[2]]))

        As you can see, it returns [[0.5]], and [[2]], which means that the
        element is at distance 0.5 and is the third element of samples
        (indexes start at 0). You can also query for multiple points:

        >>> X = [[0., 1., 0.], [1., 0., 1.]]
        >>> neigh.kneighbors(X, return_distance=False)
        array([[1],
               [2]]...)
        Nr   z Expected n_neighbors > 0. Got %dz7n_neighbors does not take %s value, enter integer valuer   Tr$   r   rY   Fr   r   rn   resetr   zn_neighbors < n_samples_fitzn_neighbors <= n_samples_fitz	Expected z, but n_neighbors = z, n_samples_fit = z, n_samples = r<   r   )rg   Yr   r   metric_kwargsstrategyr   )r   r   r   squaredreduce_funcr   r   r:   r;   Q%s does not work with sparse matrices. Densify the data, or set algorithm='brute'threadspreferc              3   r   K   | ].  } t        j                  j                        |          0 y wr   )r    r   query).0srg   r   r   r   s     rV   	<genexpr>z-KNeighborsMixin.kneighbors.<locals>.<genexpr>  s8      A<A *

(()!A$_M<s   47$internal: _fit_method not recognizedrE   )'r"   r   r}   r   numbersr   rq   typer   r   r   r   r   rt   r#   r   r_   r   r   r   r   is_usable_forr   computer   r
   r   r   r  listr   r   r   r   rH   vstackr   allr   )r   rg   r   r   r   query_is_trainn_samples_fitinequality_strr   chunked_results!use_pairwise_distances_reductionsresultsr  kwdsr   r   	n_queries_r  sample_maskdup_gr_nbrss   ````                 rV   
kneighborszKNeighborsMixin.kneighbors  s   h 	**KA?+MNNK)9)9:I{#$ 
 ,4D>+D+D+N+NKTXdA 1K{{m+&q)!&7"' ++&q !>!?N+ ,!!,-? O wwqzl,  "$++.' %%]T[[$BXBX 	* -oo++--";; /G 'DKK=,HXVW[,{OG ( ",,' /K %%4!4(44"*KK !,11! 	O !99{ /151A1AB  Ahvi@ A(V<A O
 CDD&(+_(=%
I))J/91EE))O4N
 (/%
I#	77LIq99Y/48L#|3K &&15K-2K1k*

9[#9I{UV;WXIZZ{+iq-I
 "9,,re   c                    t        |        || j                  }|dk(  r<| j                  ||d      }|j                  d   }t	        j
                  ||z        }nA|dk(  r-| j                  ||d      \  }}t	        j                  |      }nt        d| d      |j                  d   }| j                  }||z  }t	        j                  d|d	z   |      }	t        ||j                         |	f||f
      }
|
S )a  Compute the (weighted) graph of k-Neighbors for points in X.

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_queries, n_features),             or (n_queries, n_indexed) if metric == 'precomputed', default=None
            The query point or points.
            If not provided, neighbors of each indexed point are returned.
            In this case, the query point is not considered its own neighbor.
            For ``metric='precomputed'`` the shape should be
            (n_queries, n_indexed). Otherwise the shape should be
            (n_queries, n_features).

        n_neighbors : int, default=None
            Number of neighbors for each sample. The default is the value
            passed to the constructor.

        mode : {'connectivity', 'distance'}, default='connectivity'
            Type of returned matrix: 'connectivity' will return the
            connectivity matrix with ones and zeros, in 'distance' the
            edges are distances between points, type of distance
            depends on the selected metric parameter in
            NearestNeighbors class.

        Returns
        -------
        A : sparse-matrix of shape (n_queries, n_samples_fit)
            `n_samples_fit` is the number of samples in the fitted data.
            `A[i, j]` gives the weight of the edge connecting `i` to `j`.
            The matrix is of CSR format.

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

        Examples
        --------
        >>> X = [[0], [3], [1]]
        >>> from sklearn.neighbors import NearestNeighbors
        >>> neigh = NearestNeighbors(n_neighbors=2)
        >>> neigh.fit(X)
        NearestNeighbors(n_neighbors=2)
        >>> A = neigh.kneighbors_graph(X)
        >>> A.toarray()
        array([[1., 0., 1.],
               [0., 1., 1.],
               [1., 0., 1.]])
        connectivityFr   r   rA   THUnsupported mode, must be one of "connectivity", or "distance" but got "	" insteadr$   r_   )r"   r   r/  r_   rH   onesr   r}   r   r   r	   )r   rg   r   r   A_indr+  A_datar%  	n_nonzeroA_indptrkneighbors_graphs              rV   r;  z KNeighborsMixin.kneighbors_graph  s   d 	**K
 >!OOA{EOJEAIWWY45FZ OOA{DOQMFEXXf%F **.y: 
 KKN	+++	99Q	A{;%U[[]H-i5O
  re   )NNT)NNr1  )r   r   r   r   r  r/  r;   re   rV   r  r    s    )'RJXQ re   r  c                   <     e Zd ZdZd Z	 ddZ	 ddZ fdZ xZS )RadiusNeighborsMixinz*Mixin for radius-based neighbors searches.c           	      ^   |D cg c]  }t        j                  ||k        d    }}|ro| j                  dk(  r7t        |      D cg c]   \  }}t        j                  |||            " }}}n#t        |      D cg c]  \  }}|||       }}}||f}|S |}|S c c}w c c}}w c c}}w )a  Reduce a chunk of distances to the nearest neighbors.

        Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked`

        Parameters
        ----------
        dist : ndarray of shape (n_samples_chunk, n_samples)
            The distance matrix.

        start : int
            The index in X which the first row of dist corresponds to.

        radius : float
            The radius considered when making the nearest neighbors search.

        return_distance : bool
            Whether or not to return the distances.

        Returns
        -------
        dist : list of ndarray of shape (n_samples_chunk,)
            Returned only if `return_distance=True`.

        neigh : list of ndarray of shape (n_samples_chunk,)
            The neighbors indices.
        r   r   )rH   wherer   rJ   r  )	r   rP   r   r   r   dr   ir)  s	            rV   _radius_neighbors_reduce_funcz2RadiusNeighborsMixin._radius_neighbors_reduce_func  s    6 8<<t!RXXa6k*1-t	<%%4=Ft_M_TQ)A,0_M4=dODODAq)A,ODIoG   G = NDs   "B%B#?B)c           
      p   t        |        rst        d      t        |       j                  j                  rdnd}du }|r| j
                  n,| j                  dk(  rt              nt        | |ddd	      | j                  | j                  d
k(  xr9 t        j                  n| j
                  | j
                  | j                        }|r=t        j                  | j
                  | j                  | j                  d      }n[| j                  d
k(  r*| j                  dk(  rt!              rt#              }n"| j                  d
k(  r| j                  dk(  r
z  ddi}	n| j                  }	t%        | j&                        }
t)        | j
                  f|
| j                  | j*                  d|	}r>t-        | \  }}t/        |g       }t/        |g       }t1        |      }t1        |      }||f}nt/        |g       }t1        |      }rLt3        t5                    D ]2  }t7        j8                  ||   d      }|   |   ||<   ||   |   ||<   4 |f}n| j                  dv rt!              rt        d| j                  z        t;        | j*                        }t=        | j>                  j@                         tC        |d      fdtE        jF                  d   |      D              }r?tI        t-        |       \  }}t7        jJ                  |      t7        jJ                  |      f}n!t7        jJ                  |      }nt        d      |s|S r|\  }}n|}tM        |      D ]   \  }}||k7  }||   ||<   s|   |   ||<   " r|fS |S )a  Find the neighbors within a given radius of a point or points.

        Return the indices and distances of each point from the dataset
        lying in a ball with size ``radius`` around the points of the query
        array. Points lying on the boundary are included in the results.

        The result points are *not* necessarily sorted by distance to their
        query point.

        Parameters
        ----------
        X : {array-like, sparse matrix} of (n_samples, n_features), default=None
            The query point or points.
            If not provided, neighbors of each indexed point are returned.
            In this case, the query point is not considered its own neighbor.

        radius : float, default=None
            Limiting distance of neighbors to return. The default is the value
            passed to the constructor.

        return_distance : bool, default=True
            Whether or not to return the distances.

        sort_results : bool, default=False
            If True, the distances and indices will be sorted by increasing
            distances before being returned. If False, the results may not
            be sorted. If `return_distance=False`, setting `sort_results=True`
            will result in an error.

            .. versionadded:: 0.22

        Returns
        -------
        neigh_dist : ndarray of shape (n_samples,) of arrays
            Array representing the distances to each point, only present if
            `return_distance=True`. The distance values are computed according
            to the ``metric`` constructor parameter.

        neigh_ind : ndarray of shape (n_samples,) of arrays
            An array of arrays of indices of the approximate nearest points
            from the population matrix that lie within a ball of size
            ``radius`` around the query points.

        Notes
        -----
        Because the number of neighbors of each point is not necessarily
        equal, the results for multiple query points cannot be fit in a
        standard data array.
        For efficiency, `radius_neighbors` returns arrays of objects, where
        each object is a 1D array of indices or distances.

        Examples
        --------
        In the following example, we construct a NeighborsClassifier
        class from an array representing our data set and ask who's
        the closest point to [1, 1, 1]:

        >>> import numpy as np
        >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]
        >>> from sklearn.neighbors import NearestNeighbors
        >>> neigh = NearestNeighbors(radius=1.6)
        >>> neigh.fit(samples)
        NearestNeighbors(radius=1.6)
        >>> rng = neigh.radius_neighbors([[1., 1., 1.]])
        >>> print(np.asarray(rng[0][0]))
        [1.5 0.5]
        >>> print(np.asarray(rng[1][0]))
        [1 2]

        The first array returned contains the distances to all points which
        are closer than 1.6, while the second array returned contains their
        indices.  In general, multiple points can be queried at the same time.
        z5return_distance must be True if sort_results is True.r   TNr   rY   Fr   r
  r<   r   )rg   r  r   r   r  r  r   sort_results)r   r   r   r  r  rx   ry   r  r  r  r  c              3   <   K   | ]  } |            yw))rE  Nr<  )r  r  rg   delayed_queryr   r   rE  s     rV   r  z8RadiusNeighborsMixin.radius_neighbors.<locals>.<genexpr>  s,      A<A adFO,WW<s   r   r  )'r"   r}   r   r   r   r   r   rt   r#   r   r   r   r  r   r   r   r
   r   r   rC  r   r   r   r`   r!   r   lenrH   r   r   r    r   query_radiusr   r   r_   tuplehstackrJ   )r   rg   r   r   rE  r   r$  r(  r)  r*  r  r'  neigh_dist_chunksneigh_ind_chunksneigh_dist_listneigh_ind_listr   r   iir   r   indind_neighborr   rG  s    ````                   @rV   radius_neighborsz%RadiusNeighborsMixin.radius_neighborsD  s   X 	TUU+3D>+D+D+N+NKTXdA{{m+&q)!&7"' >[[F ' --]T[[$BXBX 	* -%--++--";; /)	G 'DKK=,HXVW[2&/G ( %%4& !4(44!22 /K 9 (--{{ O 69?6K3!#3"%&7"<!$%5r!:-o>
,^<	$i/!$_b!9*>:J0BJJz"~KHE$-bM%$8IbM%/^E%:JrN 1 %i/!99{ /151A1AB 
 &dkk2F#DJJ$;$;<M@hvi@ A(V<A O (-c?.C(D%	:))J/91EE))O4CDDN
 (/%
I#	%.y%9!\#s*!-d!3	#"&0od&;JsO &: !9,,re   c                    t        |        || j                  }|dk(  r| j                  ||d      }d}nK|dk(  r7| j                  ||d|      \  }}t        j                  t        |            }nt        d| d	      |j                  d
   }| j                  }	t        j                  |D 
cg c]  }
t        |
       c}
      }t        j                  t        |            }|t        j                  t        |            }t        j                  t        j                  dt              t        j                  |      f      }t        |||f||	f      S c c}
w )a)  Compute the (weighted) graph of Neighbors for points in X.

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

        Parameters
        ----------
        X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None
            The query point or points.
            If not provided, neighbors of each indexed point are returned.
            In this case, the query point is not considered its own neighbor.

        radius : float, default=None
            Radius of neighborhoods. The default is the value passed to the
            constructor.

        mode : {'connectivity', 'distance'}, default='connectivity'
            Type of returned matrix: 'connectivity' will return the
            connectivity matrix with ones and zeros, in 'distance' the
            edges are distances between points, type of distance
            depends on the selected metric parameter in
            NearestNeighbors class.

        sort_results : bool, default=False
            If True, in each row of the result, the non-zero entries will be
            sorted by increasing distances. If False, the non-zero entries may
            not be sorted. Only used with mode='distance'.

            .. versionadded:: 0.22

        Returns
        -------
        A : sparse-matrix of shape (n_queries, n_samples_fit)
            `n_samples_fit` is the number of samples in the fitted data.
            `A[i, j]` gives the weight of the edge connecting `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 NearestNeighbors
        >>> neigh = NearestNeighbors(radius=1.5)
        >>> neigh.fit(X)
        NearestNeighbors(radius=1.5)
        >>> A = neigh.radius_neighbors_graph(X)
        >>> A.toarray()
        array([[1., 0., 1.],
               [0., 1., 0.],
               [1., 0., 1.]])
        Nr1  Fr2  rA   T)r   rE  r3  r4  r   r$   r   r5  )r"   r   rS  rH   r   r!  r}   r_   r   arrayrH  r6  zerosintr   r	   )r   rg   r   r   rE  r7  r8  rP   r+  r%  r   r   r:  s                rV   radius_neighbors_graphz+RadiusNeighborsMixin.radius_neighbors_graph  sH   t 	 >[[F >!))!VU)KEFZ//64l 0 KD% ^^DJ/F**.y: 
 KKN	++hh61A67tE{+>WWSZ(F>>288AS#9299[;Q"RS65(3I};UVV  7s   /Ec                 `    t         |          }| j                  dk(  |j                  _        |S )Nr>   )r   r   r   r   r   r   s     rV   r   z%RadiusNeighborsMixin.__sklearn_tags__x  s*    w')$(KK?$B!re   )NNTF)NNr1  F)	r   r   r   r   rC  rS  rX  r   r   r   s   @rV   r>  r>    s3    4%P GLXv FKXWt re   r>  )FT)Kr   r   r  r{   abcr   r   	functoolsr   r   r   numpyrH   joblibr   scipy.sparser	   r
   baser   r   r   
exceptionsr   r   metricsr   r   %metrics._pairwise_distances_reductionr   r   metrics.pairwiser   utilsr   r   r   utils._param_validationr   r   r   utils.fixesr   r   utils.multiclassr   utils.parallelr   r    utils.validationr!   r"   r#   
_ball_treer%   _kd_treer&   SCIPY_METRICSr   valid_metricssortedr   unionr   keysr   rW   rd   rt   rr   r   r   r   r  r>  r<  re   rV   <module>rq     s   3
    '  "  # - A A A @ ; 
 L K 8 ; . O O   $ ]6**o&&M]6**k]"M]5))j\!M$$   0177F
G +&++-o0NN +\A6&R !"!*
 #'XXv1&h-`A$mw AH
I  I X
a are   