
    3jW)                        S SK Jr  S SKJr  S SKrS SKJr   " S S\R                  5      r " S S\5      r " S	 S
\5      r	g)    )annotations)CallableN)nnc                  h   ^  \ rS rSr% SrS\S'   S\S'   SSU 4S jjjrSS jrSS jrSS	 jr	S
r
U =r$ )_HausdorffERLossBase   a  Base class for binary Hausdorff loss based on morphological erosion.

This is an Hausdorff Distance (HD) Loss that based on morphological erosion,which provided
a differentiable approximation of Hausdorff distance as stated in :cite:`karimi2019reducing`.
The code is refactored on top of `here <https://github.com/PatRyg99/HausdorffLoss/
    blob/master/hausdorff_loss.py>`__.

Args:
    alpha: controls the erosion rate in each iteration.
    k: the number of iterations of erosion.
    reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
        'none': no reduction will be applied, 'mean': the weighted mean of the output is taken,
        'sum': the output will be summed.

Returns:
    Estimated Hausdorff Loss.

zCallable[..., torch.Tensor]convmax_poolc                   > [         TU ]  5         Xl        X l        X0l        U R                  SU R                  5       5        g )Nkernel)super__init__alphak	reductionregister_buffer
get_kernel)selfr   r   r   	__class__s       Q/home/wildlama/miniconda3/lib/python3.13/site-packages/kornia/losses/hausdorff.pyr   _HausdorffERLossBase.__init__1   s4    
"Xt'89    c                    [         e),Get kernel for image morphology convolution.)NotImplementedError)r   s    r   r   _HausdorffERLossBase.get_kernel8   s    !!r   c                   X-
  S-  n[         R                  " U R                  UR                  UR                  S9n[         R
                  " X1R                  UR                  S9n[         R                  " X1R                  [         R                  S9nUR                  S5      S-
  S-  n[        U R                  5       H  nU R                  X4USS9n	U	S-
  n
SXS:  '   U R                  U
5      nU R                  U
* 5      * nX-
  S:g  nUR                  5       nUR                  5       (       a"  X-
  X-
  -  n[         R                  " Xm-  X5      n
XZUS-   U R                   -  -  -   nU
nM     U$ )N   devicedtype   )weightpaddinggroupsg      ?r   )torch	as_tensorr   r    r!   
zeros_like	ones_likeboolsizeranger   r	   r
   squeezeanywherer   )r   predtargetboundr   erodedmaskr%   r   dilationerosionerosion_maxerosion_min_to_normto_norm_erosion_to_fills                   r   perform_erosion$_HausdorffERLossBase.perform_erosion<   sI   1$T[[

S!!%4::Nu[[

K ;;r?Q&1,tvvAyywqyQHnG#$GaK  --0K=='22K#1a7H&&(G{{}} %,$9k>W#X ++do7GQ Q4::(===FE- 0 r   c                   UR                   SS UR                   SS :X  a9  UR                  S5      UR                  S5      :X  a  UR                  S5      S:X  d&  [        SUR                    SUR                    S35      eUR                  S5      UR                  5       R	                  5       :  a  [        S5      e[
        R                  " [        UR                  S5      5       Vs/ s H  nU R                  USS2X3S-   24   [
        R                  " X#:H  [
        R                  " SUR                  UR                  S	9[
        R                  " SUR                  UR                  S	95      5      PM     sn5      nU R                  S
:X  a  UR                  5       nU$ U R                  S:X  a  UR                  5       nU$ U R                  S:X  a   U$ [!        SU R                   S35      es  snf )aC  Compute Hausdorff loss.

Args:
    pred: predicted torch.Tensor with a shape of :math:`(B, C, H, W)` or :math:`(B, C, D, H, W)`.
        Each channel is as binary as: 1 -> fg, 0 -> bg.
    target: target torch.Tensor with a shape of :math:`(B, 1, H, W)` or :math:`(B, C, D, H, W)`.

Returns:
    Estimated Hausdorff Loss.

r   Nr   r#   zTPrediction and target need to be of same size, and target should not be one-hot.Got z and .zInvalid target value.r   meansumnonezreduction `z` has not been implemented yet.)shaper,   
ValueErrormaxitemr'   stackr-   r=   r0   tensorr    r!   r   rA   rB   r   )r   r1   r2   iouts        r   forward_HausdorffERLossBase.forward_   s    

12&,,qr"22tyy|v{{ST~7UZ`ZeZefgZhlmZmzzl%~Q8 
 99Q<&**,++--455kk tyy|,
 -A $$AAI&KKQv}}FLLQQv}}FLLQ -

 >>V#((*C 
 ^^u$'')C 
 ^^v% 
 &DNN3CCb&cdd)
s   (BG.)r   r   r   )g       @
   rA   )r   floatr   intr   strreturnNonerR   torch.Tensorr1   rU   r2   rU   rR   rU   )__name__
__module____qualname____firstlineno____doc____annotations__r   r   r=   rL   __static_attributes____classcell__r   s   @r   r   r      s5    & &%)): :"!F, ,r   r   c                  v   ^  \ rS rSrSr\R                  r\R                  " S5      r
SS jrSU 4S jjrSrU =r$ )	HausdorffERLoss   a  Binary Hausdorff loss based on morphological erosion.

Hausdorff Distance loss measures the maximum distance of a predicted segmentation boundary to
the nearest ground-truth edge pixel. For two segmentation point sets X and Y ,
the one-sided HD from X to Y is defined as:

