o
    oix                     @  sL   d dl mZ d dlmZmZ d dlmZmZ ddd
dZG dd deZ	dS )    )annotations)ModuleTensor)KORNIA_CHECKKORNIA_CHECK_SHAPEsumimgr   	reductionstrreturnc                 C  s@  t | tstdt|  t| g d t|dv d| d | dddddf | ddd	ddf  }| dddddf | ddddd	f  }| }| }d
}|dkr|  rt|| j	|d}|| j	|d}|| S |
 j	|d}|
 j	|d}|| S |dkr|j|d}|j|d}|| S td)a  Compute Total Variation according to [1].

    Args:
        img: the input image with shape :math:`(*, H, W)`.
        reduction : Specifies the reduction to apply to the output: ``'mean'`` | ``'sum'``.
         ``'mean'``: the sum of the output will be divided by the number of elements
         in the output, ``'sum'``: the output will be summed.

    Return:
         a tensor with shape :math:`(*,)`.

    Examples:
        >>> total_variation(torch.ones(4, 4))
        tensor(0.)
        >>> total_variation(torch.ones(2, 5, 3, 4, 4)).shape
        torch.Size([2, 5, 3])

    .. note::
       See a working example `here <https://kornia.github.io/tutorials/nbs/total_variation_denoising.html>`__.
       Total Variation is formulated with summation, however this is not resolution invariant.
       Thus, `reduction='mean'` was added as an optional reduction method.

    Reference:
        [1] https://en.wikipedia.org/wiki/Total_variation

    zNot a Tensor type. Got: )*HW)meanr   z7Expected reduction to be one of 'mean'/'sum', but got 'z'..   N)r   r   )dimr   zInvalid reduction option.)
isinstancer   	TypeErrortyper   r   absis_floating_pointtor   floatr   NotImplementedError)r   r	   
pixel_dif1
pixel_dif2res1res2reduce_axes r!   Q/home/ubuntu/.local/lib/python3.10/site-packages/kornia/losses/total_variation.pytotal_variation   s,   
,,
r#   c                   @  s   e Zd ZdZdddZdS )	TotalVariationa  Compute the Total Variation according to [1].

    Shape:
        - Input: :math:`(*, H, W)`.
        - Output: :math:`(*,)`.

    Examples:
        >>> tv = TotalVariation()
        >>> output = tv(torch.ones((2, 3, 4, 4), requires_grad=True))
        >>> output.data
        tensor([[0., 0., 0.],
                [0., 0., 0.]])
        >>> output.sum().backward()  # grad can be implicitly created only for scalar outputs

    Reference:
        [1] https://en.wikipedia.org/wiki/Total_variation

    r   r   r   c                 C  s   t |S )N)r#   )selfr   r!   r!   r"   forwarde   s   zTotalVariation.forwardN)r   r   r   r   )__name__
__module____qualname____doc__r&   r!   r!   r!   r"   r$   Q   s    r$   N)r   )r   r   r	   r
   r   r   )

__future__r   kornia.corer   r   kornia.core.checkr   r   r#   r$   r!   r!   r!   r"   <module>   s
   9