B
    vd2                @   s  d dl Z d dlmZ d dlZd dlZd dl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 ddlmZ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! ddl"m#Z#m$Z$ ddl%m&Z& dd Z'ddddddddZ(dd Z)ddddd d!d"Z*dd#d$Z+ddej,dd%d&d'Z-dd(d)Z.d*d+ Z/dd,dd-d.d/Z0dd,dd-d0d1Z1dd2d3Z2ddd4d5d6Z3dd7d8Z4d9d: Z5d;d< Z6d=d> Z7e7e5e5e6e6e6d?Z8d,d@dAdBZ9ddCdDZ:ddFdGZ;ddHdIZ<ddJdKZ=ddLdMZ>ddNdOZ?ddPdQZ@ddSdTZAe3e4e*e2e*e3e3de-dU	ZBdVdW ZCdXdY ZDdZd[ ZEdd\d]ZFd,d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwgZGdvgZHdxdy ZIddzd{ZJddd,ddd|d}d~ZKddddddZLdgdidjdldndodqdrdtg	ZMe@eAe:e;e;e=e>e<e?d	ZNdd ZOdePdgddePdddgePdddgePdgePdgePddgd	ZQddddddZRdS )    N)partial)distance)
csr_matrix)issparse)Paralleleffective_n_jobs   )_num_samples)check_non_negative)check_array)gen_even_slices)gen_batchesget_chunk_n_rows)is_scalar_nan)	row_normssafe_sparse_dot)	normalize)	_get_mask)delayed)
sp_versionparse_version   )_chi2_kernel_fast_sparse_manhattan)DataConversionWarningc             C   s   t | st| tjst| } |dkr.| j}n,t |sTt|tjsTt|}|j}n|j}| j|  krrtjkr~n ntj}nt}| ||fS )zq
    1. If dtype of X and Y is float32, then dtype float32 is returned.
    2. Else dtype float is returned.
    N)r   
isinstancenpZndarrayZasarraydtypefloat32float)XYZY_dtyper    r"   e/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/sklearn/metrics/pairwise.py_return_float_dtype'   s    

r$   FZcsrT)precomputedr   accept_sparseforce_all_finitecopyc      	      C   s   t | |\} }}d}|dkr |}|| ks0|dkrJt| |||||d } }n(t| |||||d} t||||||d}|r| jd |jd krtd| jd | jd |jd f n0| jd |jd krtd| jd |jd f | |fS )az
  Set X and Y appropriately and checks inputs.

    If Y is None, it is set as a pointer to X (i.e. not a copy).
    If Y is given, this does not happen.
    All distance metrics should use this function first to assert that the
    given parameters are correct and safe to use.

    Specifically, this function first ensures that both X and Y are arrays,
    then checks that they are at least two dimensional while ensuring that
    their elements are floats (or dtype if provided). Finally, the function
    checks that the size of the second dimension of the two arrays is equal, or
    the equivalent check for a precomputed distance matrix.

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples_X, n_features)

    Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)

    precomputed : bool, default=False
        True if X is to be treated as precomputed distances to the samples in
        Y.

    dtype : str, type, list of type, default=None
        Data type required for X and Y. If None, the dtype will be an
        appropriate float type selected by _return_float_dtype.

        .. versionadded:: 0.18

    accept_sparse : str, bool or list/tuple of str, default='csr'
        String[s] representing allowed sparse matrix formats, such as 'csc',
        'csr', etc. If the input is sparse but not in the allowed format,
        it will be converted to the first listed format. True allows the input
        to be any format. False means that a sparse matrix input will
        raise an error.

    force_all_finite : bool or 'allow-nan', default=True
        Whether to raise an error on np.inf, np.nan, pd.NA in array. The
        possibilities are:

        - True: Force all values of array to be finite.
        - False: accepts np.inf, np.nan, pd.NA in array.
        - 'allow-nan': accepts only np.nan and pd.NA values in array. Values
          cannot be infinite.

        .. versionadded:: 0.22
           ``force_all_finite`` accepts the string ``'allow-nan'``.

        .. versionchanged:: 0.23
           Accepts `pd.NA` and converts it into `np.nan`.

    copy : bool, default=False
        Whether a forced copy will be triggered. If copy=False, a copy might
        be triggered by a conversion.

        .. versionadded:: 0.22

    Returns
    -------
    safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
        An array equal to X, guaranteed to be a numpy array.

    safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
        An array equal to Y if Y was not None, guaranteed to be a numpy array.
        If Y was None, safe_Y will be a pointer to X.

    check_pairwise_arraysN)r&   r   r(   r'   	estimatorr   r   zVPrecomputed metric requires shape (n_queries, n_indexed). Got (%d, %d) for %d indexed.zTIncompatible dimension for X and Y matrices: X.shape[1] == %d while Y.shape[1] == %d)r$   r   shape
ValueError)	r    r!   r%   r   r&   r'   r(   Zdtype_floatr*   r"   r"   r#   r)   ?   sH    M"r)   c             C   s6   t | |\} }| j|jkr.td| j|jf | |fS )a  Set X and Y appropriately and checks inputs for paired distances.

    All paired distance metrics should use this function first to assert that
    the given parameters are correct and safe to use.

    Specifically, this function first ensures that both X and Y are arrays,
    then checks that they are at least two dimensional while ensuring that
    their elements are floats. Finally, the function checks that the size
    of the dimensions of the two arrays are equal.

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples_X, n_features)

    Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)

    Returns
    -------
    safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
        An array equal to X, guaranteed to be a numpy array.

    safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
        An array equal to Y if Y was not None, guaranteed to be a numpy array.
        If Y was None, safe_Y will be a pointer to X.

    zGX and Y should be of same shape. They were respectively %r and %r long.)r)   r+   r,   )r    r!   r"   r"   r#   check_paired_arrays   s    r-   )Y_norm_squaredsquaredX_norm_squaredc            C   s  t | |\} }|dk	rt|dd}|j}|j| jd fkrF|dd}|jd| jd fkr`|j}|j| jd dfkrtd| j d| d	|dk	rt|dd}|j}|j|jd fkr|dd}|j|jd dfkr|j}|jd|jd fkrtd
