o
    yi
                  	   @   sb   d dl mZ d dlZd dlmZ d dlmZ dedefddZdd	eded
ee def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 )z5Computes Discounted Cumulative Gain for input tensor.)deviceg       @)dim)torchlog2arangeshaper   sum)r   denom r   Z/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/functional/retrieval/ndcg.py_dcg   s    r   predskc                 C   s   t | |dd\} }|du r| jd n|}t|tr|dks!td|tj| ddd d| }tj|ddd d| }t|}t|}|dk}d||< ||   ||    < |	 S )	a  Computes `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.
        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 ``k`` parameter is not `None` or an integer larger than 0

    Example:
        >>> from torchmetrics.functional 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)allow_non_binary_targetNr   r   z(`k` has to be a positive integer or None)r	   
descending)r   )
r   r   
isinstanceint
ValueErrorr
   argsortsortr   mean)r   r   r   sorted_targetideal_target	ideal_dcg
target_dcgall_irrelevantr   r   r   retrieval_normalized_dcg   s   r"   )N)	typingr   r
   r   torchmetrics.utilities.checksr   r   r   r"   r   r   r   r   <module>   s   $