o
    .wi\                     @   s4  d dl Z d dl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
mZmZ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 d dlmZ ded	efd
dZdedededed	eeef f
ddZ		d4dedeee e!e ef  dee  d	dfddZ"	d5deeeeef f dee dede d	eeef f
ddZ#			d6d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dZ%		d4d e dedeee e!e ef  dee  d	df
d!d"Z&deeeeef f d e dee ded	eeef f
d#d$Z'			d6d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%d&Z(		d4d'e dedeee e!e ef  dee  d	df
d(d)Z)deeeeef f d'e dee dee  ded	eeef fd*d+Z*			d6d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,d-Z+					d7d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eef eee ee ee f f fd0d1Z,					d7d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eef eee ee ee f f fd2d3Z-dS )8    N)ListOptionalUnion)Tensor)Literal)-_binary_precision_recall_curve_arg_validation%_binary_precision_recall_curve_format0_binary_precision_recall_curve_tensor_validation%_binary_precision_recall_curve_update1_multiclass_precision_recall_curve_arg_validation)_multiclass_precision_recall_curve_format4_multiclass_precision_recall_curve_tensor_validation)_multiclass_precision_recall_curve_update1_multilabel_precision_recall_curve_arg_validation)_multilabel_precision_recall_curve_format4_multilabel_precision_recall_curve_tensor_validation)_multilabel_precision_recall_curve_update)_binary_roc_compute_multiclass_roc_compute_multilabel_roc_compute)ClassificationTaskfprreturnc                 C   s   d|  S )zConvert  fprs to specificity.    )r   r   r   {/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/functional/classification/specificity_sensitivity.py_convert_fpr_to_specificity+   s   r   specificitysensitivity
thresholdsmin_sensitivityc                 C   s   ||k}|  s tjd| j| jd}tjd|j|jd}||fS | | || || } }}t| }| | || }}||fS )Ng        )devicedtypeg    .A)anytorchtensorr!   r"   argmax)r   r   r   r    indicesmax_specbest_thresholdidxr   r   r   _specificity_at_sensitivity0   s   
r+   ignore_indexc                 C   s@   t || t| tsd|   krdksn td|  d S d S Nr   r   zOExpected argument `min_sensitivity` to be an float in the [0,1] range, but got )r   
isinstancefloat
ValueError)r    r   r,   r   r   r   1_binary_specificity_at_sensitivity_arg_validationJ   s   
 r1   r   state	pos_labelc                 C   s(   t | ||\}}}t|}t||||S )N)r   r   r+   )r2   r   r    r3   r   r   r   r   r   r   *_binary_specificity_at_sensitivity_computeV   s   r4   Tpredstargetvalidate_argsc                 C   sH   |rt ||| t| || t| |||\} }}t| ||}t|||S )a  Compute the highest possible specificity value given the minimum sensitivity levels provided for binary tasks.

    This is done by first calculating the Receiver Operating Characteristic (ROC) curve for different thresholds and
    the find the specificity for a given sensitivity 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).

    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_sensitivity: float value specifying minimum sensitivity 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 `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:

        - specificity: a scalar tensor with the maximum specificity for the given sensitivity level
        - threshold: a scalar tensor with the corresponding threshold level

    Example:
        >>> from torchmetrics.functional.classification import binary_specificity_at_sensitivity
        >>> preds = torch.tensor([0, 0.5, 0.4, 0.1])
        >>> target = torch.tensor([0, 1, 1, 1])
        >>> binary_specificity_at_sensitivity(preds, target, min_sensitivity=0.5, thresholds=None)
        (tensor(1.), tensor(0.4000))
        >>> binary_specificity_at_sensitivity(preds, target, min_sensitivity=0.5, thresholds=5)
        (tensor(1.), tensor(0.2500))

    )r1   r	   r   r
   r4   )r5   r6   r    r   r,   r7   r2   r   r   r   !binary_specificity_at_sensitivitya   s   Ar8   num_classesc                 C   B   t | || t|tsd|  krdksn td| d S d S r-   )r   r.   r/   r0   )r9   r    r   r,   r   r   r   5_multiclass_specificity_at_sensitivity_arg_validation       r;   c                    s   t | |\}}dd |D }t| tr# fddt||D }n fddt||D }tdd |D }tdd |D |fS )Nc                 S      g | ]}t |qS r   r   .0fpr_r   r   r   
<listcomp>       zB_multiclass_specificity_at_sensitivity_compute.<locals>.<listcomp>c                       g | ]\}}t || qS r   r+   r@   spsnr    r   r   r   rB          c                        g | ]\}}}t ||| qS r   rE   r@   rG   rH   tr    r   r   rB          c                 S      g | ]}|d  qS r   r   r@   rr   r   r   rB      rC   c                 S   rP   r   r   rR   r   r   r   rB      rC   )r   r.   r   zipr$   stack)r2   r9   r   r    r   r   r   resr   rI   r   ._multiclass_specificity_at_sensitivity_compute   s   


rX   c                 C   sR   |rt |||| t| ||| t| ||||\} }}t| |||}t||||S )a  Compute the highest possible specificity value given minimum sensitivity level provided for multiclass tasks.

    This is done by first calculating the Receiver Operating Characteristic (ROC) curve for different thresholds and the
    find the specificity for a given sensitivity 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_sensitivity: float value specifying minimum sensitivity 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 `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

        - recall: an 1d tensor of size (n_classes, ) with the maximum recall for the given precision 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_specificity_at_sensitivity
        >>> 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_specificity_at_sensitivity(preds, target, num_classes=5, min_sensitivity=0.5, thresholds=None)
        (tensor([1., 1., 0., 0., 0.]), tensor([7.5000e-01, 7.5000e-01, 5.0000e-02, 5.0000e-02, 1.0000e+06]))
        >>> multiclass_specificity_at_sensitivity(preds, target, num_classes=5, min_sensitivity=0.5, thresholds=5)
        (tensor([1., 1., 0., 0., 0.]), tensor([7.5000e-01, 7.5000e-01, 0.0000e+00, 0.0000e+00, 1.0000e+06]))

    )r;   r   r   r   rX   )r5   r6   r9   r    r   r,   r7   r2   r   r   r   %multiclass_specificity_at_sensitivity   s   F

