§
    ’©ºjhF  ã                   óÊ  — d dl mZmZ d dlZd dlmZ d dlmZ d dlmZm	Z	m
Z
mZmZmZmZmZmZ d dlmZmZmZmZmZmZ d dlmZ ded	ed
ededeeef         f
d„Z	 	 	 ddededed
eeeee         ef                  dee         dedeeef         fd„Z 	 	 	 ddedededed
eeeee         ef                  dee         dedeeef         fd„Z!	 	 	 ddedededed
eeeee         ef                  dee         dedeeef         fd„Z"	 	 	 	 	 ddededed         ded
eeeee         ef                  dee         dee         dee         dedeeeef                  fd„Z#dS )é    )ÚOptionalÚUnionN)ÚTensor)ÚLiteral)	Ú%_binary_precision_recall_curve_formatÚ0_binary_precision_recall_curve_tensor_validationÚ%_binary_precision_recall_curve_updateÚ)_multiclass_precision_recall_curve_formatÚ4_multiclass_precision_recall_curve_tensor_validationÚ)_multiclass_precision_recall_curve_updateÚ)_multilabel_precision_recall_curve_formatÚ4_multilabel_precision_recall_curve_tensor_validationÚ)_multilabel_precision_recall_curve_update)Ú0_binary_recall_at_fixed_precision_arg_validationÚ)_binary_recall_at_fixed_precision_computeÚ1_multiclass_recall_at_fixed_precision_arg_computeÚ4_multiclass_recall_at_fixed_precision_arg_validationÚ1_multilabel_recall_at_fixed_precision_arg_computeÚ4_multilabel_recall_at_fixed_precision_arg_validation)ÚClassificationTaskÚ	precisionÚrecallÚ
thresholdsÚ
min_recallÚreturnc                 ó^  ‡— 	 t          ˆfd„t          | ||¦  «        D ¦   «         ¦  «        \  }}}nE# t          $ r8 t          j        d| j        | j        ¬¦  «        }t          j        d¦  «        }Y nw xY w|dk    r.t          j        t          d¦  «        |j        |j        ¬¦  «        }||fS )Nc              3   ó6   •K  — | ]\  }}}|‰k    ¯|||fV — Œd S )N© )Ú.0ÚpÚrÚtr   s       €ú�/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/functional/classification/precision_fixed_recall.pyú	<genexpr>z'_precision_at_recall.<locals>.<genexpr>1   s=   øè è € ð /
ð /
Ù!˜!˜Q È1ÐPZÊ?È?ˆQ��1ˆIÈ?È?È?È?ð/
ð /
ó    g        )ÚdeviceÚdtyper   Únan)ÚmaxÚzipÚ
ValueErrorÚtorchÚtensorr&   r'   Úfloat)r   r   r   r   Úmax_precisionÚ_Úbest_thresholds      `   r#   Ú_precision_at_recallr2   *   sÖ   ø€ ð)Ý+.ð /
ð /
ð /
ð /
Ý%(¨°F¸JÑ%GÔ%Gð/
ñ /
ô /
ñ ,
ô ,
Ñ(ˆ�q˜.˜.øõ ð )ð )ð )Ýœ S°Ô1AÈÌÐYÑYÔYˆÝœ a™œˆˆˆð)øøøð ˜ÒÐÝœ¥e¨E¡l¤l¸:Ô;LÐT^ÔTdÐeÑeÔeˆà˜.Ð(Ð(s   ƒ.2 ²?A4Á3A4TÚpredsÚtargetÚignore_indexÚvalidate_argsc                 óÈ   — |r"t          |||¦  «         t          | ||¦  «         t          | |||¦  «        \  } }}t          | ||¦  «        }t	          |||t
          ¬¦  «        S )a�  Compute the highest possible precision value given the minimum recall thresholds provided for binary tasks.

    This is done by first calculating the precision-recall curve for different thresholds and the find the precision
    for a given recall level.

    Accepts the following input tensors:

    - ``preds`` (float tensor): ``(N, ...)``. Preds should be a tensor containing probabilities or logits for each
      observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
      sigmoid per element.
    - ``target`` (int tensor): ``(N, ...)``. Target should be a tensor containing ground truth labels, and therefore
      only contain {0,1} values (except if `ignore_index` is specified). The value 1 always encodes the positive class.

    Additional dimension ``...`` will be flattened into the batch dimension.

    The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
    that is less accurate but more memory efficient. Setting the `thresholds` argument to ``None`` will activate the
    non-binned  version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
    argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
    size :math:`\mathcal{O}(n_{thresholds})` (constant memory).

    Args:
        preds: Tensor with predictions
        target: Tensor with true labels
        min_recall: float value specifying minimum recall threshold.
        thresholds:
            Can be one of:

            - If set to ``None``, will use a non-binned approach where thresholds are dynamically calculated from
              all the data. Most accurate but also most memory consuming approach.
            - If set to an ``int`` (larger than 1), will use that number of thresholds linearly spaced from
              0 to 1 as bins for the calculation.
            - If set to an ``list`` of floats, will use the indicated thresholds in the list as bins for the calculation
            - If set to an 1d :class:`~torch.Tensor` of floats, will use the indicated thresholds in the tensor as
              bins for the calculation.

        ignore_index:
            Specifies a target value that is ignored and does not contribute to the metric calculation
        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.

    Returns:
        (tuple): a tuple of 2 tensors containing:

        - precision: an scalar tensor with the maximum precision for the given precision level
        - threshold: an scalar tensor with the corresponding threshold level

    Example:
        >>> from torchmetrics.functional.classification import binary_precision_at_fixed_recall
        >>> preds = torch.tensor([0, 0.5, 0.7, 0.8])
        >>> target = torch.tensor([0, 1, 1, 0])
        >>> binary_precision_at_fixed_recall(preds, target, min_recall=0.5, thresholds=None)
        (tensor(0.6667), tensor(0.5000))
        >>> binary_precision_at_fixed_recall(preds, target, min_recall=0.5, thresholds=5)
        (tensor(0.6667), tensor(0.5000))

    ©Úmin_precisionÚ	reduce_fn)r   r   r   r	   r   r2   )r3   r4   r   r   r5   r6   Ústates          r#   Ú binary_precision_at_fixed_recallr<   ?   s�   € ðB ð VÝ8¸ÀZÐQ]Ñ^Ô^Ð^Ý8¸ÀÈÑUÔUÐUÝ EÀeÈVÐU_ÐamÑ nÔ nÑ€Eˆ6�:Ý1°%¸ÀÑLÔL€EÝ4Øˆz¨Õ?Sðñ ô ð r%   Únum_classesc                 óÒ   — |r$t          ||||¦  «         t          | |||¦  «         t          | ||||¦  «        \  } }}t          | |||¦  «        }t	          ||||t
          ¬¦  «        S )a  Compute the highest possible precision value given the minimum recall thresholds provided for multiclass tasks.

    This is done by first calculating the precision-recall curve for different thresholds and the find the precision
    for a given recall level.

    Accepts the following input tensors:

    - ``preds`` (float tensor): ``(N, C, ...)``. Preds should be a tensor containing probabilities or logits for each
      observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
      softmax per sample.
    - ``target`` (int tensor): ``(N, ...)``. Target should be a tensor containing ground truth labels, and therefore
      only contain values in the [0, n_classes-1] range (except if `ignore_index` is specified).

    Additional dimension ``...`` will be flattened into the batch dimension.

    The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
    that is less accurate but more memory efficient. Setting the `thresholds` argument to ``None`` will activate the
    non-binned  version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
    argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
    size :math:`\mathcal{O}(n_{thresholds} \times n_{classes})` (constant memory).

    Args:
        preds: Tensor with predictions
        target: Tensor with true labels
        num_classes: Integer specifying the number of classes
        min_recall: float value specifying minimum recall threshold.
        thresholds:
            Can be one of:

            - If set to ``None``, will use a non-binned approach where thresholds are dynamically calculated from
              all the data. Most accurate but also most memory consuming approach.
            - If set to an ``int`` (larger than 1), will use that number of thresholds linearly spaced from
              0 to 1 as bins for the calculation.
            - If set to an ``list`` of floats, will use the indicated thresholds in the list as bins for the calculation
            - If set to an 1d :class:`~torch.Tensor` of floats, will use the indicated thresholds in the tensor as
              bins for the calculation.

        ignore_index:
            Specifies a target value that is ignored and does not contribute to the metric calculation
        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.

    Returns:
        (tuple): a tuple of either 2 tensors or 2 lists containing

        - precision: an 1d tensor of size (n_classes, ) with the maximum precision for the given recall level per class
        - thresholds: an 1d tensor of size (n_classes, ) with the corresponding threshold level per class

    Example:
        >>> from torchmetrics.functional.classification import multiclass_precision_at_fixed_recall
        >>> preds = torch.tensor([[0.75, 0.05, 0.05, 0.05, 0.05],
        ...                       [0.05, 0.75, 0.05, 0.05, 0.05],
        ...                       [0.05, 0.05, 0.75, 0.05, 0.05],
        ...                       [0.05, 0.05, 0.05, 0.75, 0.05]])
        >>> target = torch.tensor([0, 1, 3, 2])
        >>> multiclass_precision_at_fixed_recall(  # doctest: +NORMALIZE_WHITESPACE
        ...     preds, target, num_classes=5, min_recall=0.5, thresholds=None)
        (tensor([1.0000, 1.0000, 0.2500, 0.2500, 0.0000]),
         tensor([0.7500, 0.7500, 0.0500, 0.0500, nan]))
        >>> multiclass_precision_at_fixed_recall(  # doctest: +NORMALIZE_WHITESPACE
        ...     preds, target, num_classes=5, min_recall=0.5, thresholds=5)
        (tensor([1.0000, 1.0000, 0.2500, 0.2500, 0.0000]),
         tensor([0.7500, 0.7500, 0.0000, 0.0000, nan]))

    r8   )r   r   r
   r   r   r2   )r3   r4   r=   r   r   r5   r6   r;   s           r#   Ú$multiclass_precision_at_fixed_recallr?   Š   s“   € ðT ð gÝ<¸[È*ÐV`ÐbnÑoÔoÐoÝ<¸UÀFÈKÐYeÑfÔfÐfÝ IØˆv�{ J°ñ!ô !Ñ€Eˆ6�:õ 6°e¸VÀ[ÐR\Ñ]Ô]€EÝ<Øˆ{˜J°jÕL`ðñ ô ð r%   Ú
