# LICENSE HEADER MANAGED BY add-license-header
#
# Copyright 2018 Kornia Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

from typing import Any, Dict, List, Optional, Tuple, Union

import torch

from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
from kornia.core.ops import eye_like
from kornia.core.utils import _to_device_nonblocking
from kornia.geometry.transform import affine
from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center


class RandomRotation(GeometricAugmentationBase2D):
    r"""Rotate images by a random angle in degrees, applied per sample with probability ``p`` (default 0.5).

    ``output = RandomRotation(degrees, ...)(input)`` rotates selected images of shape ``(B, C, H, W)``
    about their centers. Use :class:`RandomRotation90` when only quarter turns are wanted.

    .. image:: _static/img/RandomRotation.png

    .. note::
        Unlike torchvision's ``RandomRotation``, which rotates every image, this class rotates each sample with
        probability ``p``, 0.5 by default; with ``same_on_batch=True`` one draw decides for the whole batch. Pass
        ``p=1.0`` to rotate every sample.

    Args:
        degrees: range of degrees to select from. If degrees is a number the
          range of degrees to select from will be (-degrees, +degrees).
        resample: Default: the interpolation mode.
        same_on_batch: apply the same transformation across the batch.
        align_corners: interpolation flag.
        p: probability of applying the transformation to each sample.
        keepdim: whether to keep the output shape the same as input (True) or broadcast it
                 to the batch form (False).

    Shape:
        - Input: ``(C, H, W)`` or ``(B, C, H, W)``, Optional: ``(B, 3, 3)``
        - Output: ``(B, C, H, W)``

    Convention:
        - See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
        - a positive sampled angle rotates the displayed image counter-clockwise, as
          :func:`~kornia.geometry.transform.rotate` does and unlike :class:`RandomAffine`
          (:doc:`/get-started/conventions`, `#4408 <https://github.com/kornia/kornia/issues/4408>`_).

    .. note::
        This function internally uses :func:`kornia.geometry.transform.affine`.

    See Also:
        - :class:`RandomRotation90`: samples only multiples of 90 degrees.
        - :class:`RandomRotation3D`: rotates volumes by a sampled 3D axis-angle vector.

    Examples:
        >>> rng = torch.manual_seed(0)
        >>> input = torch.tensor([[1., 0., 0., 2.],
        ...                       [0., 0., 0., 0.],
        ...                       [0., 1., 2., 0.],
        ...                       [0., 0., 1., 2.]])
        >>> aug = RandomRotation(degrees=45.0, p=1.)
        >>> out = aug(input)
        >>> out
        tensor([[[[0.9824, 0.0088, 0.0000, 1.9649],
                  [0.0000, 0.0029, 0.0000, 0.0176],
                  [0.0029, 1.0000, 1.9883, 0.0000],
                  [0.0000, 0.0088, 1.0117, 1.9649]]]])
        >>> aug.transform_matrix
        tensor([[[ 1.0000, -0.0059,  0.0088],
                 [ 0.0059,  1.0000, -0.0088],
                 [ 0.0000,  0.0000,  1.0000]]])
        >>> inv = aug.inverse(out)

    To apply the exact augmenation again, you may take the advantage of the previous parameter state:
        >>> input = torch.randn(1, 3, 32, 32)
        >>> aug = RandomRotation(degrees=45.0, p=1.)
        >>> (aug(input) == aug(input, params=aug._params)).all()
        tensor(True)

    """

    # Note: Extra params, center=None, fill=0 in TorchVision

    def __init__(
        self,
        degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],
        resample: Union[str, int, Resample] = Resample.BILINEAR.name,
        same_on_batch: bool = False,
        align_corners: bool = True,
        p: float = 0.5,
        keepdim: bool = False,
    ) -> None:
        super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
        self._param_generator = rg.PlainUniformGenerator((degrees, "degrees", 0.0, (-360.0, 360.0)))

        self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}

    def compute_transformation(
        self, input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, Any]
    ) -> torch.Tensor:
        # TODO: Update to use `get_rotation_matrix2d`
        angles: torch.Tensor = _to_device_nonblocking(params["degrees"], input.device, input.dtype)

        center: torch.Tensor = _compute_tensor_center(input)
        rotation_mat: torch.Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))

        # rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix
        trans_mat: torch.Tensor = eye_like(3, input, shared_memory=False)
        trans_mat[:, 0] = rotation_mat[:, 0]
        trans_mat[:, 1] = rotation_mat[:, 1]

        return trans_mat

    def apply_transform(
        self,
        input: torch.Tensor,
        params: Dict[str, torch.Tensor],
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        if not isinstance(transform, torch.Tensor):
            raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")

        return affine(input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"])

    def inverse_transform(
        self,
        input: torch.Tensor,
        flags: Dict[str, Any],
        transform: Optional[torch.Tensor] = None,
        size: Optional[Tuple[int, int]] = None,
    ) -> torch.Tensor:
        if not isinstance(transform, torch.Tensor):
            raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
        return self.apply_transform(
            input,
            params=self._params,
            transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
            flags=flags,
        )


def _range_allows_odd_turns(low: float, high: float) -> bool:
    """Whether a ``times`` draw from ``[low, high]`` can round to an odd number of quarter turns.

    The bounds are rounded the way ``compute_transformation`` rounds a draw. Two different whole numbers always include
    an odd one, and a single whole number is either odd or even.
    """
    low, high = round(low), round(high)
    return high > low or low % 2 != 0


class RandomRotation90(GeometricAugmentationBase2D):
    r"""Rotate images by a random multiple of 90 degrees, applied per sample with probability ``p`` (default 0.5).

    ``output = RandomRotation90(times, ...)(input)`` rotates selected images of shape ``(B, C, H, W)``
    by quarter turns. Use :class:`RandomRotation` to sample arbitrary angles.

    Args:
        times: the range of n times 90 degree rotation needs to be applied. A range of whole numbers is closed:
          every whole number from the lower to the upper bound is drawn with the same probability.
        resample: Default: the interpolation mode.
        same_on_batch: apply the same transformation across the batch.
        align_corners: interpolation flag.
        p: probability of applying the transformation to each sample.
        keepdim: whether to keep the output shape the same as input (True) or broadcast it
                 to the batch form (False).

    Shape:
        - Input: ``(C, H, W)`` or ``(B, C, H, W)``, Optional: ``(B, 3, 3)``
        - Output: ``(B, C, H, W)``

    Convention:
        - See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
        - a positive rounded ``times`` rotates the displayed image counter-clockwise by ``times * 90`` degrees.
        - a range of whole numbers for ``times`` is closed and uniform: ``times=(-1, 1)`` gives a clockwise quarter
          turn, no turn and a counter-clockwise quarter turn with the same probability. A range with a fractional
          bound is still drawn continuously and rounded.
        - an odd number of quarter turns swaps the height and the width, but the output keeps the ``(H, W)`` of the
          input, so part of a non-square image would be cut off. A non-square input therefore raises ``ValueError``
          when the ``times`` range allows an odd number of quarter turns, even if a given call would draw an even one.
          Square images, and ranges of even numbers only such as ``times=(2, 2)``, are unaffected. Use
          :class:`~kornia.augmentation.RandomRotation` with a fixed angle of 90 degrees to rotate and crop, or
          :func:`torch.rot90` to turn a whole batch exactly.

    .. note::
        This function internally uses :func:`kornia.geometry.transform.affine`. This version is relatively
        slow as it operates based on affine transformations.

    See Also:
        - :class:`RandomRotation`: samples an arbitrary angle in degrees.

    Examples:
        >>> rng = torch.manual_seed(1)
        >>> input = torch.tensor([[1., 0., 0., 2.],
        ...                       [0., 0., 0., 0.],
        ...                       [0., 1., 2., 0.],
        ...                       [0., 0., 1., 2.]])
        >>> aug = RandomRotation90(times=(1, 1), p=1.)
        >>> out = aug(input)
        >>> out.round()  # rounded: the warp leaves float32 noise around 1e-7
        tensor([[[[2., 0., 0., 2.],
                  [0., 0., 2., 1.],
                  [0., 0., 1., 0.],
                  [1., 0., 0., 0.]]]])
        >>> aug.transform_matrix.round(decimals=4) + 0.  # + 0. turns -0. into 0.
        tensor([[[ 0.,  1.,  0.],
                 [-1.,  0.,  3.],
                 [ 0.,  0.,  1.]]])
        >>> inv = aug.inverse(out)

    To apply the exact augmenation again, you may take the advantage of the previous parameter state:
        >>> input = torch.randn(1, 3, 32, 32)
        >>> aug = RandomRotation90(times=(-1, 1), p=1.)
        >>> (aug(input) == aug(input, params=aug._params)).all()
        tensor(True)

    """

    def __init__(
        self,
        times: tuple[int, int],
        resample: Union[str, int, Resample] = Resample.BILINEAR.name,
        same_on_batch: bool = False,
        align_corners: bool = True,
        p: float = 0.5,
        keepdim: bool = False,
    ) -> None:
        super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
        self._param_generator = rg.Rotation90Generator(times)
        low, high = self._param_generator.times.tolist()
        self._allows_odd_turns = _range_allows_odd_turns(low, high)

        self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}

    def __setstate__(self, state: Dict[str, Any]) -> None:
        super().__setstate__(state)
        if "_allows_odd_turns" not in self.__dict__ or self._param_generator.times.requires_grad:
            # A RandomRotation90 pickled before the non-square check existed has no cached answer, and the copy of a
            # learnable range draws from the range as it is now, which an in-place update may have changed. A buffer
            # written in place keeps the copied samplers, and with them the copied answer.
            low, high = self._param_generator.times.tolist()
            self._allows_odd_turns = _range_allows_odd_turns(low, high)

    def _load_from_state_dict(self, state_dict: Dict[str, Any], prefix: str, *args: Any, **kwargs: Any) -> None:
        super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)
        times = state_dict.get(f"{prefix}_param_generator.times")
        if isinstance(times, torch.Tensor) and times.shape == (2,):
            low, high = times.tolist()
            self._allows_odd_turns = _range_allows_odd_turns(low, high)

    def validate_tensor(self, input: torch.Tensor) -> None:
        super().validate_tensor(input)
        height, width = input.shape[-2:]
        if self._allows_odd_turns and height != width:
            raise ValueError(
                f"`RandomRotation90` keeps the (H, W) shape, so an odd number of quarter turns of a non-square "
                f"{height}x{width} image would cut off part of it, and `times` allows one. Use a square image, "
                "`RandomRotation` with a fixed angle of 90 degrees to rotate and crop, or `torch.rot90` to turn "
                "the whole batch exactly."
            )

    def compute_transformation(
        self, input: torch.Tensor, params: dict[str, torch.Tensor], flags: dict[str, Any]
    ) -> torch.Tensor:
        # TODO: Update to use `get_rotation_matrix2d`
        angles: torch.Tensor = 90.0 * _to_device_nonblocking(params["times"].round(), input.device, input.dtype)

        center: torch.Tensor = _compute_tensor_center(input)
        rotation_mat: torch.Tensor = _compute_rotation_matrix(angles, center.expand(angles.shape[0], -1))

        # rotation_mat is B x 2 x 3 and we need a B x 3 x 3 matrix
        trans_mat: torch.Tensor = eye_like(3, input, shared_memory=False)
        trans_mat[:, 0] = rotation_mat[:, 0]
        trans_mat[:, 1] = rotation_mat[:, 1]

        return trans_mat

    def apply_transform(
        self,
        input: torch.Tensor,
        params: dict[str, torch.Tensor],
        flags: dict[str, Any],
        transform: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        if not isinstance(transform, torch.Tensor):
            raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")

        return affine(input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"])

    def inverse_transform(
        self,
        input: torch.Tensor,
        flags: dict[str, Any],
        transform: Optional[torch.Tensor] = None,
        size: Optional[tuple[int, int]] = None,
    ) -> torch.Tensor:
        if not isinstance(transform, torch.Tensor):
            raise TypeError(f"Expected the `transform` be a torch.Tensor. Got {type(transform)}.")
        return self.apply_transform(
            input,
            params=self._params,
            transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
            flags=flags,
        )