|j d| d	t| ||||S )u
  
    Compute the distance matrix between each pair from a vector array X and Y.

    For efficiency reasons, the euclidean distance between a pair of row
    vector x and y is computed as::

        dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y))

    This formulation has two advantages over other ways of computing distances.
    First, it is computationally efficient when dealing with sparse data.
    Second, if one argument varies but the other remains unchanged, then
    `dot(x, x)` and/or `dot(y, y)` can be pre-computed.

    However, this is not the most precise way of doing this computation,
    because this equation potentially suffers from "catastrophic cancellation".
    Also, the distance matrix returned by this function may not be exactly
    symmetric as required by, e.g., ``scipy.spatial.distance`` functions.

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

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
        An array where each row is a sample and each column is a feature.

    Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features),             default=None
        An array where each row is a sample and each column is a feature.
        If `None`, method uses `Y=X`.

    Y_norm_squared : array-like of shape (n_samples_Y,) or (n_samples_Y, 1)             or (1, n_samples_Y), default=None
        Pre-computed dot-products of vectors in Y (e.g.,
        ``(Y**2).sum(axis=1)``)
        May be ignored in some cases, see the note below.

    squared : bool, default=False
        Return squared Euclidean distances.

    X_norm_squared : array-like of shape (n_samples_X,) or (n_samples_X, 1)             or (1, n_samples_X), default=None
        Pre-computed dot-products of vectors in X (e.g.,
        ``(X**2).sum(axis=1)``)
        May be ignored in some cases, see the note below.

    Returns
    -------
    distances : ndarray of shape (n_samples_X, n_samples_Y)
        Returns the distances between the row vectors of `X`
        and the row vectors of `Y`.

    See Also
    --------
    paired_distances : Distances betweens pairs of elements of X and Y.

    Notes
    -----
    To achieve a better accuracy, `X_norm_squared` and `Y_norm_squared` may be
    unused if they are passed as `np.float32`.

    Examples
    --------
    >>> from sklearn.metrics.pairwise import euclidean_distances
    >>> X = [[0, 1], [1, 1]]
    >>> # distance between rows of X
    >>> euclidean_distances(X, X)
    array([[0., 1.],
           [1., 0.]])
    >>> # get distance to origin
    >>> euclidean_distances(X, [[0, 0]])
    array([[1.        ],
           [1.41421356]])
    NF)Z	ensure_2dr   r   z'Incompatible dimensions for X of shape z and X_norm_squared of shape .z'Incompatible dimensions for Y of shape z and Y_norm_squared of shape )r)   r   r+   reshapeTr,   _euclidean_distances)r    r!   r.   r/   r0   Zoriginal_shaper"   r"   r#   euclidean_distances   s,    L
r6   c             C   sB  |dk	r(|j tjkrd}qT|dd}n,| j tjkr:d}nt| ddddtjf }|| krp|dkrhdn|j}nT|dk	r|j tjkrd}q|dd}n,|j tjkrd}nt|ddtjddf }| j tjkrt| |||}n$dt| |jdd }||7 }||7 }tj	|d|d	 | |kr*t
|d |r4|S tj||d	S )
a'  Computational part of euclidean_distances

    Assumes inputs are already checked.

    If norms are passed as float32, they are unused. If arrays are passed as
    float32, norms needs to be recomputed on upcast chunks.
    TODO: use a float64 accumulator in row_norms to avoid the latter.
    Nr1   r   T)r/   )dense_outputr   )out)r   r   r   r3   r   newaxisr4   _euclidean_distances_upcastr   maximumfill_diagonalsqrt)r    r!   r0   r.   r/   XXYY	distancesr"   r"   r#   r5   M  s2    	
r5   )r/   missing_valuesr(   c            C   s2  t |rdnd}t| |d||d\} }t| |}|| kr<|nt||}d| |< d||< t| |dd}| |  }	|| }
|t|	|j8 }|t||
j8 }tj|dd|d | |krt|d	 d
| }|| kr|n| }t||j}tj	||dk< tj
d
||d || }|| jd
 9 }|s.tj||d |S )a  Calculate the euclidean distances in the presence of missing values.

    Compute the euclidean distance between each pair of samples in X and Y,
    where Y=X is assumed if Y=None. When calculating the distance between a
    pair of samples, this formulation ignores feature coordinates with a
    missing value in either sample and scales up the weight of the remaining
    coordinates:

        dist(x,y) = sqrt(weight * sq. distance from present coordinates)
        where,
        weight = Total # of coordinates / # of present coordinates

    For example, the distance between ``[3, na, na, 6]`` and ``[1, na, 4, 5]``
    is:

        .. math::
            \sqrt{\frac{4}{2}((3-1)^2 + (6-5)^2)}

    If all the coordinates are missing or if there are no common present
    coordinates then NaN is returned for that pair.

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

    .. versionadded:: 0.22

    Parameters
    ----------
    X : array-like of shape=(n_samples_X, n_features)

    Y : array-like of shape=(n_samples_Y, n_features), default=None

    squared : bool, default=False
        Return squared Euclidean distances.

    missing_values : np.nan or int, default=np.nan
        Representation of missing value.

    copy : bool, default=True
        Make and use a deep copy of X and Y (if Y exists).

    Returns
    -------
    distances : ndarray of shape (n_samples_X, n_samples_Y)

    See Also
    --------
    paired_distances : Distances between pairs of elements of X and Y.

    Examples
    --------
    >>> from sklearn.metrics.pairwise import nan_euclidean_distances
    >>> nan = float("NaN")
    >>> X = [[0, 1], [1, nan]]
    >>> nan_euclidean_distances(X, X) # distance between rows of X
    array([[0.        , 1.41421356],
           [1.41421356, 0.        ]])

    >>> # get distance to origin
    >>> nan_euclidean_distances(X, [[0, 0]])
    array([[1.        ],
           [1.41421356]])

    References
    ----------
    * John K. Dixon, "Pattern Recognition with Partly Missing Data",
      IEEE Transactions on Systems, Man, and Cybernetics, Volume: 9, Issue:
      10, pp. 617 - 621, Oct. 1979.
      http://ieeexplore.ieee.org/abstract/document/4310090/
    z	allow-nanTF)r&   r'   r(   r   )r/   N)r9   g        r   )r   r)   r   r6   r   dotr4   clipr=   nanr<   r+   r>   )r    r!   r/   rB   r(   r'   Z	missing_XZ	missing_YrA   r?   r@   Z	present_XZ	present_YZpresent_countr"   r"   r#   nan_euclidean_distances  s2    I
rF   c             C   s  | j d }|j d }| j d }tj||ftjd}|dkrt| rT| jt| j  nd}	t|rr|jt|j  nd}
t|	| |
|  | |	| |
 |  d d}|	|
 | }| t|d d|   d }tt	|d}t
