o
    X۷iS                     @  s  d dl mZ d dlZdZdZz
d dlmZ dZW n! ey9   z
d dlmZ dZW n ey6   dZdZY nw Y nw dd Z	dd	 Z
G d
d dZeddhdedh ddedh ddedddhdedddhdedh dddgdedh ddedddhdedh d ded!d!hdgded"h d#ded$d$hded%h d&dgZd'd( eD Zed)d* eD Zee Zd+d, Zd-d Zd.d Zd/d Zd0d Zd1d Zd2d Zd3d Zd4d Zd5d Zd6d! Zd7d" Zd8d$ Zd9d% Z dBd:d;Z!dCdd<d=d>Z"dDd@dAZ#dS )E    )annotationsNF)pairwise_distanceTc                 C  s   t j| |dS )Ndtype)cupyascontiguousarray)Xout_type r
   R/home/ubuntu/vllm_env/lib/python3.10/site-packages/cupyx/scipy/spatial/distance.py_convert_to_type   s   r   c                 K  s\   |j }| j|v r||| j n|d }t| |d} |j}|r)|| ||fi |}| ||fS )Nr   )r	   )typesr   indexr   	validator)r   mnmetric_infokwargsr   typ_validate_kwargsr
   r
   r   _validate_pdist_input   s   "
r   c                   @  s   e Zd Z		dddZdS )
MetricInfoNc                 C  s   || _ || _|| _|| _d S N)canonical_name_aka_
validator_types_)selfcanonical_nameakar   r   r
   r
   r   __init__)   s   
zMetricInfo.__init__)NNNN)__name__
__module____qualname__r    r
   r
   r
   r   r   '   s    r   canberra)r   r   	chebyshev>   chchebcheby	chebychevr%   	cityblock>   ccbcblockr*   correlationcocosinecoshamming>   hhahammr2   matchingdoublebool)r   r   r   	euclidean>   eeueuclidr9   jensenshannonjs	minkowski>   r   mipnormr?   
russellraosqeuclidean>   sqesqeuclidrC   	hellingerkl_divergence>   kldkl_divrG   c                 C  s   i | ]}|j |qS r
   )r   ).0infor
   r
   r   
<dictcomp>l   s    rL   c                 c  s$    | ]}|j D ]}||fV  qqd S r   )r   )rJ   rK   aliasr
   r
   r   	<genexpr>m   s    rN   c                   C  s   t sts
tdd S d S )NzJcuVS >= 24.12 or pylibraft < 24.12 should be installed to use this feature)cuvs_availablepylibraft_availableRuntimeErrorr
   r
   r
   r   check_soft_dependenciest   s
   rR   c                 C  sl   t   t| r
