o
    0 ihS                     @   s  d dl Z dZdZz
d dlmZ dZW n! ey3   z
d dlmZ dZW n ey0   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d/d Zd0d Zd1d Zd2d Zd3d Zd4d Zd5d  Zd6d! Zd7d# Zd8d$ ZdAd9d:ZdBdd;d<d=Z dCd?d@Z!dS )D    NF)pairwise_distanceTc                 C   s   t j| |dS )Ndtype)cupyZascontiguousarray)Xout_type r   h/home/app/PaddleOCR-VL-test/.venv_paddleocr/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   typZ_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_Z
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>   ZchebyZchebchZ	chebychevr!   	cityblock>   Zcblockccbr#   correlationcocosinecoshamming>   hZhaZhammr*   Zmatchingdoublebool)r   r   r   	euclidean>   eZeuclidr.   eujensenshannonjs	minkowski>   r3   Zpnormmir   
russellraosqeuclidean>   r6   ZsqeZsqeuclid	hellingerkl_divergence>   r8   ZkldZkl_divc                 C   s   i | ]}|j |qS r   )r   ).0infor   r   r	   
<dictcomp>j   s    r;   c                 c   s$    | ]}|j D ]}||fV  qqd S r   )r   )r9   r:   aliasr   r   r	   	<genexpr>k   s    r=   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_dependenciesr   s
   rA   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   rF   r   orderr3   r   r   rA   r   	isfortran
ValueErroremptyr   r   )uvpu_orderv_order
output_arrr   r   r	   r3   y   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`.
    rB   rC   rD   rE   rG   r    rI   rJ   rN   rO   rQ   rR   rS   r   r   r	   r          c                 C   rT   )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`.
    rB   rC   rD   rE   rG   r!   rI   rJ   rU   r   r   r	   r!      rV   c                 C   rT   )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`.
    rB   rC   rD   rE   rG   r#   rI   rJ   rU   r   r   r	   r#         c                 C   rT   )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`.
    rB   rC   rD   rE   rG   r&   rI   rJ   rU   r   r   r	   r&      s   c                 C   rT   )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`.
    rB   rC   rD   rE   rG   r(   rI   rJ   rU   r   r   r	   r(        c                 C   rT   )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`.
    rB   rC   rD   rE   rG   r*   rI   rJ   rU   r   r   r	   r*   ;     c                 C   rT   )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`.
    rB   rC   rD   rE   rG   r.   rI   rJ   rU   r   r   r	   r.   ^  rV   c                 C   rT   )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`.
    rB   rC   rD   rE   rG   r1   rI   rJ   rU   r   r   r	   r1   }  rY   c                 C   rT   )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`.
    rB   rC   rD   rE   rG   r5   rI   rJ   rU   r   r   r	   r5     rY   c                 C   rT   )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`.
    rB   rC   rD   rE   rG   r6   rI   rJ   rU   r   r   r	   r6     rW   c                 C   rT   )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`.
    rB   rC   rD   rE   rG   r7   rI   rJ   rU   r   r   r	   r7     rX   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`.
    rB   rC   rD   rE   rG   r8   rI   )rA   r   asarrayrK   rL   rM   r   r   rU   r   r   r	   r8     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.
    )float32Zfloat64r[   r   rB   rC   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.rF   zHXA and XB must have the same number of columns (i.e. feature dimension.)r   rP          @Nz1out must have same layout as input (out.order=%s)F)copyrG   zUnknown Distance Metric: %sz/2nd argument metric must be a string identifier)rA   r?   r>   r   r   rZ   rK   rL   shapelenZastyperesize
isinstancestrlower_METRIC_ALIASgetrM   r   	TypeError)ZXAZXBmetricoutr   ZXA_orderZXB_ordersZsBZmAZmBrP   Z	out_orderZmstrr   rS   r   r   r	   cdist&  sj   



rk   )ri   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``.
    )rh   ri   rF   )rk   r   Ztriu_indices_from)r   rh   ri   r   Zall_distZup_idxr   r   r	   pdist~  s   rl   r]   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 vectorsr3   )rh   rP   )r   rZ   r_   rL   rk   )xyrP   r   kr   kkr   r   r	   distance_matrix  s   



rq   )r.   N)r.   )r]   )"r   r>   r?   Zcuvs.distancer   ImportErrorZpylibraft.distancer
   r   r   Z_METRIC_INFOSZ_METRICSdictre   listkeysZ_METRICS_NAMESrA   r3   r    r!   r#   r&   r(   r*   r.   r1   r5   r6   r7   r8   rk   rl   rq   r   r   r   r	   <module>   s    
; $!### !
"X!