o
    .wiE                     @   s   d dl mZ d dlmZmZmZmZmZ d dlZd dlm	Z	 d dl
mZ d dl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 dlmZ d dlmZmZmZ esZddg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 )    )Sequence)AnyCallableListOptionalUnionN)Tensor)Literal)Metric) retrieval_precision_recall_curve)_retrieval_aggregate)_check_retrieval_inputs)_flexible_bincountdim_zero_cat)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPE
plot_curve"RetrievalPrecisionRecallCurve.plot$RetrievalRecallAtFixedPrecision.plot	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  Compute 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   j/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/retrieval/precision_recall_curve.py	<genexpr>4   s   $ z7_retrieval_recall_at_fixed_precision.<locals>.<genexpr>        )devicedtype)maxzip
ValueErrortorchtensorr$   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< e	e
 ed< e	e
 ed< e	e
 ed	< 	
			
	ddee dededee deed ef 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	
	
d deee
e
e
f  dee defddZ  ZS )!RetrievalPrecisionRecallCurvea  Compute 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.
        aggregation:
            Specify how to aggregate over indexes. Can either a custom callable function that takes in a single tensor
            and returns a scalar value or one of the following strings:

            - ``'mean'``: average value is returned
            - ``'median'``: median value is returned
            - ``'max'``: max value is returned
            - ``'min'``: min value is returned

        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 not an integer larger than 0.

    Example:
        >>> from torch import tensor
        >>> from torchmetrics.retrieval 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_updateindexespredstargetNnegmeanmax_k
adaptive_kempty_target_actionignore_indexaggregationr7   medianminr&   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|| _
|d	v s]t|s]td
| d|| _| jdg d d | jdg d d | jdg d d d S )NF)errorskipr6   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 booleanr=   zArgument `aggregation` must be one of `mean`, `median`, `min`, `max` or a custom callable functionwhich takes tensor of values, but got .r3   )defaultdist_reduce_fxr4   r5   r   )super__init__allow_non_binary_targetr(   r:   
isinstanceintr;   r8   boolr9   callabler<   	add_state)selfr8   r9   r:   r;   r<   r@   empty_target_action_options	__class__r   r!   rH      s2   	
z&RetrievalPrecisionRecallCurve.__init__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)rI   r;   )r(   r   rI   r;   r3   appendr4   r5   )rO   r4   r5   r3   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t fd	d
|D | jddnt| }
|rtt fdd
|D | jddnt| }tjd|d  jd}|
||fS )Compute metric.Nr   )dimrA   zC`compute` method was provided with a query with no positive target.rC   )r$   r6   c                       g | ]}|  qS r   tor   xr4   r   r!   
<listcomp>       z9RetrievalPrecisionRecallCurve.compute.<locals>.<listcomp>)r<   rV   c                    rW   r   rX   rZ   r\   r   r!   r]      r^      )r   r3   r4   r5   r)   sortr   detachcputolistr8   r&   r'   splitsumr:   r(   rS   onesr$   zerosr   r9   r   stackr<   rY   arange)rO   r3   r5   indicessplit_sizesr8   
precisionsrecalls
mini_predsmini_targetr   r   _r   r   r\   r!   compute   sJ   







&&
z%RetrievalPrecisionRecallCurve.computecurveaxc                 C   s    |p|   }t||d| jjdS )a  Plot a single or multiple values from the metric.

        Args:
            curve: the output of either `metric.compute` or `metric.forward`. If no value is provided, will
                automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> import torch
            >>> from torchmetrics.retrieval import RetrievalPrecisionRecallCurve
            >>> # Example plotting a single value
            >>> metric = RetrievalPrecisionRecallCurve()
            >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))
            >>> fig_, ax_ = metric.plot()

        )zFalse positive ratezTrue positive rate)rs   label_namesname)rq   r   rR   __name__)rO   rr   rs   r   r   r!   plot  s   r   )NFr6   Nr7   NN)rv   
__module____qualname____doc__r0   rL   __annotations__r1   r2   r   r   r   rK   strr   r	   r   r   rH   rT   tuplerq   r   r   rw   __classcell__r   r   rQ   r!   r/   @   sN   
 M*7r/   c                       s   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	ddeeeee f  dee defddZ  ZS )RetrievalRecallAtFixedPrecisiona!  Compute `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

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

    .. attention::
        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 torch import tensor
        >>> from torchmetrics.retrieval 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#   NFr6   r   r8   r9   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)r8   r9   r:   r;   r#   g      ?z:`min_precision` has to be a positive float between 0 and 1r   )rG   rH   rJ   floatr(   r   )rO   r   r8   r9   r:   r;   r@   rQ   r   r!   rH   j  s   	
z(RetrievalRecallAtFixedPrecision.__init__c                    s    t   \}}}t|||| jS )rU   )rG   rq   r.   r   )rO   rl   rm   r   rQ   r   r!   rq     s   z'RetrievalRecallAtFixedPrecision.computevalrs   c                 C   s   |p|   d }| ||S )a  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> import torch
            >>> from torchmetrics.retrieval import RetrievalRecallAtFixedPrecision
            >>> # Example plotting a single value
            >>> metric = RetrievalRecallAtFixedPrecision(min_precision=0.5)
            >>> metric.update(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> import torch
            >>> from torchmetrics.retrieval import RetrievalRecallAtFixedPrecision
            >>> # Example plotting multiple values
            >>> metric = RetrievalRecallAtFixedPrecision(min_precision=0.5)
            >>> values = []
            >>> for _ in range(10):
            ...     values.append(metric(torch.rand(10,), torch.randint(2, (10,)), indexes=torch.randint(2,(10,)))[0])
            >>> fig, ax = metric.plot(values)

        r   )rq   _plot)rO   r   rs   r   r   r!   rw     s   (r   )r#   NFr6   Nrx   )rv   ry   rz   r{   r1   r   r   rK   rL   r}   r   rH   r~   r   rq   r   r   r   r   rw   r   r   r   rQ   r!   r   )  s@    >r   )#collections.abcr   typingr   r   r   r   r   r)   r   typing_extensionsr	   torchmetricsr
   8torchmetrics.functional.retrieval.precision_recall_curver   torchmetrics.retrieval.baser   torchmetrics.utilities.checksr   torchmetrics.utilities.datar   r   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   r   __doctest_skip__r   r~   r.   r/   r   r   r   r   r!   <module>   s8   

 j