||}xt|D ]\}}| | tj}|dkr4t|d	d
ddtjf }n|| }t
||}xt|D ]\}}| |kr|||k r||||f j}nj|| tj}|dkrt|d	d
tjddf }n|dd|f }dt||jd	d }||7 }||7 }|jtjdd|||f< qPW qW |S )a  Euclidean distances between X and Y.

    Assumes X and Y have float32 dtype.
    Assumes XX and YY have float64 dtype or are None.

    X and Y are upcast to float64 by chunks, which size is chosen to limit
    memory increase by approximately 10% (at least 10MiB).
    r   r   )r   N
   i   r      T)r/   r7   )r8   F)r(   )r+   r   emptyr   r   Znnzprodmaxr>   intr   	enumerateZastypefloat64r   r:   r4   r   )r    r?   r!   r@   Z
batch_sizen_samples_XZn_samples_YZ
n_featuresrA   Z	x_densityZ	y_densityZmaxmemtmpZ	x_batchesiZx_sliceX_chunkZXX_chunkZ	y_batchesjZy_slicedZY_chunkZYY_chunkr"   r"   r#   r;     sD    	


	 



"r;   c             C   s,   | j dd}| t| jd |f }||fS )Nr   )axisr   )Zargminr   Zaranger+   )diststartindicesvaluesr"   r"   r#   _argmin_min_reduce>  s    rZ   	euclidean)rU   metricmetric_kwargsc            C   sh   t | |\} }|dkri }|dkr,||  } }tt| |ft|d| \}}t|}t|}||fS )ae	  Compute minimum distances between one point and a set of points.

    This function computes for each row in X, the index of the row of Y which
    is closest (according to the specified distance). The minimal distances are
    also returned.

    This is mostly equivalent to calling:

        (pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis),
         pairwise_distances(X, Y=Y, metric=metric).min(axis=axis))

    but uses much less memory, and is faster for large arrays.

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
        Array containing points.

    Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features)
        Array containing points.

    axis : int, default=1
        Axis along which the argmin and distances are to be computed.

    metric : str or callable, default='euclidean'
        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.

        Distance matrices are not supported.

        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.

    metric_kwargs : dict, default=None
        Keyword arguments to pass to specified metric function.

    Returns
    -------
    argmin : ndarray
        Y[argmin[i], :] is the row in Y that is closest to X[i, :].

    distances : ndarray
        distances[i] is the distance between the i-th row in X and the
        argmin[i]-th row in Y.

    See Also
    --------
    sklearn.metrics.pairwise_distances
    sklearn.metrics.pairwise_distances_argmin
    Nr   )reduce_funcr\   )r)   zippairwise_distances_chunkedrZ   r   Zconcatenate)r    r!   rU   r\   r]   rX   rY   r"   r"   r#   pairwise_distances_argmin_minD  s    F


ra   c            C   s"   |dkri }t | ||||dd S )a  Compute minimum distances between one point and a set of points.

    This function computes for each row in X, the index of the row of Y which
    is closest (according to the specified distance).

    This is mostly equivalent to calling:

        pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis)

    but uses much less memory, and is faster for large arrays.

    This function works with dense 2D arrays only.

    Parameters
    ----------
    X : array-like of shape (n_samples_X, n_features)
        Array containing points.

    Y : array-like of shape (n_samples_Y, n_features)
        Arrays containing points.

    axis : int, default=1
        Axis along which the argmin and distances are to be computed.

    metric : str or callable, default="euclidean"
        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.

        Distance matrices are not supported.

        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.

    metric_kwargs : dict, default=None
        Keyword arguments to pass to specified metric function.

    Returns
    -------
    argmin : numpy.ndarray
        Y[argmin[i], :] is the row in Y that is closest to X[i, :].

    See Also
    --------
    sklearn.metrics.pairwise_distances
    sklearn.metrics.pairwise_distances_argmin_min
    N)rU   r\   r]   r   )ra   )r    r!   rU   r\   r]   r"   r"   r#   pairwise_distances_argmin  s
    @rb   c             C   s   ddl m} |d| |S )a_  Compute the Haversine distance between samples in X and Y.

    The Haversine (or great circle) distance is the angular distance between
    two points on the surface of a sphere. The first coordinate of each point
    is assumed to be the latitude, the second is the longitude, given
    in radians. The dimension of the data must be 2.

    .. math::
       D(x, y) = 2\arcsin[\sqrt{\sin^2((x1 - y1) / 2)
                                + \cos(x1)\cos(y1)\sin^2((x2 - y2) / 2)}]

    Parameters
    ----------
    X : array-like of shape (n_samples_X, 2)

    Y : array-like of shape (n_samples_Y, 2), default=None

    Returns
    -------
    distance : ndarray of shape (n_samples_X, n_samples_Y)

    Notes
    -----
    As the Earth is nearly spherical, the haversine formula provides a good
    approximation of the distance between two points of the Earth surface, with
    a less than 1% error on average.

    Examples
    --------
    We want to calculate the distance between the Ezeiza Airport
    (Buenos Aires, Argentina) and the Charles de Gaulle Airport (Paris,
    France).

    >>> from sklearn.metrics.pairwise import haversine_distances
    >>> from math import radians
    >>> bsas = [-34.83333, -58.5166646]
    >>> paris = [49.0083899664, 2.53844117956]
    >>> bsas_in_radians = [radians(_) for _ in bsas]
    >>> paris_in_radians = [radians(_) for _ in paris]
    >>> result = haversine_distances([bsas_in_radians, paris_in_radians])
    >>> result * 6371000/1000  # multiply by Earth radius to get kilometers
    array([[    0.        , 11099.54035582],
           [11099.54035582,     0.        ]])
    r   )DistanceMetric	haversine)Zmetricsrc   Z
