o
    .wi5                     @   s   d dl m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 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 esOdgZG dd deZG dd deZG dd deZdS )    )Sequence)AnyOptionalUnionN)Tensor)Literal)_binary_groups_stat_scores"_compute_binary_demographic_parity!_compute_binary_equal_opportunity)"_binary_stat_scores_arg_validation)Metric)rank_zero_warn)_MATPLOTLIB_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEBinaryFairness.plotc                   @   sn   e Zd ZU dZeed< eed< eed< eed< deddfd	d
Zdee	e
je
je
je
jf  ddfddZdS )_AbstractGroupStatScoreszECreate and update states for computing group stats tp, fp, tn and fn.tpfptnfn
num_groupsreturnNc                    sX    fdd}| j d| dd | j d| dd | j d| dd | j d| dd d S )	Nc                      s   t j t jdS )N)dtype)torchzeroslong r   r   g/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/classification/group_fairness.py<lambda>-   s    z9_AbstractGroupStatScores._create_states.<locals>.<lambda>r   sum)dist_reduce_fxr   r   r   )	add_state)selfr   defaultr   r   r   _create_states,   s
   z'_AbstractGroupStatScores._create_statesgroup_statsc                 C   sj   t |D ].\}}|\}}}}| j|  |7  < | j|  |7  < | j|  |7  < | j|  |7  < qd S )N)	enumerater   r   r   r   )r$   r'   groupstatsr   r   r   r   r   r   r   _update_states3   s   z'_AbstractGroupStatScores._update_states)__name__
__module____qualname____doc__r   __annotations__intr&   listtupler   r+   r   r   r   r   r   $   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Z	e
ed< dZe
ed	< 	
		ddede
dee d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f fddZ  ZS )BinaryGroupStatRatesa  Computes the true/false positives and true/false negatives rates for binary classification by group.

    Related to `Type I and Type II errors`_.

    Accepts the following input tensors:

    - ``preds`` (int or float tensor): ``(N, ...)``. If preds is a floating point tensor with values outside
      [0,1] range we consider the input to be logits and will auto apply sigmoid per element. Additionally,
      we convert to int tensor with thresholding using the value in ``threshold``.
    - ``target`` (int tensor): ``(N, ...)``.
    - ``groups`` (int tensor): ``(N, ...)``. The group identifiers should be ``0, 1, ..., (num_groups - 1)``.

    The additional dimensions are flatted along the batch dimension.

    Args:
        num_groups: The number of groups.
        threshold: Threshold for transforming probability to binary {0,1} predictions.
        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.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Returns:
        The metric returns a dict with a group identifier as key and a tensor with the tp, fp, tn and fn rates as value.

    Example (preds is int tensor):
        >>> from torchmetrics.classification import BinaryGroupStatRates
        >>> target = torch.tensor([0, 1, 0, 1, 0, 1])
        >>> preds = torch.tensor([0, 1, 0, 1, 0, 1])
        >>> groups = torch.tensor([0, 1, 0, 1, 0, 1])
        >>> metric = BinaryGroupStatRates(num_groups=2)
        >>> metric(preds, target, groups)
        {'group_0': tensor([0., 0., 1., 0.]), 'group_1': tensor([1., 0., 0., 0.])}

    Example (preds is float tensor):
        >>> from torchmetrics.classification import BinaryGroupStatRates
        >>> target = torch.tensor([0, 1, 0, 1, 0, 1])
        >>> preds = torch.tensor([0.11, 0.84, 0.22, 0.73, 0.33, 0.92])
        >>> groups = torch.tensor([0, 1, 0, 1, 0, 1])
        >>> metric = BinaryGroupStatRates(num_groups=2)
        >>> metric(preds, target, groups)
        {'group_0': tensor([0., 0., 1., 0.]), 'group_1': tensor([1., 0., 0., 0.])}

    Fis_differentiablehigher_is_betterfull_state_update        plot_lower_bound      ?plot_upper_bound      ?NTr   	thresholdignore_indexvalidate_argskwargsr   c                    sb   t    |rt|d| t|ts|dk rtd| || _|| _|| _|| _	| 
| j d S )Nglobal   CExpected argument `num_groups` to be an int larger than 1, but got )super__init__r   
isinstancer1   
ValueErrorr   r=   r>   r?   r&   )r$   r   r=   r>   r?   r@   	__class__r   r   rE   p   s   
zBinaryGroupStatRates.__init__predstargetgroupsc                 C   s*   t |||| j| j| j| j}| | dS )a"  Update state with predictions, target and group identifiers.

        Args:
            preds: Tensor with predictions.
            target: Tensor with true labels.
            groups: Tensor with group identifiers. The group identifiers should be ``0, 1, ..., (num_groups - 1)``.

        N)r   r   r=   r>   r?   r+   r$   rJ   rK   rL   r'   r   r   r   update   s   	zBinaryGroupStatRates.updatec                 C   s0   t j| j| j| j| jfdd}dd t|D S )zSCompute tp, fp, tn and fn rates based on inputs passed in to ``update`` previously.   )dimc                 S   s$   i | ]\}}d | ||   qS )group_)r!   ).0ir)   r   r   r   
<dictcomp>   s   $ z0BinaryGroupStatRates.compute.<locals>.<dictcomp>)r   stackr   r   r   r   r(   )r$   resultsr   r   r   compute   s   zBinaryGroupStatRates.compute)r<   NT)r,   r-   r.   r/   r5   boolr0   r6   r7   r9   floatr;   r1   r   r   rE   r   rN   dictstrrW   __classcell__r   r   rH   r   r4   <   s6   
 -
r4   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Z	e
ed< dZe
ed	< 	
			d#deded de
