
    3j                        S r SSKJr  SSKJr  SSKrSSKJs  Jr	  SSKJr  SSK
JrJr  SSKJr  SSKJr      S             SS	 jjr " S
 S\R$                  5      rg)u6   Module containing the Sørensen-Dice Coefficient loss.    )annotations)OptionalN)nn)KORNIA_CHECKKORNIA_CHECK_IS_TENSOR)mask_ignore_pixels)one_hotc                `   [        U 5        [        U R                  5      S:X  d  [        SU R                   35      eU R                  SS UR                  SS :X  d%  [        SU R                   SUR                   35      eU R                  UR                  :X  d%  [        SU R                   SUR                   35      eU R                  S   nS	S
1n[        X';   SU SU 35        [        R                  " U SS9n[        X5      u  p[        XR                  S   U R                  U R                  S9n
U	b  U	R                  S5        X-  n
X-  nUb  [        US5        [        UR                  S   U:H  =(       a    UR                  5       U:H  SU SUR                   35        [        UR                  U R                  :H  SUR                   SU R                   35        OU R                  U R                  S   5      nSnUS	:X  a!  S/UQ7nUR                  SSS5      nX-  nX-  n
[        R                   " X-  U5      n[        R                   " X-   U5      nSU-  X-   -  nU* S-   nUS
:X  a$  X-  R!                  S5      UR!                  5       -  n[        R"                  " U5      nU$ )u  Criterion that computes Sørensen-Dice Coefficient loss.

According to [1], we compute the Sørensen-Dice Coefficient as follows:

.. math::

    \text{Dice}(x, class) = \frac{2 |X \cap Y|}{|X| + |Y|}

Where:
   - :math:`X` expects to be the scores of each class.
   - :math:`Y` expects to be the one-hot torch.Tensor with the class labels.

the loss, is finally computed as:

.. math::

    \text{loss}(x, class) = 1 - \text{Dice}(x, class)

Reference:
    [1] https://en.wikipedia.org/wiki/S%C3%B8rensen%E2%80%93Dice_coefficient

Args:
    pred: logits torch.Tensor with shape :math:`(N, C, H, W)` where C = number of classes.
    target: labels torch.Tensor with shape :math:`(N, H, W)` where each value
      is in range :math:`0 ≤ targets[i] ≤ C-1`.
    average:
        Reduction applied in multi-class scenario:
        - ``'micro'`` [default]: Calculate the loss across all classes.
        - ``'macro'``: Calculate the loss for each class separately and average the metrics across classes.
    eps: Scalar to enforce numerical stabiliy.
    weight: weights for classes with shape :math:`(num\_of\_classes,)`.
    ignore_index: labels with this value are ignored in the loss computation.

Return:
    One-element torch.Tensor of the computed loss.

Example:
    >>> N = 5  # num_classes
    >>> pred = torch.randn(1, N, 3, 5, requires_grad=True)
    >>> target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)
    >>> output = dice_loss(pred, target)
    >>> output.backward()

   z,Invalid pred shape, we expect BxNxHxW. Got: Nz.pred and target shapes must be the same. Got: z and z1pred and target must be in the same device. Got:    micromacrozThe `average` has to be one of z. Got: )dim)num_classesdevicedtypez$weight must be torch.Tensor or None.r   z)weight shape must be (num_of_classes,): (z,), got z1weight and pred must be in the same device. Got: )      g       @g      ?)r   lenshape
ValueErrorr   r   Fsoftmaxr   r	   r   
unsqueeze_numelnew_onesviewtorchsummean)predtargetaverageepsweightignore_indexnum_of_classespossible_average	pred_softtarget_masktarget_one_hotdimsintersectioncardinality
dice_score	dice_losss                   L/home/wildlama/miniconda3/lib/python3.13/site-packages/kornia/losses/dice.pyr2   r2   %   s   h 4 tzz?aG

|TUU::bc?fll23//I$**UZ[a[g[gZhijj;;&--'LT[[MY^_e_l_l^mnooZZ]N),0OP`Oaahiphq.rs  ii!4I,VBF $+6zz!}UYU`U`hlhrhr#sN q!'5+	 v'MN\\!_.S6<<>^3S77GxPVP\P\~^	
 	MMT[[(?eTXT_T_S`a	

 tzz!}- #D'zDzRA&&	'099Y7>L))I6=K|#{'89Jc!I '',,R06::<?	

9%I    c                  X   ^  \ rS rSrSr    S         SU 4S jjjrSS jrSrU =r$ )	DiceLoss   u  Criterion that computes Sørensen-Dice Coefficient loss.

Dice-based objectives are common in medical and semantic segmentation because pixel classes
are often highly imbalanced. This loss directly optimizes region-level agreement.

Args:
    average: Reduction strategy for multi-class computation. Use "micro" to aggregate
        classes globally, or "macro" to average class-wise Dice scores.
    eps: Small constant added to the denominator for numerical stability.
    weight: Optional class-weight tensor of shape :math:`(C,)`.
    ignore_index: Label value to exclude from loss computation.

Shapes:
    - pred: :math:`(N, C, H, W)` where C is the number of classes.
    - target: :math:`(N, H, W)` where each value is in the range :math:`[0, C-1]`.
    - Output: scalar by default.
c                R   > [         TU ]  5         Xl        X l        X0l        X@l        g)a  Initialize the Dice loss module.

Args:
    average: Reduction strategy for multi-class computation.
    eps: Small constant added for numerical stability.
    weight: Optional class-weight tensor of shape :math:`(C,)`.
    ignore_index: Label value to exclude from loss computation.
N)super__init__r%   r&   r'   r(   )selfr%   r&   r'   r(   	__class__s        r3   r:   DiceLoss.__init__   s%     	(r4   c                p    [        XU R                  U R                  U R                  U R                  5      $ )u   Compute Dice loss from logits and integer labels.

Args:
    pred: The input prediction logits with shape :math:`(N, C, H, W)`.
    target: The ground truth labels with shape :math:`(N, H, W)`.

Returns:
    The computed Sørensen-Dice loss value.
)r2   r%   r&   r'   r(   )r;   r#   r$   s      r3   forwardDiceLoss.forward   s)     t||TXXt{{DL]L]^^r4   )r%   r&   r(   r'   r   g:0yE>Ni)
r%   strr&   floatr'   Optional[torch.Tensor]r(   Optional[int]returnNone)r#   torch.Tensorr$   rH   rF   rH   )	__name__
__module____qualname____firstlineno____doc__r:   r?   __static_attributes____classcell__)r<   s   @r3   r6   r6      s\    ( )-&*)) ) '	)
 $) 
) )*
_ 
_r4   r6   rA   )r#   rH   r$   rH   r%   rB   r&   rC   r'   rD   r(   rE   rF   rH   )rM   
__future__r   typingr   r    torch.nn.functionalr   
functionalr   kornia.core.checkr   r   kornia.losses._utilsr   kornia.losses.one_hotr	   r2   Moduler6    r4   r3   <module>rY      s   $ = "      B 3 ) %)"&t
tt t 
	t
 #t  t tn2_ryy 2_r4   