get_metricpairwise)r    r!   rc   r"   r"   r#   haversine_distances  s    -rf   )sum_over_featuresc            C   s   t | |\} }t| st|r|s.td| t| dd} t|dd}|   |  t| jd |jd f}t| j	| j
| j|j	|j
|j| |S |rt| |dS | ddtjddf |tjddddf  }t||}|d| jd fS )	a  Compute the L1 distances between the vectors in X and Y.

    With sum_over_features equal to False it returns the componentwise
    distances.

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

    Parameters
    ----------
    X : array-like of shape (n_samples_X, n_features)

    Y : array-like of shape (n_samples_Y, n_features), default=None
        If `None`, uses `Y=X`.

    sum_over_features : bool, default=True
        If True the function returns the pairwise distance matrix
        else it returns the componentwise L1 pairwise-distances.
        Not supported for sparse matrix inputs.

    Returns
    -------
    D : ndarray of shape (n_samples_X * n_samples_Y, n_features) or             (n_samples_X, n_samples_Y)
        If sum_over_features is False shape is
        (n_samples_X * n_samples_Y, n_features) and D contains the
        componentwise L1 pairwise-distances (ie. absolute difference),
        else shape is (n_samples_X, n_samples_Y) and D contains
        the pairwise L1 distances.

    Notes
    --------
    When X and/or Y are CSR sparse matrices and they are not already
    in canonical format, this function modifies them in-place to
    make them canonical.

    Examples
    --------
    >>> from sklearn.metrics.pairwise import manhattan_distances
    >>> manhattan_distances([[3]], [[3]])
    array([[0.]])
    >>> manhattan_distances([[3]], [[2]])
    array([[1.]])
    >>> manhattan_distances([[2]], [[3]])
    array([[1.]])
    >>> manhattan_distances([[1, 2], [3, 4]],         [[1, 2], [0, 3]])
    array([[0., 2.],
           [4., 4.]])
    >>> import numpy as np
    >>> X = np.ones((1, 2))
    >>> y = np.full((2, 2), 2.)
    >>> manhattan_distances(X, y, sum_over_features=False)
    array([[1., 1.],
           [1., 1.]])
    z6sum_over_features=%r not supported for sparse matricesF)r(   r   	cityblockNr1   r   )r)   r   	TypeErrorr   Zsum_duplicatesr   zerosr+   r   datarX   Zindptrr   cdistr:   absr3   )r    r!   rg   Dr"   r"   r#   manhattan_distances  s$    8 0ro   c             C   sN   t | |}|d9 }|d7 }tj|dd|d | |ks<|dkrJd|t|< |S )ad  Compute cosine distance between samples in X and Y.

    Cosine distance is defined as 1.0 minus the cosine similarity.

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

    Parameters
    ----------
    X : {array-like, sparse matrix} of shape (n_samples_X, n_features)
        Matrix `X`.

    Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features),             default=None
        Matrix `Y`.

    Returns
    -------
    distance matrix : ndarray of shape (n_samples_X, n_samples_Y)

    See Also
    --------
    cosine_similarity
    scipy.spatial.distance.cosine : Dense matrices only.
    r1   r   r   r   )r9   Ng        )cosine_similarityr   rD   Zdiag_indices_from)r    r!   Sr"   r"   r#   cosine_distancesh  s    
rr   c             C   s   t | |\} }t| | S )aD  
    Computes the paired euclidean distances between X and Y.

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

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

    Y : array-like of shape (n_samples, n_features)

    Returns
    -------
    distances : ndarray of shape (n_samples,)
    )r-   r   )r    r!   r"   r"   r#   paired_euclidean_distances  s    rs   c             C   sZ   t | |\} }| | }t|rDt|j|_tt|jddS t|jddS dS )a?  Compute the L1 distances between the vectors in X and Y.

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

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

    Y : array-like of shape (n_samples, n_features)

    Returns
    -------
    distances : ndarray of shape (n_samples,)
    r   )rU   r1   N)r-   r   r   rm   rk   Zsqueezearraysum)r    r!   diffr"   r"   r#   paired_manhattan_distances  s    rw   c             C   s*   t | |\} }dtt| t| dd S )a  
    Computes the paired cosine distances between X and Y.

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

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

    Y : array-like of shape (n_samples, n_features)

    Returns
    -------
    distances : ndarray of shape (n_samples,)

    Notes
    -----
    The cosine distance is equivalent to the half the squared
    euclidean distance if each sample is normalized to unit norm.
    g      ?T)r/   )r-   r   r   )r    r!   r"   r"   r#   paired_cosine_distances  s    rx   )cosiner[   l2l1	manhattanrh   )r\   c            K   s~   |t krt | }|| |S t|rnt| |\} }tt| }x*tt| D ]}|| | || ||< qLW |S td| dS )a6  
    Computes the paired distances between X and Y.

    Computes the distances between (X[0], Y[0]), (X[1], Y[1]), etc...

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

    Parameters
    ----------
    X : ndarray of shape (n_samples, n_features)
        Array 1 for distance computation.

    Y : ndarray of shape (n_samples, n_features)
        Array 2 for distance computation.

    metric : str or callable, default="euclidean"
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string, it must be one of the options
        specified in PAIRED_DISTANCES, including "euclidean",
        "manhattan", or "cosine".
        Alternatively, 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 from X as input and return a value indicating
        the distance between them.

    Returns
    -------
    distances : ndarray of shape (n_samples,)

    See Also
    --------
    pairwise_distances : Computes the distance between every pair of samples.

    Examples
    --------
    >>> from sklearn.metrics.pairwise import paired_distances
    >>> X = [[0, 1], [1, 1]]
    >>> Y = [[0, 1], [2, 1]]
    >>> paired_distances(X, Y)
    array([0., 1.])
    zUnknown distance %sN)PAIRED_DISTANCEScallabler-   r   rj   lenranger,   )r    r!   r\   kwdsfuncrA   rQ   r"   r"   r#   paired_distances  s    +