num_labelsc                 óÔ   — |r$t          ||||¦  «         t          | |||¦  «         t          | ||||¦  «        \  } }}t          | |||¦  «        }t	          |||||t
          ¬¦  «        S )aª  Compute the highest possible precision value given the minimum recall thresholds provided for multilabel tasks.

    This is done by first calculating the precision-recall curve for different thresholds and the find the precision
    for a given recall level.

    Accepts the following input tensors:

    - ``preds`` (float tensor): ``(N, C, ...)``. Preds should be a tensor containing probabilities or logits for each
      observation. If preds has values outside [0,1] range we consider the input to be logits and will auto apply
      sigmoid per element.
    - ``target`` (int tensor): ``(N, C, ...)``. Target should be a tensor containing ground truth labels, and therefore
      only contain {0,1} values (except if `ignore_index` is specified).

    Additional dimension ``...`` will be flattened into the batch dimension.

    The implementation both supports calculating the metric in a non-binned but accurate version and a binned version
    that is less accurate but more memory efficient. Setting the `thresholds` argument to ``None`` will activate the
    non-binned  version that uses memory of size :math:`\mathcal{O}(n_{samples})` whereas setting the `thresholds`
    argument to either an integer, list or a 1d tensor will use a binned version that uses memory of
    size :math:`\mathcal{O}(n_{thresholds} \times n_{labels})` (constant memory).

    Args:
        preds: Tensor with predictions
        target: Tensor with true labels
        num_labels: Integer specifying the number of labels
        min_recall: float value specifying minimum recall threshold.
        thresholds:
            Can be one of:

            - If set to ``None``, will use a non-binned approach where thresholds are dynamically calculated from
              all the data. Most accurate but also most memory consuming approach.
            - If set to an ``int`` (larger than 1), will use that number of thresholds linearly spaced from
              0 to 1 as bins for the calculation.
            - If set to an ``list`` of floats, will use the indicated thresholds in the list as bins for the calculation
            - If set to an 1d :class:`~torch.Tensor` of floats, will use the indicated thresholds in the tensor as
              bins for the calculation.

        ignore_index:
            Specifies a target value that is ignored and does not contribute to the metric calculation
        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.

    Returns:
        (tuple): a tuple of either 2 tensors or 2 lists containing

        - precision: an 1d tensor of size (n_classes, ) with the maximum precision for the given recall level per class
        - thresholds: an 1d tensor of size (n_classes, ) with the corresponding threshold level per class

    Example:
        >>> from torchmetrics.functional.classification import multilabel_precision_at_fixed_recall
        >>> preds = torch.tensor([[0.75, 0.05, 0.35],
        ...                       [0.45, 0.75, 0.05],
        ...                       [0.05, 0.55, 0.75],
        ...                       [0.05, 0.65, 0.05]])
        >>> target = torch.tensor([[1, 0, 1],
        ...                        [0, 0, 0],
        ...                        [0, 1, 1],
        ...                        [1, 1, 1]])
        >>> multilabel_precision_at_fixed_recall(preds, target, num_labels=3, min_recall=0.5, thresholds=None)
        (tensor([1.0000, 0.6667, 1.0000]), tensor([0.7500, 0.5500, 0.3500]))
        >>> multilabel_precision_at_fixed_recall(preds, target, num_labels=3, min_recall=0.5, thresholds=5)
        (tensor([1.0000, 0.6667, 1.0000]), tensor([0.7500, 0.5000, 0.2500]))

    r8   )r   r   r   r   r   r2   )r3   r4   r@   r   r   r5   r6   r;   s           r#   Ú$multilabel_precision_at_fixed_recallrB   à   s•   € ðR ð fÝ<¸ZÈÐU_ÐamÑnÔnÐnÝ<¸UÀFÈJÐXdÑeÔeÐeÝ IØˆv�z :¨|ñ!ô !Ñ€Eˆ6�:õ 6°e¸VÀZÐQ[Ñ\Ô\€EÝ<Øˆz˜: |À:ÕYmðñ ô ð r%   Útask)ÚbinaryÚ