.. math::

    hd(X,Y) = \max_{x \in X} \min_{y \in Y}||x - y||_2

Furthermore, the bidirectional HD is:

.. math::

    HD(X,Y) = max(hd(X, Y), hd(Y, X))

This is an Hausdorff Distance (HD) Loss that based on morphological erosion, which provided
a differentiable approximation of Hausdorff distance as stated in :cite:`karimi2019reducing`.
The code is refactored on top of `here <https://github.com/PatRyg99/HausdorffLoss/
blob/master/hausdorff_loss.py>`__.

Args:
    alpha: controls the erosion rate in each iteration.
    k: the number of iterations of erosion.
    reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
        'none': no reduction will be applied, 'mean': the weighted mean of the output is taken,
        'sum': the output will be summed.

Examples:
    >>> hdloss = HausdorffERLoss()
    >>> input = torch.randn(5, 3, 20, 20)
    >>> target = (torch.rand(5, 1, 20, 20) * 2).long()
    >>> res = hdloss(input, target)

r#   c                V    [         R                  " / SQ/ SQ/ SQ//5      nUS-  nUS   $ )r   r   r#   r   r#   r#   r#   g?N)r'   rI   )r   crossr   s      r   r   HausdorffERLoss.get_kernel   s-    y)Y?@Ad|r   c           	       > UR                  5       S:w  a  [        SUR                  5        S35      eUR                  5       UR                  S5      :  a2  UR	                  5       S:  a  UR
                  [        R                  :X  d@  [        SUR                  S5       SUR	                  5        SUR                  5        S	35      e[        TU ]%  X5      $ )
a  Compute Hausdorff loss.

Args:
    pred: predicted torch.Tensor with a shape of :math:`(B, C, H, W)`.
        Each channel is as binary as: 1 -> fg, 0 -> bg.
    target: target torch.Tensor with a shape of :math:`(B, 1, H, W)`.

Returns:
    Estimated Hausdorff Loss.

   zOnly 2D images supported. Got r@   r#   r   z+Expect long type target value in range (0, z). (z, ))
dimrE   rF   r,   minr!   r'   longr   rL   r   r1   r2   r   s      r   rL   HausdorffERLoss.forward   s     88:?=dhhj\KLL

tyy|+

0AfllV[V`V`F`=diil^4PVPZPZP\~]_`f`j`j`l_mmno  wt,,r    rT   rV   )rW   rX   rY   rZ   r[   r'   conv2dr	   r   AdaptiveMaxPool2dr
   r   rL   r]   r^   r_   s   @r   ra   ra      s3    "H <<D##A&H- -r   ra   c                  v   ^  \ rS rSrSr\R                  r\R                  " S5      r
SS jrSU 4S jjrSrU =r$ )	HausdorffERLoss3D   a  Binary 3D Hausdorff loss based on morphological erosion.

Hausdorff Distance loss measures the maximum distance of a predicted segmentation boundary to
the nearest ground-truth edge pixel. For two segmentation point sets X and Y ,
the one-sided HD from X to Y is defined as:

.. math::

    hd(X,Y) = \max_{x \in X} \min_{y \in Y}||x - y||_2

Furthermore, the bidirectional HD is:

.. math::

    HD(X,Y) = max(hd(X, Y), hd(Y, X))

This is a 3D Hausdorff Distance (HD) Loss that based on morphological erosion, which provided
a differentiable approximation of Hausdorff distance as stated in :cite:`karimi2019reducing`.
The code is refactored on top of `here <https://github.com/PatRyg99/HausdorffLoss/
blob/master/hausdorff_loss.py>`__.

Args:
    alpha: controls the erosion rate in each iteration.
    k: the number of iterations of erosion.
    reduction: Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
        'none': no reduction will be applied, 'mean': the weighted mean of the output is taken,
        'sum': the output will be summed.

Examples:
    >>> hdloss = HausdorffERLoss3D()
    >>> input = torch.randn(5, 3, 20, 20, 20)
    >>> target = (torch.rand(5, 1, 20, 20, 20) * 2).long()
    >>> res = hdloss(input, target)

r#   c                    [         R                  " / SQ/ SQ/ SQ//5      n[         R                  " / SQ/ SQ/ SQ//5      n[         R                  " X!U/S5      S-  nUS   $ )r   rd   re   )r   r   r   r#   g$I$I?N)r'   rI   rH   )r   rf   r3   r   s       r   r   HausdorffERLoss3D.get_kernel   sX    y)Y?@Ay)Y?@A eE2A6%@d|r   c                   > UR                  5       S:w  a  [        SUR                  5        S35      e[        TU ]  X5      $ )a  Compute 3D Hausdorff loss.

Args:
    pred: predicted torch.Tensor with a shape of :math:`(B, C, D, H, W)`.
        Each channel is as binary as: 1 -> fg, 0 -> bg.
    target: target torch.Tensor with a shape of :math:`(B, 1, D, H, W)`.

Returns:
    Estimated Hausdorff Loss.

   zOnly 3D images supported. Got r@   )rk   rE   r   rL   rn   s      r   rL   HausdorffERLoss3D.forward  s<     88:?=dhhj\KLLwt,,r   rp   rT   rV   )rW   rX   rY   rZ   r[   r'   conv3dr	   r   AdaptiveMaxPool3dr
   r   rL   r]   r^   r_   s   @r   rt   rt      s3    "H <<D##A&H- -r   rt   )

__future__r   typingr   r'   r   Moduler   ra   rt   rp   r   r   <module>r      sE   $ #   q299 qhA-* A-HA-, A-r   