r   c             C   s   t | |\} }t| |j|dS )a  
    Compute the linear kernel between X and Y.

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

    Parameters
    ----------
    X : ndarray of shape (n_samples_X, n_features)
        A feature array.

    Y : ndarray of shape (n_samples_Y, n_features), default=None
        An optional second feature array. If `None`, uses `Y=X`.

    dense_output : bool, default=True
        Whether to return dense output even when the input is sparse. If
        ``False``, the output is sparse if both input arrays are sparse.

        .. versionadded:: 0.20

    Returns
    -------
    Gram matrix : ndarray of shape (n_samples_X, n_samples_Y)
        The Gram matrix of the linear kernel, i.e. `X @ Y.T`.
    )r8   )r)   r   r4   )r    r!   r8   r"   r"   r#   linear_kernel  s    r      c             C   sP   t | |\} }|dkr$d| jd  }t| |jdd}||9 }||7 }||C }|S )a  
    Compute the polynomial kernel between X and Y::

        K(X, Y) = (gamma <X, Y> + coef0)^degree

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

    Parameters
    ----------
    X : ndarray of shape (n_samples_X, n_features)

    Y : ndarray of shape (n_samples_Y, n_features), default=None

    degree : int, default=3

    gamma : float, default=None
        If None, defaults to 1.0 / n_features.

    coef0 : float, default=1

    Returns
    -------
    Gram matrix : ndarray of shape (n_samples_X, n_samples_Y)
    Ng      ?r   T)r8   )r)   r+   r   r4   )r    r!   degreegammacoef0Kr"   r"   r#   polynomial_kernel4  s    r   c             C   sT   t | |\} }|dkr$d| jd  }t| |jdd}||9 }||7 }t|| |S )a  
    Compute the sigmoid kernel between X and Y::

        K(X, Y) = tanh(gamma <X, Y> + coef0)

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

    Parameters
    ----------
    X : ndarray of shape (n_samples_X, n_features)

    Y : ndarray of shape (n_samples_Y, n_features), default=None
        If `None`, uses `Y=X`.

    gamma : float, default=None
        If None, defaults to 1.0 / n_features.

    coef0 : float, default=1

    Returns
    -------
    Gram matrix : ndarray of shape (n_samples_X, n_samples_Y)
    Ng      ?r   T)r8   )r)   r+   r   r4   r   tanh)r    r!   r   r   r   r"   r"   r#   sigmoid_kernelX  s    r   c             C   sL   t | |\} }|dkr$d| jd  }t| |dd}|| 9 }t|| |S )a&  
    Compute the rbf (gaussian) kernel between X and Y::

        K(x, y) = exp(-gamma ||x-y||^2)

    for each pair of rows x in X and y in Y.

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

    Parameters
    ----------
    X : ndarray of shape (n_samples_X, n_features)

    Y : ndarray of shape (n_samples_Y, n_features), default=None
        If `None`, uses `Y=X`.

    gamma : float, default=None
        If None, defaults to 1.0 / n_features.

    Returns
    -------
    kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y)
    Ng      ?r   T)r/   )r)   r+   r6   r   exp)r    r!   r   r   r"   r"   r#   
rbf_kernel{  s    
r   c             C   sD   t | |\} }|dkr$d| jd  }| t| | }t|| |S )af  Compute the laplacian kernel between X and Y.

    The laplacian kernel is defined as::

        K(x, y) = exp(-gamma ||x-y||_1)

    for each pair of rows x in X and y in Y.
    Read more in the :ref:`User Guide <laplacian_kernel>`.

    .. versionadded:: 0.17

    Parameters
    ----------
    X : ndarray of shape (n_samples_X, n_features)

    Y : ndarray of shape (n_samples_Y, n_features), default=None
        If `None`, uses `Y=X`.

    gamma : float, default=None
        If None, defaults to 1.0 / n_features.

    Returns
    -------
    kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y)
    Ng      ?r   )r)   r+   ro   r   r   )r    r!   r   r   r"   r"   r#   laplacian_kernel  s    r   c             C   sH   t | |\} }t| dd}| |kr(|}nt|dd}t||j|d}|S )a  Compute cosine similarity between samples in X and Y.

    Cosine similarity, or the cosine kernel, computes similarity as the
    normalized dot product of X and Y:

        K(X, Y) = <X, Y> / (||X||*||Y||)

    On L2-normalized data, this function is equivalent to linear_kernel.

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

    Parameters
    ----------
    X : {ndarray, sparse matrix} of shape (n_samples_X, n_features)
        Input data.

    Y : {ndarray, sparse matrix} of shape (n_samples_Y, n_features),             default=None
        Input data. If ``None``, the output will be the pairwise
        similarities between all samples in ``X``.

    dense_output : bool, default=True
        Whether to return dense output even when the input is sparse. If
        ``False``, the output is sparse if both input arrays are sparse.

        .. versionadded:: 0.17
           parameter ``dense_output`` for dense output.

    Returns
    -------
    kernel matrix : ndarray of shape (n_samples_X, n_samples_Y)
    T)r(   )r8   )r)   r   r   r4   )r    r!   r8   ZX_normalizedZY_normalizedr   r"   r"   r#   rp     s    #rp   c             C   s   t | st |rtdt| |\} }| dk  r:td|| k	rV|dk  rVtdtj| jd |jd f| jd}t| || |S )a  Computes the additive chi-squared kernel between observations in X and
    Y.

    The chi-squared kernel is computed between each pair of rows in X and Y.  X
    and Y have to be non-negative. This kernel is most commonly applied to
    histograms.

    The chi-squared kernel is given by::

        k(x, y) = -Sum [(x - y)^2 / (x + y)]

    It can be interpreted as a weighted difference per entry.

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

    Notes
    -----
    As the negative of a distance, this kernel is only conditionally positive
    definite.


    Parameters
    ----------
    X : array-like of shape (n_samples_X, n_features)

    Y : ndarray of shape (n_samples_Y, n_features), default=None
        If `None`, uses `Y=X`.

    Returns
    -------
    kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y)

    See Also
    --------
    chi2_kernel : The exponentiated version of the kernel, which is usually
        preferable.
    sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation
        to this kernel.

    References
    ----------
    * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C.
      Local features and kernels for classification of texture and object
      categories: A comprehensive study
      International Journal of Computer Vision 2007
      https://research.microsoft.com/en-us/um/people/manik/projects/trade-off/papers/ZhangIJCV06.pdf
    z/additive_chi2 does not support sparse matrices.r   zX contains negative values.zY contains negative values.)r   )	r   r,   r)   anyr   rj   r+   r   r   )r    r!   resultr"   r"   r#   additive_chi2_kernel  s    0 r         ?c             C   s   t | |}||9 }t||S )aA  Computes the exponential chi-squared kernel X and Y.

    The chi-squared kernel is computed between each pair of rows in X and Y.  X
    and Y have to be non-negative. This kernel is most commonly applied to
    histograms.

    The chi-squared kernel is given by::

        k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)])

    It can be interpreted as a weighted difference per entry.

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

    Parameters
    ----------
    X : array-like of shape (n_samples_X, n_features)

    Y : ndarray of shape (n_samples_Y, n_features), default=None

    gamma : float, default=1.
        Scaling parameter of the chi2 kernel.

    Returns
    -------
    kernel_matrix : ndarray of shape (n_samples_X, n_samples_Y)

    See Also
    --------
    additive_chi2_kernel : The additive version of this kernel.
    sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation
        to the additive version of this kernel.

    References
    ----------
    * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C.
      Local features and kernels for classification of texture and object
      categories: A comprehensive study
      International Journal of Computer Vision 2007
      https://research.microsoft.com/en-us/um/people/manik/projects/trade-off/papers/ZhangIJCV06.pdf
    )r   r   r   )r    r!   r   r   r"   r"   r#   chi2_kernel-  s    *
