
    ig"                     f   d dl 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ed	ed
eed      ded   deed      ddfdZ	 ddededed	eded   deeeef   fdZ	 	 	 ddeded
eed      deed      dee   defdZ	 	 	 	 ddededed	ed
eed      ded   deed      defdZy)    )OptionalN)Tensor)Literal)_segmentation_inputs_format)rank_zero_warn)_safe_dividenum_classesinclude_backgroundaveragemicromacroweightednoneinput_formatone-hotindexmixedaggregation_level
samplewiseglobalreturnc                    t        | t              r| dk  rt        d|  d      t        |t              st        d| d      g d}|||vrt        d| d| d      |d	vrt        d
| d      |dvrt        d|       y)z%Validate the arguments of the metric.r   zDExpected argument `num_classes` must be a positive integer, but got .zBExpected argument `include_background` must be a boolean, but got r   Nz)Expected argument `average` to be one of z or None, but got r   zSExpected argument `input_format` to be one of 'one-hot', 'index', 'mixed', but got r   zSExpected argument `aggregation_level` to be one of `samplewise`, `global`, but got )
isinstanceint
ValueErrorbool)r	   r
   r   r   r   allowed_averages         ~/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/functional/segmentation/dice.py_dice_score_validate_argsr#      s     k3';!+;_`k_llmnoo($/]^p]qqrstt<Owo=D_DUUghogppqrss88abnaoopq
 	
  88absatu
 	
 9    predstargetc                    t        | ||||      \  } }t        t        d|j                              }t	        j
                  | |z  |      }t	        j
                  ||      }t	        j
                  | |      }d|z  }	||z   }
|}|	|
|fS )z8Update the state with the current prediction and target.   dim)r   listrangendimtorchsum)r%   r&   r	   r
   r   reduce_axisintersection
target_sumpred_sum	numeratordenominatorsupports               r"   _dice_score_updater7   2   s     0v?QS^`lmME6uQ,-K99UV^=L6{3JyyK0HL IZ'KGk7**r$   r4   r5   r6   c                 .   |dk(  rgt        j                  | d      j                  d      } t        j                  |d      j                  d      }|t        j                  |d      nd}|dk(  r<t        j                  | d      } t        j                  |d      }t        | |d      S t        | |d      }|d	k(  rt        j                  |d      S |d
k(  rt        |t         j                        st        dt        |       d      t        |t        j                  |dd      d      }|j                         j                  d      }t        j                  ||z  d      }t         j                  ||<   |S |dv r|S t        d| d      )z:Compute the Dice score from the numerator and denominator.r   r   r)   Nr   nan)zero_divisionr   r   z1Expected argument `support` to be a tensor, got: r   T)r*   keepdim)r   NzInvalid value for `average`: )r.   r/   	unsqueezer   nanmeanr   r   r   typeisnanallnansumr:   )r4   r5   r   r   r6   diceweightsnan_masks           r"   _dice_score_computerF   G   sh    H$IIiQ/99!<	ii3==a@/6/B%))G+'IIiR0	ii4I{%HH	;eDD'}}Tr***'5<<0PQUV]Q^P__`abbw		'r4(P`ef::<###+||D7N3X. 
4WIQ?
@@r$   c                     |dk(  rt        dt               t        |||||       t        | ||||      \  }}}	t	        |||||	      S )a  Compute the Dice score for semantic segmentation.

    Args:
        preds: Predictions from model
        target: Ground truth values
        num_classes: Number of classes
        include_background: Whether to include the background class in the computation
        average: The method to average the dice score. Options are ``"micro"``, ``"macro"``, ``"weighted"``, ``"none"``
            or ``None``. This determines how to average the dice score across different classes.
        input_format: What kind of input the function receives.
            Choose between ``"one-hot"`` for one-hot encoded tensors, ``"index"`` for index tensors
            or ``"mixed"`` for one one-hot encoded and one index tensor
        aggregation_level: The level at which to aggregate the dice score. Options are ``"samplewise"`` or ``"global"``.
            For ``"samplewise"`` the dice score is computed for each sample and then averaged. For ``"global"`` the dice
            score is computed globally over all samples.

    Returns:
        The Dice score.

    Example (with one-hot encoded tensors):
        >>> from torch import randint
        >>> from torchmetrics.functional.segmentation import dice_score
        >>> _ = torch.manual_seed(42)
        >>> preds = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 prediction
        >>> target = randint(0, 2, (4, 5, 16, 16))  # 4 samples, 5 classes, 16x16 target
        >>> # dice score micro averaged over all classes
        >>> dice_score(preds, target, num_classes=5, average="micro")
        tensor([0.4842, 0.4968, 0.5053, 0.4902])
        >>> # dice score per sample and class
        >>> dice_score(preds, target, num_classes=5, average="none")
        tensor([[0.4724, 0.5185, 0.4710, 0.5062, 0.4500],
                [0.4571, 0.4980, 0.5191, 0.4380, 0.5649],
                [0.5428, 0.4904, 0.5358, 0.4830, 0.4724],
                [0.4715, 0.4925, 0.4797, 0.5267, 0.4788]])
        >>> # global dice score over all samples with macro averaging
        >>> dice_score(preds, target, num_classes=5, average="macro", aggregation_level="global")
        tensor([0.4942])

    Example (with index tensors):
        >>> from torch import randint
        >>> from torchmetrics.functional.segmentation import dice_score
        >>> _ = torch.manual_seed(42)
        >>> preds = randint(0, 5, (4, 16, 16))  # 4 samples, 5 classes, 16x16 prediction
        >>> target = randint(0, 5, (4, 16, 16))  # 4 samples, 5 classes, 16x16 target
        >>> # dice score micro averaged over all classes
        >>> dice_score(preds, target, num_classes=5, average="micro", input_format="index")
        tensor([0.2031, 0.1914, 0.2266, 0.1641])
        >>> # dice score per sample and class
        >>> dice_score(preds, target, num_classes=5, average="none", input_format="index")
        tensor([[0.1731, 0.1667, 0.2400, 0.2424, 0.1947],
                [0.2245, 0.2247, 0.2321, 0.1132, 0.1682],
                [0.2500, 0.2476, 0.1887, 0.1818, 0.2718],
                [0.1308, 0.1800, 0.1980, 0.1607, 0.1522]])
        >>> # global dice score over all samples with macro averaging
        >>> dice_score(preds, target, num_classes=5, average="macro", aggregation_level="global", input_format="index")
        tensor([0.1965])

    r   zdice_score metric currently defaults to `average=micro`, but will change to`average=macro` in the v1.9 release. If you've explicitly set this parameter, you can ignore this warning.)r   r6   )r   UserWarningr#   r7   rF   )
r%   r&   r	   r
   r   r   r   r4   r5   r6   s
             r"   
dice_scorerI   i   sd    F 'U 		
 k+=wVgh&8Ugiu&v#I{Gy+wRcmtuur$   )r   r   r   )r   )r   r   N)Tr   r   r   )typingr   r.   r   typing_extensionsr   *torchmetrics.functional.segmentation.utilsr   torchmetrics.utilitiesr   torchmetrics.utilities.computer   r   r    r#   tupler7   rF   rI    r$   r"   <module>rQ      s      % R 1 7 HO9BCO


 gBCD
 56	

  (> ?@
 

< :C+++ + 	+
 56+ 666!"+0 HOCO $AAA gBCDA  (> ?@	A
 fA AL  $GN9BCOLvLvLv Lv 	Lv
 gBCDLv 56Lv  (> ?@Lv Lvr$   