dnd}t|rdnd}||kr!td||f tjd| j|d}t| ||d| |d S )a  Compute the Minkowski distance between two 1-D arrays.

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)
        p (float): The order of the norm of the difference
            :math:`{\|u-v\|}_p`. Note that for :math:`0 < p < 1`,
            the triangle inequality only holds with an additional
            multiplicative factor, i.e. it is only a quasi-metric.

    Returns:
        minkowski (double): The Minkowski distance between vectors `u` and `v`.
    FC9u and v must have the same layout (u.order=%s, v.order=%s   rW   r   orderr?   r   r   rR   r   	isfortran
ValueErroremptyr   r   )uvpu_orderv_order
output_arrr
   r
   r   r?   {   s   c                 C  j   t   t| r
dnd}t|rdnd}||kr!td||f tjd| j|d}t| ||d |d S )az  Compute the Canberra distance between two 1-D arrays.

    The Canberra distance is defined as

    .. math::
        d(u, v) = \sum_{i} \frac{| u_i - v_i |}{|u_i| + |v_i|}

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        canberra (double): The Canberra distance between vectors `u` and `v`.
    rS   rT   rU   rV   rX   r$   rZ   r[   r_   r`   rb   rc   rd   r
   r
   r   r$         c                 C  re   )af  Compute the Chebyshev distance between two 1-D arrays.

    The Chebyshev distance is defined as

    .. math::
        d(u, v) = \max_{i} |u_i - v_i|

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        chebyshev (double): The Chebyshev distance between vectors `u` and `v`.
    rS   rT   rU   rV   rX   r%   rZ   r[   rf   r
   r
   r   r%      rg   c                 C  re   )a}  Compute the City Block (Manhattan) distance between two 1-D arrays.

    The City Block distance is defined as

    .. math::
        d(u, v) = \sum_{i} |u_i - v_i|

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        cityblock (double): The City Block distance between
        vectors `u` and `v`.
    rS   rT   rU   rV   rX   r*   rZ   r[   rf   r
   r
   r   r*         c                 C  re   )a2  Compute the correlation distance between two 1-D arrays.

    The correlation distance is defined as

    .. math::
        d(u, v) = 1 - \frac{(u - \bar{u}) \cdot (v - \bar{v})}{
        \|(u - \bar{u})\|_2 \|(v - \bar{v})\|_2}

    where :math:`\bar{u}` is the mean of the elements of :math:`u` and
    :math:`x \cdot y` is the dot product.

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        correlation (double): The correlation distance between
        vectors `u` and `v`.
    rS   rT   rU   rV   rX   r.   rZ   r[   rf   r
   r
   r   r.      s   c                 C  re   )a  Compute the Cosine distance between two 1-D arrays.

    The Cosine distance is defined as

    .. math::
        d(u, v) = 1 - \frac{u \cdot v}{\|u\|_2 \|v\|_2}

    where :math:`x \cdot y` is the dot product.

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        cosine (double): The Cosine distance between vectors `u` and `v`.
    rS   rT   rU   rV   rX   r0   rZ   r[   rf   r
   r
   r   r0        c                 C  re   )a/  Compute the Hamming distance between two 1-D arrays.

    The Hamming distance is defined as the proportion of elements
    in both `u` and `v` that are not in the exact same position:

    .. math::
        d(u, v) = \frac{1}{n} \sum_{k=0}^n u_i \neq v_i

    where :math:`x \neq y` is one if :math:`x` is different from :math:`y`
    and zero otherwise.

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        hamming (double): The Hamming distance between vectors `u` and `v`.
    rS   rT   rU   rV   rX   r2   rZ   r[   rf   r
   r
   r   r2   =     c                 C  re   )a  Compute the Euclidean distance between two 1-D arrays.

    The Euclidean distance is defined as

    .. math::
        d(u, v) = \left(\sum_{i} (u_i - v_i)^2\right)^{\sfrac{1}{2}}

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        euclidean (double): The Euclidean distance between vectors `u` and `v`.
    rS   rT   rU   rV   rX   r9   rZ   r[   rf   r
   r
   r   r9   `  rg   c                 C  re   )a  Compute the Jensen-Shannon distance between two 1-D arrays.

    The Jensen-Shannon distance is defined as

    .. math::
        d(u, v) = \sqrt{\frac{KL(u \| m) + KL(v \| m)}{2}}

    where :math:`KL` is the Kullback-Leibler divergence and :math:`m` is the
    pointwise mean of `u` and `v`.

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        jensenshannon (double): The Jensen-Shannon distance between
        vectors `u` and `v`.
    rS   rT   rU   rV   rX   r=   rZ   r[   rf   r
   r
   r   r=     rj   c                 C  re   )a-  Compute the Russell-Rao distance between two 1-D arrays.

    The Russell-Rao distance is defined as the proportion of elements
    in both `u` and `v` that are in the exact same position:

    .. math::
        d(u, v) = \frac{1}{n} \sum_{k=0}^n u_i = v_i

    where :math:`x = y` is one if :math:`x` is different from :math:`y`
    and zero otherwise.

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        hamming (double): The Hamming distance between vectors `u` and `v`.
    rS   rT   rU   rV   rX   rB   rZ   r[   rf   r
   r
   r   rB     rj   c                 C  re   )a  Compute the squared Euclidean distance between two 1-D arrays.

    The squared Euclidean distance is defined as

    .. math::
        d(u, v) = \sum_{i} (u_i - v_i)^2

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        sqeuclidean (double): The squared Euclidean distance between
        vectors `u` and `v`.
    rS   rT   rU   rV   rX   rC   rZ   r[   rf   r
   r
   r   rC     rh   c                 C  re   )a  Compute the Hellinger distance between two 1-D arrays.

    The Hellinger distance is defined as

    .. math::
        d(u, v) = \frac{1}{\sqrt{2}} \sqrt{
            \sum_{i} (\sqrt{u_i} - \sqrt{v_i})^2}

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        hellinger (double): The Hellinger distance between
        vectors `u` and `v`.
    rS   rT   rU   rV   rX   rF   rZ   r[   rf   r
   r
   r   rF     ri   c                 C  s~   t   t| } t|}t| rdnd}t|rdnd}||kr+td||f tjd| j|d}t| ||d |d S )a  Compute the Kullback-Leibler divergence between two 1-D arrays.

    The Kullback-Leibler divergence is defined as

    .. math::
        KL(U \| V) = \sum_{i} U_i \log{\left(\frac{U_i}{V_i}\right)}

    Args:
        u (array_like): Input array of size (N,)
        v (array_like): Input array of size (N,)

    Returns:
        kl_divergence (double): The Kullback-Leibler divergence between
        vectors `u` and `v`.
    rS   rT   rU   rV   rX   rG   rZ   )rR   r   asarrayr\   r]   r^   r   r   rf   r
   r
   r   rG     s   

c                 K  s  t   tstr| jdvrtj| dd} tstr#|jdvr#tj|dd}t| r*dnd}t|r3dnd}||krAtd||f | j}|j}t	|dkrQtdt	|dkr[td	|d
 |d
 krgtd|d }	|d }