r   )	rh   ry   r[   rd   rz   r{   r|   r%   nan_euclideanc               C   s   t S )a  Valid metrics for pairwise_distances.

    This function simply returns the valid pairwise distance metrics.
    It exists to allow for a description of the mapping for
    each of the valid strings.

    The valid distance metrics, and the function they map to, are:

    =============== ========================================
    metric          Function
    =============== ========================================
    'cityblock'     metrics.pairwise.manhattan_distances
    'cosine'        metrics.pairwise.cosine_distances
    'euclidean'     metrics.pairwise.euclidean_distances
    'haversine'     metrics.pairwise.haversine_distances
    'l1'            metrics.pairwise.manhattan_distances
    'l2'            metrics.pairwise.euclidean_distances
    'manhattan'     metrics.pairwise.manhattan_distances
    'nan_euclidean' metrics.pairwise.nan_euclidean_distances
    =============== ========================================

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

    )PAIRWISE_DISTANCE_FUNCTIONSr"   r"   r"   r#   distance_metricsl  s    r   c             O   s   | |||dd|f< dS )z/Write in-place to a slice of a distance matrix.Nr"   )Z	dist_funcZdist_matrixZslice_argskwargsr"   r"   r#   _dist_wrapper  s    r   c                s   dkr t  \ }t|dkr6 fS tttj jd jd f|ddtd|d fdd	tt	t|D   ksdkrt
krtd S )
zQBreak the pairwise matrix in n_jobs even slices
    and compute them in parallel.Nr   r   F)r   order	threading)backendn_jobsc             3   s&   | ]}| | fV  qd S )Nr"   ).0s)r    r!   fdr   r   retr"   r#   	<genexpr>  s   z%_parallel_pairwise.<locals>.<genexpr>)r$   r   r   r   r   rI   r+   r   r   r	   r6   r=   )r    r!   r   r   r   r   r"   )r    r!   r   r   r   r   r#   _parallel_pairwise  s     
r   c       
      K   s4  t | ||d\} }| |krtj| jd |jd fdd}tt| jd d}x.|D ]&\}}|| | || f||||f< qTW ||j }xt| jd D ]"}| | }	||	|	f||||f< qW nptj| jd |jd fdd}t	t| jd t|jd }x0|D ](\}}|| | || f||||f< qW |S )z:Handle the callable case for pairwise_{distances,kernels}.)r'   r   r   )r   r   )
r)   r   rj   r+   	itertoolscombinationsr   r4   rI   product)
r    r!   r\   r'   r   r9   iteratorrQ   rS   xr"   r"   r#   _pairwise_callable  s    "
 $r   rz   r{   r|   rh   Z
braycurtisZcanberraZ	chebyshevZcorrelationry   ZdiceZhammingZjaccardZ	kulsinskimahalanobisZmatchingZ	minkowskiZrogerstanimotoZ
russellrao
seuclideanZsokalmichenerZsokalsneathZsqeuclideanZyuleZ
wminkowskir   rd   c                s   | dkrdS t | t}|s | f} tdd | D rNtd|r>| n| d  f t fdd| D rtdd | D }td|r|n|d  f dS )	z?Checks chunk is a sequence of expected size or a tuple of same.Nc             s   s$   | ]}t |tpt|d  V  qdS )__iter__N)r   tuplehasattr)r   rr"   r"   r#   r     s    z$_check_chunk_size.<locals>.<genexpr>z;reduce_func returned %r. Expected sequence(s) of length %d.r   c             3   s   | ]}t | kV  qd S )N)r	   )r   r   )
chunk_sizer"   r#   r     s    c             s   s   | ]}t |V  qd S )N)r	   )r   r   r"   r"   r#   r     s    zLreduce_func returned object of length %s. Expected same length as input: %d.)r   r   r   ri   r,   )Zreducedr   is_tupleZactual_sizer"   )r   r#   _check_chunk_size  s    
r   c             K   s   |dkrRd|krRt tdk r"tjnd}| |krBtj| dd|d}ntdd|iS |d	krd
|kr| |krtjt| j	j	}ntdd
|iS i S )z:Precompute data-derived metric parameters if not provided.r   Vz1.5Nr   r   )rU   Zddofr   zIThe 'V' parameter is required for the seuclidean metric when Y is passed.r   VIzKThe 'VI' parameter is required for the mahalanobis metric when Y is passed.)
r   r   r   rN   varr,   ZlinalginvZcovr4   )r    r!   r\   r   r   r   r   r"   r"   r#   _precompute_metric_params  s    r   )r^   r\   r   working_memoryc            k   s"  t | }|dkrtd|f}n,|dkr*| }tdt | ||d}	t||	}t| |fd|i|}
|jf |
 x|D ]}|jdkr|j|kr| }n| | }t||f||d|}| |ks|dkrt	