multiclassÚ
multilabelc	           	      óÞ  — t          j        |¦  «        }|t           j        k    rt          | |||||¦  «        S |t           j        k    rJt          |t          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚t          | ||||||¦  «        S |t           j
        k    rJt          |t          ¦  «        s t          dt          |¦  «        › d�¦  «        ‚t          | ||||||¦  «        S dS )a)  Compute the highest possible recall value given the minimum precision thresholds provided.

    This is done by first calculating the precision-recall curve for different thresholds and the find the recall for a
    given precision level.

    This function is a simple wrapper to get the task specific versions of this metric, which is done by setting the
    ``task`` argument to either ``'binary'``, ``'multiclass'`` or ``'multilabel'``. See the documentation of
    :func:`~torchmetrics.functional.classification.binary_precision_at_fixed_recall`,
    :func:`~torchmetrics.functional.classification.multiclass_precision_at_fixed_recall` and
    :func:`~torchmetrics.functional.classification.multilabel_precision_at_fixed_recall` for the specific details of
    each argument influence and examples.

    z+`num_classes` is expected to be `int` but `z was passed.`z*`num_labels` is expected to be `int` but `N)r   Úfrom_strÚBINARYr<   Ú
MULTICLASSÚ
isinstanceÚintr+   Útyper?   Ú
MULTILABELrB   )	r3   r4   rC   r   r   r=   r@   r5   r6   s	            r#   Úprecision_at_fixed_recallrO   5  s  € õ0 Ô& tÑ,Ô,€DØÕ!Ô(Ò(Ð(Ý/°°v¸zÈ:ÐWcÐerÑsÔsÐsØÕ!Ô,Ò,Ð,Ý˜+¥sÑ+Ô+ð 	mÝÐkÍ4ÐP[ÑK\ÔK\ÐkÐkÐkÑlÔlÐlÝ3Ø�6˜;¨
°JÀÈmñ
ô 
ð 	
ð Õ!Ô,Ò,Ð,Ý˜*¥cÑ*Ô*ð 	kÝÐiÍ$ÈzÑJZÔJZÐiÐiÐiÑjÔjÐjÝ3Ø�6˜: z°:¸|È]ñ
ô 
ð 	
ð ˆ4r%   )NNT)NNNNT)$Útypingr   r   r,   r   Útyping_extensionsr   Ú=torchmetrics.functional.classification.precision_recall_curver   r   r	   r
   r   r   r   r   r   Ú=torchmetrics.functional.classification.recall_fixed_precisionr   r   r   r   r   r   Útorchmetrics.utilities.enumsr   r.   Útupler2   rL   ÚlistÚboolr<   r?   rB   rO   r   r%   r#   ú<module>rX      s  ðð #Ð "Ð "Ð "Ð "Ð "Ð "Ð "à €€€Ø Ð Ð Ð Ð Ð Ø %Ð %Ð %Ð %Ð %Ð %ð
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð <Ð ;Ð ;Ð ;Ð ;Ð ;ð)Øð)àð)ð ð)ð ð	)ð
 ˆ6�6ˆ>Ôð)ð )ð )ð )ð2 =AØ"&ØðHð HØðHàðHð ðHð ˜˜s D¨¤K°Ð7Ô8Ô9ð	Hð
 ˜3”-ðHð ðHð ˆ6�6ˆ>ÔðHð Hð Hð Hð` =AØ"&ØðSð SØðSàðSð ðSð ð	Sð
 ˜˜s D¨¤K°Ð7Ô8Ô9ðSð ˜3”-ðSð ðSð ˆ6�6ˆ>ÔðSð Sð Sð Sðv =AØ"&ØðRð RØðRàðRð ðRð ð	Rð
 ˜˜s D¨¤K°Ð7Ô8Ô9ðRð ˜3”-ðRð ðRð ˆ6�6ˆ>ÔðRð Rð Rð Rðt =AØ!%Ø $Ø"&Øð'ð 'Øð'àð'ð Ð6Ô
7ð'ð ð	'ð
 ˜˜s D¨¤K°Ð7Ô8Ô9ð'ð ˜#”ð'ð ˜”ð'ð ˜3”-ð'ð ð'ð ˆe�F˜F�NÔ#Ô$ð'ð 'ð 'ð 'ð 'ð 'r%   