o
    yi3                     @   s   d dl mZmZmZ d dl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ed	ed
ededeeef f
ddZG dd deZG dd deZdS )    )AnyOptionalTupleN)Tensortensor)Metric) retrieval_precision_recall_curve)_check_retrieval_inputs)_flexible_bincountdim_zero_cat	precisionrecalltop_kmin_precisionreturnc                    s   zt  fddt| ||D \}}W n ty-   tjd|j|jd}tt|}Y nw |dkr>tjt||j|jd}||fS )a  Computes maximum recall with condition that corresponding precision >= `min_precision`.

    Args:
        top_k: tensor with all possible k
        precision: tensor with all values precisions@k for k from top_k tensor
        recall: tensor with all values recall@k for k from top_k tensor
        min_precision: float value specifying minimum precision threshold.

    Returns:
        Maximum recall value, corresponding it best k
    c                 3   s&    | ]\}}}| kr||fV  qd S N ).0prkr   r   a/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/retrieval/precision_recall_curve.py	<genexpr>+   s   $ z7_retrieval_recall_at_fixed_precision.<locals>.<genexpr>        )devicedtype)maxzip
ValueErrortorchr   r   r   len)r   r   r   r   
max_recallbest_kr   r   r   $_retrieval_recall_at_fixed_precision   s   &r$   c                       s   e Zd ZU dZdZeed< dZeed< dZeed< 				dd	e	e
 d
edede	e
 deddf fddZdedededdfddZdeeeef fddZ  ZS )RetrievalPrecisionRecallCurvea*  Computes precision-recall pairs for different k (from 1 to `max_k`).

    In a ranked retrieval context, appropriate sets of retrieved documents are naturally given by the top k retrieved
    documents. Recall is the fraction of relevant documents retrieved among all the relevant documents. Precision is the
    fraction of relevant documents among all the retrieved documents. For each such set, precision and recall values
    can be plotted to give a recall-precision curve.

    As input to ``forward`` and ``update`` the metric accepts the following input:

    - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
    - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)``
    - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a
      prediction belongs

    As output to ``forward`` and ``compute`` the metric returns the following output:

    - ``precisions`` (:class:`~torch.Tensor`): A tensor with the fraction of relevant documents among all the
      retrieved documents.
    - ``recalls`` (:class:`~torch.Tensor`): A tensor with the fraction of relevant documents retrieved among all the
      relevant documents
    - ``top_k`` (:class:`~torch.Tensor`): A tensor with k from 1 to `max_k`

    All ``indexes``, ``preds`` and ``target`` must have the same dimension and will be flatten at the beginning,
    so that for example, a tensor of shape ``(N, M)`` is treated as ``(N * M, )``. Predictions will be first grouped by
    ``indexes`` and then will be computed as the mean of the metric over each query.

    Args:
        max_k: Calculate recall and precision for all possible top k from 1 to max_k
               (default: `None`, which considers all possible top k)
        adaptive_k: adjust `k` to `min(k, number of documents)` for each query
        empty_target_action:
            Specify what to do with queries that do not have at least a positive ``target``. Choose from:

            - ``'neg'``: those queries count as ``0.0`` (default)
            - ``'pos'``: those queries count as ``1.0``
            - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned
            - ``'error'``: raise a ``ValueError``

        ignore_index:
            Ignore predictions where the target is equal to this number.
        kwargs:
            Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ValueError:
            If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``.
        ValueError:
            If ``ignore_index`` is not `None` or an integer.
        ValueError:
            If ``max_k`` parameter is not `None` or an integer larger than 0.

    Example:
        >>> from torchmetrics import RetrievalPrecisionRecallCurve
        >>> indexes = tensor([0, 0, 0, 0, 1, 1, 1])
        >>> preds = tensor([0.4, 0.01, 0.5, 0.6, 0.2, 0.3, 0.5])
        >>> target = tensor([True, False, False, True, True, False, True])
        >>> r = RetrievalPrecisionRecallCurve(max_k=4)
        >>> precisions, recalls, top_k = r(preds, target, indexes=indexes)
        >>> precisions
        tensor([1.0000, 0.5000, 0.6667, 0.5000])
        >>> recalls
        tensor([0.5000, 0.5000, 1.0000, 1.0000])
        >>> top_k
        tensor([1, 2, 3, 4])
    Fis_differentiableThigher_is_betterfull_state_updateNnegmax_k
adaptive_kempty_target_actionignore_indexkwargsr   c                    s   t  jdi | d| _d}||vrtd| d|| _|d ur*t|ts*td|| _|d ur>t|tr:|dks>td|| _t|t	sJtd|| _
| jd	g d d
 | jdg d d
 | jdg d d
 d S )NF)errorskipr)   posz7Argument `empty_target_action` received a wrong value `z`.z3Argument `ignore_index` must be an integer or None.r   z,`max_k` has to be a positive integer or Nonez `adaptive_k` has to be a booleanindexes)defaultdist_reduce_fxpredstargetr   )super__init__allow_non_binary_targetr   r,   