|dtkrd|j|jdt | d < |dk	r|jd }|||j}t|| |V  qrW dS )	a  Generate a distance matrix chunk by chunk with optional reduction.

    In cases where not all of a pairwise distance matrix needs to be stored at
    once, this is used to calculate pairwise distances in
    ``working_memory``-sized chunks.  If ``reduce_func`` is given, it is run
    on each chunk and its return values are concatenated into lists, arrays
    or sparse matrices.

    Parameters
    ----------
    X : ndarray of shape (n_samples_X, n_samples_X) or             (n_samples_X, n_features)
        Array of pairwise distances between samples, or a feature array.
        The shape the array should be (n_samples_X, n_samples_X) if
        metric='precomputed' and (n_samples_X, n_features) otherwise.

    Y : ndarray of shape (n_samples_Y, n_features), default=None
        An optional second feature array. Only allowed if
        metric != "precomputed".

    reduce_func : callable, default=None
        The function which is applied on each chunk of the distance matrix,
        reducing it to needed values.  ``reduce_func(D_chunk, start)``
        is called repeatedly, where ``D_chunk`` is a contiguous vertical
        slice of the pairwise distance matrix, starting at row ``start``.
        It should return one of: None; an array, a list, or a sparse matrix
        of length ``D_chunk.shape[0]``; or a tuple of such objects. Returning
        None is useful for in-place operations, rather than reductions.

        If None, pairwise_distances_chunked returns a generator of vertical
        chunks of the distance matrix.

    metric : str or callable, default='euclidean'
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string, it must be one of the options
        allowed by scipy.spatial.distance.pdist for its metric parameter, or
        a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS.
        If metric is "precomputed", X is assumed to be a distance matrix.
        Alternatively, 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 from X as input and return a value indicating
        the distance between them.

    n_jobs : int, default=None
        The number of jobs to use for the computation. This works by breaking
        down the pairwise matrix into n_jobs even slices and computing them in
        parallel.

        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    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.

    `**kwds` : optional keyword parameters
        Any further parameters are passed directly to the distance function.
        If using a scipy.spatial.distance metric, the parameters are still
        metric dependent. See the scipy docs for usage examples.

    Yields
    ------
    D_chunk : {ndarray, sparse matrix}
        A contiguous slice of distance matrix, optionally processed by
        ``reduce_func``.

    Examples
    --------
    Without reduce_func:

    >>> import numpy as np
    >>> from sklearn.metrics import pairwise_distances_chunked
    >>> X = np.random.RandomState(0).rand(5, 3)
    >>> D_chunk = next(pairwise_distances_chunked(X))
    >>> D_chunk
    array([[0.  ..., 0.29..., 0.41..., 0.19..., 0.57...],
           [0.29..., 0.  ..., 0.57..., 0.41..., 0.76...],
           [0.41..., 0.57..., 0.  ..., 0.44..., 0.90...],
           [0.19..., 0.41..., 0.44..., 0.  ..., 0.51...],
           [0.57..., 0.76..., 0.90..., 0.51..., 0.  ...]])

    Retrieve all neighbors and average distance within radius r:

    >>> r = .2
    >>> def reduce_func(D_chunk, start):
    ...     neigh = [np.flatnonzero(d < r) for d in D_chunk]
    ...     avg_dist = (D_chunk * (D_chunk < r)).mean(axis=1)
    ...     return neigh, avg_dist
    >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func)
    >>> neigh, avg_dist = next(gen)
    >>> neigh
    [array([0, 3]), array([1]), array([2]), array([0, 3]), array([4])]
    >>> avg_dist
    array([0.039..., 0.        , 0.        , 0.039..., 0.        ])

    Where r is defined per sample, we need to make use of ``start``:

    >>> r = [.2, .4, .4, .3, .1]
    >>> def reduce_func(D_chunk, start):
    ...     neigh = [np.flatnonzero(d < r[i])
    ...              for i, d in enumerate(D_chunk, start)]
    ...     return neigh
    >>> neigh = next(pairwise_distances_chunked(X, reduce_func=reduce_func))
    >>> neigh
    [array([0, 3]), array([0, 1]), array([2]), array([0, 3]), array([4])]

    Force row-by-row generation by reducing ``working_memory``:

    >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func,
    ...                                  working_memory=0)
    >>> next(gen)
    [array([0, 3])]
    >>> next(gen)
    [array([0, 1])]
    r%   r   N   )Z	row_bytesZ
max_n_rowsr   r\   )r\   r   r   )r	   slicer   r   r   updaterW   stoppairwise_distancesr   getr6   Zflatr+   r   )r    r!   r^   r\   r   r   r   rO   ZslicesZchunk_n_rowsparamsslrR   ZD_chunkr   r"   r"   r#   r`     s4    