rY   
num_labelsc                 C   r:   r-   )r   r.   r/   r0   )rZ   r    r   r,   r   r   r   5_multilabel_specificity_at_sensitivity_arg_validation  r<   r[   c           	         s   t | ||\}}dd |D }t| tr$ fddt||D }n fddt||D }tdd |D }tdd |D |fS )Nc                 S   r=   r   r>   r?   r   r   r   rB   3  rC   zB_multilabel_specificity_at_sensitivity_compute.<locals>.<listcomp>c                    rD   r   rE   rF   rI   r   r   rB   5  rJ   c                    rK   r   rE   rL   rN   r   r   rB   :  rO   c                 S   rP   rQ   r   rR   r   r   r   rB   >  rC   c                 S   rP   rT   r   rR   r   r   r   rB   ?  rC   )r   r.   r   rU   r$   rV   )	r2   rZ   r   r,   r    r   r   r   rW   r   rI   r   ._multilabel_specificity_at_sensitivity_compute+  s   


r\   c                 C   sT   |rt |||| t| ||| t| ||||\} }}t| |||}t|||||S )a  Compute the highest possible specificity value given minimum sensitivity level provided for multilabel tasks.

    This is done by first calculating the Receiver Operating Characteristic (ROC) curve for different thresholds and
    the find the specificity for a given sensitivity 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_sensitivity: float value specifying minimum sensitivity 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 `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

        - specificity: an 1d tensor of size (n_classes, ) with the maximum recall for the given precision
            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_specificity_at_sensitivity
        >>> 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_specificity_at_sensitivity(preds, target, num_labels=3, min_sensitivity=0.5, thresholds=None)
        (tensor([1.0000, 0.5000, 1.0000]), tensor([0.7500, 0.6500, 0.3500]))
        >>> multilabel_specificity_at_sensitivity(preds, target, num_labels=3, min_sensitivity=0.5, thresholds=5)
        (tensor([1.0000, 0.5000, 1.0000]), tensor([0.7500, 0.5000, 0.2500]))

    )r[   r   r   r   r\   )r5   r6   rZ   r    r   r,   r7   r2   r   r   r   %multilabel_specificity_at_sensitivityC  s   J

r]   task)binary
multiclass
multilabelc	           	      C   s*   t jdtdd t| ||||||||d	S )a	  Compute the highest possible specificity value given the minimum sensitivity thresholds provided.

    .. warning::
        This function was deprecated in v1.3.0 of Torchmetrics and will be removed in v2.0.0.
        Use `specificity_at_sensitivity` instead.

    zSThis method has will be removed in 2.0.0. Use `specificity_at_sensitivity` instead.r   )
stacklevel	r5   r6   r^   r    r   r9   rZ   r,   r7   )warningswarnDeprecationWarningspecificity_at_sensitivityrc   r   r   r   specicity_at_sensitivity  s    rh   c	           	      C   s   t |}|t jkrt| |||||S |t jkr1t|ts'tdt| dt	| ||||||S |t j
krOt|tsEtdt| dt| ||||||S td| )aQ  Compute the highest possible specificity value given the minimum sensitivity thresholds provided.

    This is done by first calculating the Receiver Operating Characteristic (ROC) curve for different thresholds and
    the find the specificity for a given sensitivity 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_specificity_at_sensitivity`,
    :func:`~torchmetrics.functional.classification.multiclass_specificity_at_sensitivity` and
    :func:`~torchmetrics.functional.classification.multilabel_specificity_at_sensitivity` 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 `zNot handled value: )r   from_strBINARYr8   
MULTICLASSr.   intr0   typerY   
MULTILABELr]   rc   r   r   r   rg     s$   





rg   )NNrT   )NNT)NNNNT).rd   typingr   r   r   r$   r   typing_extensionsr   =torchmetrics.functional.classification.precision_recall_curver   r   r	   r
   r   r   r   r   r   r   r   r   *torchmetrics.functional.classification.rocr   r   r   torchmetrics.utilities.enumsr   r   r/   tupler+   rl   listr1   r4   boolr8   r;   rX   rY   r[   r\   r]   rh   rg   r   r   r   r   <module>   s  8






L




S




Y	,

)	,