dee d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jf fddZ	d$deeeee f  d ee defd!d"Z  ZS )%BinaryFairnessa  Computes `Demographic parity`_ and `Equal opportunity`_ ratio for binary classification problems.

    Accepts the following input tensors:

    - ``preds`` (int or float tensor): ``(N, ...)``. If preds is a floating point tensor with values outside
      [0,1] range we consider the input to be logits and will auto apply sigmoid per element. Additionally,
      we convert to int tensor with thresholding using the value in ``threshold``.
    - ``groups`` (int tensor): ``(N, ...)``. The group identifiers should be ``0, 1, ..., (num_groups - 1)``.
    - ``target`` (int tensor): ``(N, ...)``.

    The additional dimensions are flatted along the batch dimension.

    This class computes the ratio between positivity rates and true positives rates for different groups.
    If more than two groups are present, the disparity between the lowest and highest group is reported.
    A disparity between positivity rates indicates a potential violation of demographic parity, and between
    true positive rates indicates a potential violation of equal opportunity.

    The lowest rate is divided by the highest, so a lower value means more discrimination against the numerator.
    In the results this is also indicated as the key of dict is {metric}_{identifier_low_group}_{identifier_high_group}.

    Args:
        num_groups: The number of groups.
        task: The task to compute. Can be either ``demographic_parity`` or ``equal_opportunity`` or ``all``.
        threshold: Threshold for transforming probability to binary {0,1} predictions.
        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.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Returns:
        The metric returns a dict where the key identifies the metric and groups with the lowest and highest true
        positives rates as follows: {metric}__{identifier_low_group}_{identifier_high_group}.
        The value is a tensor with the disparity rate.

    Example (preds is int tensor):
        >>> from torchmetrics.classification import BinaryFairness
        >>> target = torch.tensor([0, 1, 0, 1, 0, 1])
        >>> preds = torch.tensor([0, 1, 0, 1, 0, 1])
        >>> groups = torch.tensor([0, 1, 0, 1, 0, 1])
        >>> metric = BinaryFairness(2)
        >>> metric(preds, target, groups)
        {'DP_0_1': tensor(0.), 'EO_0_1': tensor(0.)}

    Example (preds is float tensor):
        >>> from torchmetrics.classification import BinaryFairness
        >>> target = torch.tensor([0, 1, 0, 1, 0, 1])
        >>> preds = torch.tensor([0.11, 0.84, 0.22, 0.73, 0.33, 0.92])
        >>> groups = torch.tensor([0, 1, 0, 1, 0, 1])
        >>> metric = BinaryFairness(2)
        >>> metric(preds, target, groups)
        {'DP_0_1': tensor(0.), 'EO_0_1': tensor(0.)}

    Fr5   r6   r7   r8   r9   r:   r;   allr<   NTr   taskdemographic_parityequal_opportunityr^   r=   r>   r?   r@   r   c                    s   t    |dvrtd| d|rt|d| t|ts)|dk r)td| || _|| _|| _|| _	|| _
| | j d S )Nr`   zfExpected argument `task` to either be ``demographic_parity``,``equal_opportunity`` or ``all`` but got .rA   rB   rC   )rD   rE   rG   r   rF   r1   r   r_   r=   r>   r?   r&   )r$   r   r_   r=   r>   r?   r@   rH   r   r   rE      s"   
	zBinaryFairness.__init__rJ   rK   rL   c                 C   sR   | j dkr|durtdt t|j}t|||| j| j| j	| j
}| | dS )a  Update state with predictions, groups, and target.

        Args:
            preds: Tensor with predictions.
            target: Tensor with true labels.
            groups: Tensor with group identifiers. The group identifiers should be ``0, 1, ..., (num_groups - 1)``.

        ra   Nz6The task demographic_parity does not require a target.)r_   r   UserWarningr   r   shaper   r   r=   r>   r?   r+   rM   r   r   r   rN      s   
	
zBinaryFairness.updatec                 C   s~   | j dkrt| j| j| j| jS | j dkr t| j| j| j| jS | j dkr=i t| j| j| j| jt| j| j| j| jS dS )zMCompute fairness criteria based on inputs passed in to ``update`` previously.ra   rb   r^   N)r_   r	   r   r   r   r   r
   )r$   r   r   r   rW     s   


zBinaryFairness.computevalaxc                 C   s   |  ||S )ad  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 object and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> from torch import ones, rand, randint
            >>> # Example plotting a single value
            >>> from torchmetrics.classification import BinaryFairness
            >>> metric = BinaryFairness(2)
            >>> metric.update(rand(50), randint(2, (50,)), ones(50).long())
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> from torch import ones, rand, randint
            >>> # Example plotting multiple values
            >>> from torchmetrics.classification import BinaryFairness
            >>> metric = BinaryFairness(2)
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(rand(50), randint(2, (50,) ), ones(50).long()))
            >>> fig_, ax_ = metric.plot(values)

        )_plot)r$   rf   rg   r   r   r   plot  s   (r   )r^   r<   NT)NN)r,   r-   r.   r/   r5   rX   r0   r6   r7   r9   rY   r;   r1   r   r   r   rE   r   rN   rZ   r[   r   rW   r   r   r   r   ri   r\   r   r   rH   r   r]      sL   
 6
r]   )collections.abcr   typingr   r   r   r   r   typing_extensionsr   5torchmetrics.functional.classification.group_fairnessr   r	   r
   2torchmetrics.functional.classification.stat_scoresr   torchmetrics.metricr   torchmetrics.utilitiesr   torchmetrics.utilities.importsr   torchmetrics.utilities.plotr   r   __doctest_skip__r   r4   r]   r   r   r   r   <module>   s    b