r`   )r   r'   c            K   s~  |t kr(t|s(|dkr(td|t f |dkrXt| |d|d\} }d}t| |d | S |tkrlt| }n t|rttf||d|}nt| st|rt	d|t
krtnd	}	|	tkr| jtks|d	k	r|jtkrd
| }
t|
t t| ||	|d\} }t| |fd|i|}|jf | t|dkrV| |krVttj| fd|i|S ttjfd|i|}t| |||f|S )a  Compute the distance matrix from a vector array X and optional Y.

    This method takes either a vector array or a distance matrix, and returns
    a distance matrix. If the input is a vector array, the distances are
    computed. If the input is a distances matrix, it is returned instead.

    This method provides a safe way to take a distance matrix as input, while
    preserving compatibility with many other algorithms that take a vector
    array.

    If Y is given (default is None), then the returned matrix is the pairwise
    distance between the arrays from both X and Y.

    Valid values for metric are:

    - From scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2',
      'manhattan']. These metrics support sparse matrix
      inputs.
      ['nan_euclidean'] but it does not yet support sparse matrices.

    - 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. These metrics do not support sparse matrix inputs.

    Note that in the case of 'cityblock', 'cosine' and 'euclidean' (which are
    valid scipy.spatial.distance metrics), the scikit-learn implementation
    will be used, which is faster and has support for sparse matrices (except
    for 'cityblock'). For a verbose description of the metrics from
    scikit-learn, see the __doc__ of the sklearn.pairwise.distance_metrics
    function.

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

    Parameters
    ----------
    X : ndarray of shape (n_samples_X, n_samples_X) or             (n_samples_X, n_features)
        Array of pairwise distances between samples, or a feature array.
        The shape of the array should be (n_samples_X, n_samples_X) if
        metric == "precomputed" and (n_samples_X, n_features) otherwise.

    Y : ndarray of shape (n_samples_Y, n_features), default=None
        An optional second feature array. Only allowed if
        metric != "precomputed".

    metric : str or callable, default='euclidean'
        The metric to use when calculating distance between instances in a
        feature array. If metric is a string, it must be one of the options
        allowed by scipy.spatial.distance.pdist for its metric parameter, or
        a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``.
        If metric is "precomputed", X is assumed to be a distance matrix.
        Alternatively, 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 from X as input and return a value indicating
        the distance between them.

    n_jobs : int, default=None
        The number of jobs to use for the computation. This works by breaking
        down the pairwise matrix into n_jobs even slices and computing them in
        parallel.

        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    force_all_finite : bool or 'allow-nan', default=True
        Whether to raise an error on np.inf, np.nan, pd.NA in array. Ignored
        for a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``. The
        possibilities are:

        - True: Force all values of array to be finite.
        - False: accepts np.inf, np.nan, pd.NA in array.
        - 'allow-nan': accepts only np.nan and pd.NA values in array. Values
          cannot be infinite.

        .. versionadded:: 0.22
           ``force_all_finite`` accepts the string ``'allow-nan'``.

        .. versionchanged:: 0.23
           Accepts `pd.NA` and converts it into `np.nan`.

    **kwds : optional keyword parameters
        Any further parameters are passed directly to the distance function.
        If using a scipy.spatial.distance metric, the parameters are still
        metric dependent. See the scipy docs for usage examples.

    Returns
    -------
    D : ndarray of shape (n_samples_X, n_samples_X) or             (n_samples_X, n_samples_Y)
        A distance matrix D such that D_{i, j} is the distance between the
        ith and jth vectors of the given matrix X, if Y is None.
        If Y is not None, then D_{i, j} is the distance between the ith array
        from X and the jth array from Y.

    See Also
    --------
    pairwise_distances_chunked : Performs the same calculation as this
        function, but returns a generator of chunks of the distance matrix, in
        order to limit memory usage.
    paired_distances : Computes the distances between corresponding elements
        of two arrays.
    r%   zHUnknown metric %s. Valid metrics are %s, or 'precomputed', or a callableT)r%   r'   zM`pairwise_distances`. Precomputed distance  need to have non-negative values.)whom)r\   r'   z6scipy distance metrics do not support sparse matrices.Nz+Data was converted to boolean for metric %s)r   r'   r\   r   )_VALID_METRICSr~   r,   r)   r
   r   r   r   r   ri   PAIRWISE_BOOLEAN_FUNCTIONSboolr   warningswarnr   r   r   r   r   Z
squareformZpdistrl   r   )r    r!   r\   r   r'   r   _r   r   r   msgr   r"   r"   r#   r     s>    n$r   )	additive_chi2chi2linear
polynomialpolyrbf	laplaciansigmoidry   c               C   s   t S )a8  Valid metrics for pairwise_kernels.

    This function simply returns the valid pairwise distance metrics.
    It exists, however, to allow for a verbose description of the mapping for
    each of the valid strings.

    The valid distance metrics, and the function they map to, are:
      ===============   ========================================
      metric            Function
      ===============   ========================================
      'additive_chi2'   sklearn.pairwise.additive_chi2_kernel
      'chi2'            sklearn.pairwise.chi2_kernel
      'linear'          sklearn.pairwise.linear_kernel
      'poly'            sklearn.pairwise.polynomial_kernel
      'polynomial'      sklearn.pairwise.polynomial_kernel
      'rbf'             sklearn.pairwise.rbf_kernel
      'laplacian'       sklearn.pairwise.laplacian_kernel
      'sigmoid'         sklearn.pairwise.sigmoid_kernel
      'cosine'          sklearn.pairwise.cosine_similarity
      ===============   ========================================

    Read more in the :ref:`User Guide <metrics>`.
    )PAIRWISE_KERNEL_FUNCTIONSr"   r"   r"   r#   kernel_metrics  s    r   r"   r   r   r   )	r   r   ry   r   r   r   r   r   r   r   )filter_paramsr   c      	         s   ddl m} dkr*t| |dd\} }| S t|r<j}nTtkrf|r\ fdd D  t }n*trttfdi }nt	d	 t
| |||f S )
a  Compute the kernel between arrays X and optional array Y.

    This method takes either a vector array or a kernel matrix, and returns
    a kernel matrix. If the input is a vector array, the kernels are
    computed. If the input is a kernel matrix, it is returned instead.

    This method provides a safe way to take a kernel matrix as input, while
    preserving compatibility with many other algorithms that take a vector
    array.

    If Y is given (default is None), then the returned matrix is the pairwise
    kernel between the arrays from both X and Y.

    Valid values for metric are:
        ['additive_chi2', 'chi2', 'linear', 'poly', 'polynomial', 'rbf',
        'laplacian', 'sigmoid', 'cosine']

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

    Parameters
    ----------
    X : ndarray of shape (n_samples_X, n_samples_X) or             (n_samples_X, n_features)
        Array of pairwise kernels between samples, or a feature array.
        The shape of the array should be (n_samples_X, n_samples_X) if
        metric == "precomputed" and (n_samples_X, n_features) otherwise.

    Y : ndarray of shape (n_samples_Y, n_features), default=None
        A second feature array only if X has shape (n_samples_X, n_features).

    metric : str or callable, default="linear"
        The metric to use when calculating kernel between instances in a
        feature array. If metric is a string, it must be one of the metrics
        in pairwise.PAIRWISE_KERNEL_FUNCTIONS.
        If metric is "precomputed", X is assumed to be a kernel matrix.
        Alternatively, 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 rows from X as input and return the corresponding
        kernel value as a single number. This means that callables from
        :mod:`sklearn.metrics.pairwise` are not allowed, as they operate on
        matrices, not single samples. Use the string identifying the kernel
        instead.

    filter_params : bool, default=False
        Whether to filter invalid parameters or not.

    n_jobs : int, default=None
        The number of jobs to use for the computation. This works by breaking
        down the pairwise matrix into n_jobs even slices and computing them in
        parallel.

        ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
        ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
        for more details.

    **kwds : optional keyword parameters
        Any further parameters are passed directly to the kernel function.

    Returns
    -------
    K : ndarray of shape (n_samples_X, n_samples_X) or             (n_samples_X, n_samples_Y)
        A kernel matrix K such that K_{i, j} is the kernel between the
        ith and jth vectors of the given matrix X, if Y is None.
        If Y is not None, then K_{i, j} is the kernel between the ith array
        from X and the jth array from Y.

    Notes
    -----
    If metric is 'precomputed', Y is ignored and X is returned.

    r   )Kernelr%   T)r%   c                s"   i | ]}|t  kr | |qS r"   )KERNEL_PARAMS)r   k)r   r\   r"   r#   
<dictcomp>  s    z$pairwise_kernels.<locals>.<dictcomp>r\   zUnknown kernel %r)Zgaussian_process.kernelsr   r)   r   __call__r   r~   r   r   r,   r   )	r    r!   r\   r   r   r   ZGPKernelr   r   r"   )r   r\   r#   pairwise_kernels  s    L

r   )N)NNF)N)NNNN)N)N)N)NT)Nr   Nr   )NNr   )NN)NN)NT)N)Nr   )T)N)N)Nr[   )Nr   )Sr   	functoolsr   r   numpyr   Zscipy.spatialr   Zscipy.sparser   r   Zjoblibr   r   Zutils.validationr	   r
   utilsr   r   r   r   r   Zutils.extmathr   r   Zpreprocessingr   Zutils._maskr   Zutils.fixesr   r   r   Z_pairwise_fastr   r   
exceptionsr   r$   r)   r-   r6   r5   rE   rF   r;   rZ   ra   rb   rf   ro   rr   rs   rw   rx   r}   r   r   r   r   r   r   rp   r   r   r   r   r   r   r   r   Z_NAN_METRICSr   r   r`   r   r   r   r   	frozensetr   r   r"   r"   r"   r#   <module>   s  v&j
4t
IXH
2Q
&:

$
#
"
#
0
=
3
 
 ' #