d|v rw|d nd}|durtr|jdkstr|jdvrt|rdnd}||krtd| |j
ddd}|j|	|
fkrt||	|
f t|tr| }t|d}|dur|dur|n
tj|	|
f| j|d}t| |||| |S td| td)a  Compute distance between each pair of the two collections of inputs.

    Args:
        XA (array_like): An :math:`m_A` by :math:`n` array of :math:`m_A`
            original observations in an :math:`n`-dimensional space.
            Inputs are converted to float type.
        XB (array_like): An :math:`m_B` by :math:`n` array of :math:`m_B`
            original observations in an :math:`n`-dimensional space.
            Inputs are converted to float type.
        metric (str, optional): The distance metric to use.
            The distance function can be 'canberra', 'chebyshev',
            'cityblock', 'correlation', 'cosine', 'euclidean', 'hamming',
            'hellinger', 'jensenshannon', 'kl_divergence', 'matching',
            'minkowski', 'russellrao', 'sqeuclidean'.
        out (cupy.ndarray, optional): The output array. If not None, the
            distance matrix Y is stored in this array.
        **kwargs (dict, optional): Extra arguments to `metric`: refer to each
            metric documentation for a list of all possible arguments.
            Some possible arguments:
            p (float): The p-norm to apply for Minkowski, weighted and
            unweighted. Default: 2.0

    Returns:
        Y (cupy.ndarray): A :math:`m_A` by :math:`m_B` distance matrix is
            returned. For each :math:`i` and :math:`j`, the metric
            ``dist(u=XA[i], v=XB[j])`` is computed and stored in the
            :math:`ij` th entry.
    )float32float64rl   r   rS   rT   z=XA and XB must have the same layout (XA.order=%s, XB.order=%s   z!XA must be a 2-dimensional array.z!XB must be a 2-dimensional array.rW   zHXA and XB must have the same number of columns (i.e. feature dimension.)r   ra          @Nz1out must have same layout as input (out.order=%s)F)copyrX   zUnknown Distance Metric: %sz/2nd argument metric must be a string identifier)rR   rP   rO   r   r   rk   r\   r]   shapelenastyperesize
isinstancestrlower_METRIC_ALIASgetr^   r   	TypeError)XAXBmetricoutr   XA_orderXB_orderssBmAmBra   	out_ordermstrr   rd   r
   r
   r   cdist(  sj   



r   )r~   c                K  s,   t | | f||d|}t|d}|| S )a[  Compute distance between observations in n-dimensional space.

    Args:
        X (array_like): An :math:`m` by :math:`n` array of :math:`m`
            original observations in an :math:`n`-dimensional space.
            Inputs are converted to float type.
        metric (str, optional): The distance metric to use.
            The distance function can be 'canberra', 'chebyshev',
            'cityblock', 'correlation', 'cosine', 'euclidean', 'hamming',
            'hellinger', 'jensenshannon', 'kl_divergence', 'matching',
            'minkowski', 'russellrao', 'sqeuclidean'.
        out (cupy.ndarray, optional): The output array. If not None, the
            distance matrix Y is stored in this array.
        **kwargs (dict, optional): Extra arguments to `metric`: refer to each
            metric documentation for a list of all possible arguments.
            Some possible arguments:
            p (float): The p-norm to apply for Minkowski, weighted and
            unweighted. Default: 2.0

    Returns:
        Y (cupy.ndarray):
            Returns a condensed distance matrix Y. For each :math:`i` and
            :math:`j` and (where :math:`i < j < m`), where m is the number of
            original observations. The metric ``dist(u=X[i], v=X[j])`` is
            computed and stored in entry
            ``m * i + j - ((i + 2) * (i + 1)) // 2``.
    )r}   r~   rW   )r   r   triu_indices_from)r   r}   r~   r   all_distup_idxr
   r
   r   pdist  s   r   ro   c                 C  sP   t | } | j\}}t |}|j\}}||kr td||f t| |d|dS )a  Compute the distance matrix.

    Returns the matrix of all pair-wise distances.

    Args:
        x (array_like): Matrix of M vectors in K dimensions.
        y (array_like): Matrix of N vectors in K dimensions.
        p (float): Which Minkowski p-norm to use (1 <= p <= infinity).
            Default=2.0
    Returns:
        result (cupy.ndarray): Matrix containing the distance from every
            vector in `x` to every vector in `y`, (size M, N).
    zGx contains %d-dimensional vectors but y contains %d-dimensional vectorsr?   )r}   ra   )r   rk   rq   r]   r   )xyra   r   kr   kkr
   r
   r   distance_matrix  s   



r   )r9   N)r9   )ro   )$
__future__r   r   rO   rP   cuvs.distancer   ImportErrorpylibraft.distancer   r   r   _METRIC_INFOS_METRICSdictrx   listkeys_METRICS_NAMESrR   r?   r$   r%   r*   r.   r0   r2   r9   r=   rB   rC   rF   rG   r   r   r   r
   r
   r
   r   <module>   s    
; $!### !
"X!