o
    .wi{I                     @   s   d dl mZ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mZ d dlmZmZmZmZmZmZ d dlmZ d dlmZ d d	lmZ d d
lmZ esTg dZG dd deZG dd deZ G dd deZ!G dd de	Z"dS )    )AnyOptionalUnion)Tensor)Literal)_ClassificationTaskWrapper)BinaryPrecisionRecallCurveMulticlassPrecisionRecallCurveMultilabelPrecisionRecallCurve)1_binary_specificity_at_sensitivity_arg_validation*_binary_specificity_at_sensitivity_compute5_multiclass_specificity_at_sensitivity_arg_validation._multiclass_specificity_at_sensitivity_compute5_multilabel_specificity_at_sensitivity_arg_validation._multilabel_specificity_at_sensitivity_compute)Metric)dim_zero_cat)ClassificationTask)_MATPLOTLIB_AVAILABLE)z#BinarySpecificityAtSensitivity.plotz'MulticlassSpecificityAtSensitivity.plotz'MultilabelSpecificityAtSensitivity.plotc                       s   e Zd ZU dZdZeed< dZee ed< dZ	eed< dZ
eed< d	Zeed
< 			ddedeeeee ef  dee dededdf fddZdeeef fddZ  ZS )BinarySpecificityAtSensitivityaH  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.

    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:
        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.

        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

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

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

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

    Fis_differentiableNhigher_is_betterfull_state_update        plot_lower_bound      ?plot_upper_boundTmin_sensitivity
thresholdsignore_indexvalidate_argskwargsreturnc                    s:   t  j||fddi| |rt||| || _|| _d S )Nr    F)super__init__r   r    r   )selfr   r   r   r    r!   	__class__ p/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/classification/specificity_sensitivity.pyr$   o   s
   
z'BinarySpecificityAtSensitivity.__init__c                 C   s4   | j du rt| jt| jfn| j}t|| j | jS zCompute metric.N)r   _catpredstargetconfmatr   r   r%   stater(   r(   r)   compute}   s   $z&BinarySpecificityAtSensitivity.computeNNT)__name__
__module____qualname____doc__r   bool__annotations__r   r   r   r   floatr   r   intlistr   r   r$   tupler1   __classcell__r(   r(   r&   r)   r   .   s0   
 :r   c                          e Zd ZU dZdZeed< dZee ed< dZ	eed< dZ
eed< d	Zeed
< dZeed< 			ddededeeeee ef  dee dededdf fddZdeeef fddZ  ZS )"MulticlassSpecificityAtSensitivitya  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.

    For multiclass the metric is calculated by iteratively treating each class as the positive class and all other
    classes as the negative, which is referred to as the one-vs-rest approach. One-vs-one is currently not supported by
    this metric.

    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:
        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.

        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

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

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


    Example:
        >>> from torchmetrics.classification import MulticlassSpecificityAtSensitivity
        >>> from torch import tensor
        >>> preds = 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 = tensor([0, 1, 3, 2])
        >>> metric = MulticlassSpecificityAtSensitivity(num_classes=5, min_sensitivity=0.5, thresholds=None)
        >>> metric(preds, target)
        (tensor([1., 1., 0., 0., 0.]), tensor([7.5000e-01, 7.5000e-01, 5.0000e-02, 5.0000e-02, 1.0000e+06]))
        >>> metric = MulticlassSpecificityAtSensitivity(num_classes=5, min_sensitivity=0.5, thresholds=5)
        >>> metric(preds, target)
        (tensor([1., 1., 0., 0., 0.]), tensor([7.5000e-01, 7.5000e-01, 0.0000e+00, 0.0000e+00, 1.0000e+06]))

    Fr   Nr   r   r   r   r   r   Classplot_legend_nameTnum_classesr   r   r   r    r!   r"   c                    >   t  jd|||dd| |rt|||| || _|| _d S )NF)rB   r   r   r    r(   )r#   r$   r   r    r   )r%   rB   r   r   r   r    r!   r&   r(   r)   r$      s   	