isinstanceintr-   r*   boolr+   	add_state)selfr*   r+   r,   r-   r.   empty_target_action_options	__class__r   r   r8   ~   s$   
z&RetrievalPrecisionRecallCurve.__init__r5   r6   r2   c                 C   sT   |du rt dt|||| j| jd\}}}| j| | j| | j| dS )zGCheck shape, check and convert dtypes, flatten and add to accumulators.Nz!Argument `indexes` cannot be None)r9   r-   )r   r	   r9   r-   r2   appendr5   r6   )r>   r5   r6   r2   r   r   r   update   s   z$RetrievalPrecisionRecallCurve.updatec                    s  t | j}t | j t | j}t|\}} |  || }t|  	 }| j
}|d u r3t|}g g }}ttj |ddtj||ddD ]^\}}	|	 s| jdkrZtd| jdkrv|tj| jd |tj| jd qI| jdkr|tj| jd |tj| jd qIt||	|| j\}
}}||
 || qI|rt fdd	|D jddnt| }
|rt fd
d	|D jddnt| }tjd|d  jd}|
||fS )Nr   )dimr/   zC`compute` method was provided with a query with no positive target.r1   )r   r)   c                       g | ]}|  qS r   tor   xr5   r   r   
<listcomp>       z9RetrievalPrecisionRecallCurve.compute.<locals>.<listcomp>c                    rE   r   rF   rH   rJ   r   r   rK      rL      )r   r2   r5   r6   r    sortr
   detachcputolistr*   r   r   splitsumr,   r   rB   onesr   zerosr   r+   stackmeanrG   arange)r>   r2   r6   indicessplit_sizesr*   
precisionsrecalls
mini_predsmini_targetr   r   _r   r   rJ   r   compute   s@   







24
z%RetrievalPrecisionRecallCurve.compute)NFr)   N)__name__
__module____qualname____doc__r&   r<   __annotations__r'   r(   r   r;   strr   r8   r   rC   r   r`   __classcell__r   r   r@   r   r%   7   s0   
 B" r%   c                       sp   e Zd ZdZdZ					ddedee d	ed
e	dee de
ddf fddZdeeef f fddZ  ZS )RetrievalRecallAtFixedPrecisiona
  Computes `IR Recall at fixed Precision`_.

    As input to ``forward`` and ``update`` the metric accepts the following input:

    - ``preds`` (:class:`~torch.Tensor`): A float tensor of shape ``(N, ...)``
    - ``target`` (:class:`~torch.Tensor`): A long or bool tensor of shape ``(N, ...)``
    - ``indexes`` (:class:`~torch.Tensor`): A long tensor of shape ``(N, ...)`` which indicate to which query a
      prediction belongs

    .. note:: All ``indexes``, ``preds`` and ``target`` must have the same dimension.

    .. note::
        Predictions will be first grouped by ``indexes`` and then `RetrievalRecallAtFixedPrecision`
        will be computed as the mean of the `RetrievalRecallAtFixedPrecision` over each query.

    As output to ``forward`` and ``compute`` the metric returns the following output:

    - ``max_recall`` (:class:`~torch.Tensor`): A tensor with the maximum recall value
      retrieved documents.
    - ``best_k`` (:class:`~torch.Tensor`): A tensor with the best k corresponding to the maximum recall value

    Args:
        min_precision: float value specifying minimum precision threshold.
        max_k: Calculate recall and precision for all possible top k from 1 to max_k
               (default: `None`, which considers all possible top k)
        adaptive_k: adjust `k` to `min(k, number of documents)` for each query
        empty_target_action:
            Specify what to do with queries that do not have at least a positive ``target``. Choose from:

            - ``'neg'``: those queries count as ``0.0`` (default)
            - ``'pos'``: those queries count as ``1.0``
            - ``'skip'``: skip those queries; if all queries are skipped, ``0.0`` is returned
            - ``'error'``: raise a ``ValueError``

        ignore_index:
            Ignore predictions where the target is equal to this number.
        kwargs:
            Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ValueError:
            If ``empty_target_action`` is not one of ``error``, ``skip``, ``neg`` or ``pos``.
        ValueError:
            If ``ignore_index`` is not `None` or an integer.
        ValueError:
            If ``min_precision`` parameter is not float or between 0 and 1.
        ValueError:
            If ``max_k`` parameter is not `None` or an integer larger than 0.

    Example:
        >>> from torchmetrics import RetrievalRecallAtFixedPrecision
        >>> indexes = tensor([0, 0, 0, 0, 1, 1, 1])
        >>> preds = tensor([0.4, 0.01, 0.5, 0.6, 0.2, 0.3, 0.5])
        >>> target = tensor([True, False, False, True, True, False, True])
        >>> r = RetrievalRecallAtFixedPrecision(min_precision=0.8)
        >>> r(preds, target, indexes=indexes)
        (tensor(0.5000), tensor(1))
    Tr   NFr)   r   r*   r+   r,   r-   r.   r   c                    sT   t  jd||||d| t|tr!d|  kr dks%td td|| _d S )N)r*   r+   r,   r-   r   g      ?z:`min_precision` has to be a positive float between 0 and 1r   )r7   r8   r:   floatr   r   )r>   r   r*   r+   r,   r-   r.   r@   r   r   r8     s   	
z(RetrievalRecallAtFixedPrecision.__init__c                    s    t   \}}}t|||| jS r   )r7   r`   r$   r   )r>   r[   r\   r   r@   r   r   r`   0  s   z'RetrievalRecallAtFixedPrecision.compute)r   NFr)   N)ra   rb   rc   rd   r'   ri   r   r;   r<   rf   r   r8   r   r   r`   rg   r   r   r@   r   rh      s0    ;"rh   )typingr   r   r   r    r   r   torchmetricsr   8torchmetrics.functional.retrieval.precision_recall_curver   torchmetrics.utilities.checksr	   torchmetrics.utilities.datar
   r   ri   r$   r%   rh   r   r   r   r   <module>   s*   

 &