a
    d
                     @   sZ   d dl mZ d dlZd dlmZ d dlmZ eedddZdeeee edd	d
ZdS )    )OptionalN)Tensor)"_check_retrieval_functional_inputs)targetreturnc                 C   s0   t t j| jd | jdd }| | jddS )z4Compute Discounted Cumulative Gain for input tensor.)deviceg       @)dim)torchlog2Zarangeshaper   sum)r   Zdenom r   o/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/functional/retrieval/ndcg.py_dcg   s     r   )predsr   top_kr   c                 C   s   t | |dd\} }|du r$| jd n|}t|tr:|dksBtd|tj| ddd d| }tj|ddd d| }t|}t|}|dk}d||< ||   ||    < |	 S )	a  Compute `Normalized Discounted Cumulative Gain`_ (for information retrieval).

    ``preds`` and ``target`` should be of the same shape and live on the same device.
    ``target`` must be either `bool` or `integers` and ``preds`` must be ``float``,
    otherwise an error is raised.

    Args:
        preds: estimated probabilities of each document to be relevant.
        target: ground truth about each document relevance.
        top_k: consider only the top k elements (default: ``None``, which considers them all)

    Return:
        A single-value tensor with the nDCG of the predictions ``preds`` w.r.t. the labels ``target``.

    Raises:
        ValueError:
            If ``top_k`` parameter is not `None` or an integer larger than 0

    Example:
        >>> from torchmetrics.functional.retrieval import retrieval_normalized_dcg
        >>> preds = torch.tensor([.1, .2, .3, 4, 70])
        >>> target = torch.tensor([10, 0, 0, 1, 5])
        >>> retrieval_normalized_dcg(preds, target)
        tensor(0.6957)

    T)Zallow_non_binary_targetNr   r   z,`top_k` has to be a positive integer or None)r	   
descending)r   )
r   r   
isinstanceint
ValueErrorr
   Zargsortsortr   mean)r   r   r   Zsorted_targetZideal_targetZ	ideal_dcgZ
target_dcgZall_irrelevantr   r   r   retrieval_normalized_dcg   s    r   )N)	typingr   r
   r   Ztorchmetrics.utilities.checksr   r   r   r   r   r   r   r   <module>   s
   