z+MulticlassSpecificityAtSensitivity.__init__c                 C   s8   | j du rt| jt| jfn| j}t|| j| j | jS r*   )r   r+   r,   r-   r.   r   rB   r   r/   r(   r(   r)   r1      s   $z*MulticlassSpecificityAtSensitivity.computer2   r3   r4   r5   r6   r   r7   r8   r   r   r   r   r9   r   rA   strr:   r   r;   r   r   r$   r<   r1   r=   r(   r(   r&   r)   r?      s6   
 Dr?   c                       r>   )"MultilabelSpecificityAtSensitivityas  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.

    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:
        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.

        validate_args: bool indicating if input arguments and tensors should be validated for correctness.
            Set to ``False`` for faster computations.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

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

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

    Example:
        >>> from torchmetrics.classification import MultilabelSpecificityAtSensitivity
        >>> from torch import tensor
        >>> preds = 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 = tensor([[1, 0, 1],
        ...                  [0, 0, 0],
        ...                  [0, 1, 1],
        ...                  [1, 1, 1]])
        >>> metric = MultilabelSpecificityAtSensitivity(num_labels=3, min_sensitivity=0.5, thresholds=None)
        >>> metric(preds, target)
        (tensor([1.0000, 0.5000, 1.0000]), tensor([0.7500, 0.6500, 0.3500]))
        >>> metric = MultilabelSpecificityAtSensitivity(num_labels=3, min_sensitivity=0.5, thresholds=5)
        >>> metric(preds, target)
        (tensor([1.0000, 0.5000, 1.0000]), tensor([0.7500, 0.5000, 0.2500]))

    Fr   Nr   r   r   r   r   r   LabelrA   T
num_labelsr   r   r   r    r!   r"   c                    rC   )NF)rH   r   r   r    r(   )r#   r$   r   r    r   )r%   rH   r   r   r   r    r!   r&   r(   r)   r$   4  s   	
z+MultilabelSpecificityAtSensitivity.__init__c                 C   s<   | j du rt| jt| jfn| j}t|| j| j | j| jS r*   )	r   r+   r,   r-   r.   r   rH   r   r   r/   r(   r(   r)   r1   E  s   $z*MultilabelSpecificityAtSensitivity.computer2   rD   r(   r(   r&   r)   rF      s6   
 BrF   c                   @   st   e Zd ZdZ					dded  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defddZdS )SpecificityAtSensitivitya*  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
    :class:`~torchmetrics.classification.BinarySpecificityAtSensitivity`,
    :class:`~torchmetrics.classification.MulticlassSpecificityAtSensitivity` and
    :class:`~torchmetrics.classification.MultilabelSpecificityAtSensitivity` for the specific details of each argument
    influence and examples.

    NTclstask)binary
multiclass
multilabelr   r   rB   rH   r   r    r!   r"   c           	      K   s   t |}|t jkrt||||fi |S |t jkr5t|ts)tdt| dt	|||||fi |S |t j
krUt|tsItdt| dt|||||fi |S td| d)zInitialize task metric.z+`num_classes` is expected to be `int` but `z was passed.`z*`num_labels` is expected to be `int` but `zTask z not supported!)r   from_strBINARYr   
MULTICLASS
isinstancer:   
ValueErrortyper?   
MULTILABELrF   )	rJ   rK   r   r   rB   rH   r   r    r!   r(   r(   r)   __new__\  s(   







z SpecificityAtSensitivity.__new__)NNNNT)r3   r4   r5   r6   rT   r   r9   r   r   r:   r;   r   r7   r   r   rV   r(   r(   r(   r)   rI   M  s8    	
rI   N)#typingr   r   r   torchr   typing_extensionsr    torchmetrics.classification.baser   2torchmetrics.classification.precision_recall_curver   r	   r
   >torchmetrics.functional.classification.specificity_sensitivityr   r   r   r   r   r   torchmetrics.metricr   torchmetrics.utilities.datar   r+   torchmetrics.utilities.enumsr   torchmetrics.utilities.importsr   __doctest_skip__r   r?   rF   rI   r(   r(   r(   r)   <module>   s     Ugc