# 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.
#

# kornia.geometry.so3 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py
from __future__ import annotations

from typing import Optional, Union, overload

import torch
from torch import nn

from kornia.core.check import KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
from kornia.core.tensor_wrapper import _unwrap
from kornia.geometry.conversions import quaternion_to_axis_angle, vector_to_skew_symmetric_matrix
from kornia.geometry.quaternion import Quaternion
from kornia.geometry.vector import Vector3


def _so3_small_angle_coefficients(
    theta: torch.Tensor, theta_sq: Optional[torch.Tensor] = None
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    r"""Evaluate the three angle coefficients of the SO(3) and SE(3) closed forms without cancellation.

    Returns :math:`(1 - \cos\theta) / \theta^2`, :math:`(\theta - \sin\theta) / \theta^3` and
    :math:`(1 - \tfrac{\theta}{2}\cot\tfrac{\theta}{2}) / \theta^2`, the coefficients of :math:`[\omega]_\times`
    and :math:`[\omega]_\times^2` in the SO(3) Jacobians, in the SE(3) :math:`V` matrix and in its inverse.

    Each closed form is a 0/0 at :math:`\theta = 0` and keeps only about :math:`\epsilon / \theta^2` of its
    relative accuracy near it: all three evaluate to exactly 0 in float32 for :math:`\theta \le 10^{-4}` and in
    float64 for :math:`\theta \le 10^{-8}`. Below ``theta_small`` the Taylor series through :math:`\theta^{10}`
    is used instead. At the switch point the series is accurate to a fraction of an ulp and the closed forms to a
    few hundred ulps, so the two branches agree there. The closed forms divide by :math:`\theta` one factor at a
    time: :math:`\theta^3` overflows float16 above 40.3 rad and :math:`\theta^2` above 256 rad.

    Args:
        theta: rotation angles of any shape, non-negative.
        theta_sq: optional squared angles computed directly from the rotation vector, with the shape of ``theta``.
            Avoids differentiating a norm at zero in the Taylor series.

    Returns:
        the three coefficients, each with the shape of ``theta``.
    """
    theta_small = 0.2 if theta.dtype == torch.float64 else 0.5
    small = theta < theta_small
    # torch.where differentiates the branch it does not select, so each branch gets a substituted argument
    # where the other is used: 1 for the closed forms (0/0 at theta = 0) and 0 for the series, whose Horner
    # terms overflow float16 from about 50 rad and would put 0 * inf = nan into the gradient (kornia#4965).
    safe_theta = torch.where(small, torch.ones_like(theta), theta)
    if theta_sq is None:
        series_theta = torch.where(small, theta, torch.zeros_like(theta))
        t2 = series_theta * series_theta
    else:
        t2 = torch.where(small, theta_sq, torch.zeros_like(theta_sq))
    a_series = 0.5 + t2 * (-1 / 24 + t2 * (1 / 720 + t2 * (-1 / 40320 + t2 * (1 / 3628800 - t2 / 479001600))))
    b_series = 1 / 6 + t2 * (-1 / 120 + t2 * (1 / 5040 + t2 * (-1 / 362880 + t2 * (1 / 39916800 - t2 / 6227020800))))
    c_series = 1 / 12 + t2 * (
        1 / 720 + t2 * (1 / 30240 + t2 * (1 / 1209600 + t2 * (1 / 47900160 + t2 * (691 / 1307674368000))))
    )
    half = 0.5 * safe_theta
    a = torch.where(small, a_series, (1 - torch.cos(safe_theta)) / safe_theta / safe_theta)
    b = torch.where(small, b_series, (1 - torch.sin(safe_theta) / safe_theta) / safe_theta / safe_theta)
    c = torch.where(small, c_series, (1 - half * torch.cos(half) / torch.sin(half)) / safe_theta / safe_theta)
    return a, b, c


def _so3_jacobian_coefficients(vec: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """Evaluate Jacobian coefficients without a singular norm backward at the identity."""
    theta_sq = (vec * vec).sum(-1, keepdim=True)
    nonzero = theta_sq > 0
    # Even an unselected norm at zero produces NaNs in double backward. Substitute its input,
    # and evaluate the series directly in vec.dot(vec) to retain derivatives of every Taylor term.
    # Keep norm (rather than sqrt(theta_sq)) for the closed forms: the squared angle can overflow half.
    safe_vec = torch.where(nonzero, vec, torch.ones_like(vec))
    theta = torch.where(nonzero, safe_vec.norm(dim=-1, keepdim=True), torch.zeros_like(theta_sq))
    return _so3_small_angle_coefficients(theta[..., None], theta_sq[..., None])


def _computes_in_float32(dtype: torch.dtype) -> bool:
    """Whether So3 and Se3 evaluate an operation of this result dtype in float32 and round it once."""
    return dtype in (torch.float16, torch.bfloat16)


def _so3_rotate(q: Quaternion, points: torch.Tensor) -> torch.Tensor:
    """Rotate points of shape ``(*, 3)`` by the unit direction of ``q`` as :math:`q p q^*`.

    A float16/bfloat16 result is computed in float32 and returned in float32, for the caller to add to it or round it
    once; any other dtype combination is evaluated as given.
    """
    KORNIA_CHECK_SHAPE(points, ["*", "3"])
    if _computes_in_float32(torch.promote_types(q.data.dtype, points.dtype)):
        q, points = q.to(torch.float32), points.float()
    if q.data.dim() == 1 and points.dim() == 2:
        # an unbatched rotation rotates every point of an (N, 3) point set, as So2 does for (N, 2)
        q = Quaternion(q.data.expand(points.shape[0], 4))
    w = torch.zeros(*points.shape[:-1], 1, device=points.device, dtype=points.dtype)
    quat = Quaternion(torch.cat((w, points), -1))
    # q p q* scales p by |q|^2, so rotate by the unit direction of q
    q = q.normalize()
    return (q * quat * q.conj()).vec


def _check_points_layout(q: Quaternion, points: torch.Tensor) -> None:
    """Raise unless So3 and Se3 map ``points``: ``(3,)`` or ``(N, 3)`` unbatched, one point per pose for a batch.

    For a batch of ``B`` poses the points are ``(B, 3)``; a batch of one pose also maps ``(N, 3)``, and one point
    ``(1, 3)`` maps under every pose.
    """
    batch = q.data.shape[:-1]
    if len(batch) == 0:
        accepted = points.dim() in (1, 2)
    else:
        accepted = points.dim() == len(batch) + 1 and all(
            p in (b, 1) or b == 1 for p, b in zip(points.shape[:-1], batch)
        )
    if not accepted:
        raise ValueError(
            "Expected points of shape (3,) or (N, 3) for an unbatched pose, or (B, 3), one point per pose, for a batch "
            "of B poses (a batch of one pose also maps (N, 3), and one point (1, 3) maps under every pose). Got points "
            f"of shape {tuple(points.shape)} for a pose of batch shape {tuple(batch)}."
        )


class So3(nn.Module):
    r"""Represent a 3D rotation as an SO(3) Lie group element stored as a quaternion.

    ``r = So3.exp(omega)`` builds rotations from rotation vectors ``omega`` of shape ``(B, 3)``, the axis times the
    angle in radians; ``So3(q)`` wraps a ``(B, 4)`` :class:`~kornia.geometry.quaternion.Quaternion`,
    :meth:`from_matrix` reads ``(B, 3, 3)`` matrices, and ``So3.identity(B)`` and ``So3.random(B)`` build ``B``
    rotations, or an unbatched one with ``batch_size=None``. ``r1 * r2`` composes a batch with a batch of the same size,
    a batch of one or an unbatched rotation; ``r.inverse()`` inverts, ``r.log()`` returns the ``(B, 3)`` rotation
    vectors and ``r.matrix()`` the ``(B, 3, 3)`` matrices; an unbatched rotation drops the ``B``. ``r * p`` rotates
    points as :math:`R p`: ``(3,)`` or ``(N, 3)`` points for an unbatched rotation, and ``(B, 3)``, one point per
    rotation, or a single ``(1, 3)`` point, not ``(3,)``, for a batch of ``B``; a batch of one also maps ``(N, 3)``.
    For a rotation and a translation, use :class:`Se3`; for
    quaternion arithmetic, interpolation and Euler angles, :class:`~kornia.geometry.quaternion.Quaternion`.

    SO(3) is the group of rotations of :math:`R^3` about the origin under composition; see
    https://en.wikipedia.org/wiki/3D_rotation_group.

    Convention:
        - The tangent vector is the rotation vector, the axis times the angle in radians, and ``hat(v)`` is its
          cross-product matrix: ``hat(v) @ p`` equals ``torch.linalg.cross(v, p)``. ``log()`` is
          ``q.to_axis_angle()``: it reads only the direction of ``q``, within the range limits stated on
          :class:`~kornia.geometry.quaternion.Quaternion`, and returns the principal vector, of norm at most
          :math:`\pi`, the same for ``q`` and ``-q`` below a half turn.
        - ``a * b`` composes like ``a.matrix() @ b.matrix()``, so ``b`` acts first; ``s * p`` rotates points ``p``, a
          tensor or a ``Vector3``, as :math:`R p`: ``(3,)`` or ``(N, 3)`` for an unbatched ``So3``, and ``(B, 3)``,
          one point per rotation, or ``(1, 3)``, not ``(3,)``, for a batch of ``B`` (a batch of one also maps
          ``(N, 3)``); other layouts raise ``ValueError``. ``adjoint()`` is :math:`R` itself.
          :ref:`Rotations and rigid motions <rotation-conventions>` compares these with scipy, Sophus and Eigen.
        - A non-unit quaternion stands for the rotation of its direction :math:`q / |q|`, as for
          :meth:`~kornia.geometry.quaternion.Quaternion.matrix`: ``matrix()`` and ``s * p`` normalise it where they
          use it, so ``matrix()`` is a rotation and ``s * p`` keeps the norm of ``p`` within the range limits stated
          on :class:`~kornia.geometry.quaternion.Quaternion`. ``q`` returns the quaternion as stored, which keeps an
          ``nn.Parameter`` registered and following optimiser steps.
        - For a small :math:`\delta`,
          :math:`\exp(\omega + \delta) \approx \exp(\omega) \exp(J_r \delta) = \exp(J_l \delta) \exp(\omega)`,
          with :math:`J_r` = ``right_jacobian(omega)`` and :math:`J_l` = ``left_jacobian(omega)`` =
          ``right_jacobian(-omega)``.
        - ``from_matrix`` does not check its input by default: a reflection (det :math:`-1`) is accepted without
          error and returns an ``So3`` whose ``matrix()`` is not the input. ``check_rotation=True`` raises
          ``ValueError`` instead.
        - The quaternion is registered as module state following
          :class:`~kornia.geometry.quaternion.Quaternion`'s buffer/parameter convention, including rotations
          produced by ``exp``, ``identity``, ``random``, ``from_matrix`` and group operations.
        - ``matrix()``, ``adjoint()``, ``a * b`` and ``s * p`` compute in float32 for float16/bfloat16 inputs and
          return the input dtype, rounding once; float32 and float64 are evaluated in their own dtype.

    See Also:
        - :class:`So2`: the 2D rotation group, stored as a complex number.
        - :class:`Se3`: a 3D rotation followed by a translation, mapping points as :math:`R p + t`.
        - :class:`~kornia.geometry.quaternion.Quaternion`: the stored quaternion, with the Hamilton product,
          ``slerp`` and Euler angles but no action on points.
        - :func:`~kornia.geometry.conversions.axis_angle_to_rotation_matrix`: the matrix of ``So3.exp(v)`` in one
          call on a plain ``(*, 3)`` tensor.

    Example:
        >>> q = Quaternion.identity()
        >>> s = So3(q)
        >>> s.q
        tensor([1., 0., 0., 0.])

    """

    def __init__(self, q: Quaternion) -> None:
        """Construct an So3 that stores the quaternion ``q`` as given.

        Args:
            q: Quaternion with the shape of ``(B, 4)`` or ``(4,)``.

        Example:
            >>> data = torch.tensor([[1., 0., 0., 0.], [0., 1., 0., 0.]])
            >>> q = Quaternion(data)
            >>> So3(q)
            tensor([[1., 0., 0., 0.],
                    [0., 1., 0., 0.]])

        """
        super().__init__()
        KORNIA_CHECK_TYPE(q, Quaternion)
        self._q = q

    def __repr__(self) -> str:
        return f"{self.q}"

    def __getitem__(self, idx: int | slice) -> So3:
        return So3(self._q[idx])

    @overload
    def __mul__(self, right: So3) -> So3: ...

    @overload
    def __mul__(self, right: Vector3) -> Vector3: ...

    @overload
    def __mul__(self, right: torch.Tensor) -> torch.Tensor: ...

    def __mul__(self, right: So3 | Vector3 | torch.Tensor) -> So3 | Vector3 | torch.Tensor:
        """Compose two So3 transformations, or rotate points.

        Both compute in float32 for float16/bfloat16 inputs and return the input dtype.

        Args:
            right: the other So3 transformation, unbatched, a batch of the same size or a batch of one, or points
                as a tensor or a ``Vector3``: ``(3,)`` or ``(N, 3)`` for an unbatched rotation, and ``(B, 3)``, one
                point per rotation, or ``(1, 3)``, not ``(3,)``, for a batch of ``B`` (a batch of one also maps
                ``(N, 3)``).

        Return:
            The resulting So3 transformation, or the rotated points of the type of ``right``.

        """
        # https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L98
        if isinstance(right, So3):
            dtype = torch.promote_types(self.q.data.dtype, right.q.data.dtype)
            if _computes_in_float32(dtype):
                product = self.q.to(torch.float32) * right.q.to(torch.float32)
                return So3(Quaternion(product.data.to(dtype)))
            return So3(self.q * right.q)
        if isinstance(right, (torch.Tensor, Vector3)):
            _right_data = _unwrap(right)
            _check_points_layout(self.q, _right_data)
            out = _so3_rotate(self.q, _right_data).to(torch.promote_types(self.q.data.dtype, _right_data.dtype))
            return Vector3(out) if isinstance(right, Vector3) else out
        raise TypeError(f"Not So3 or torch.Tensor type. Got: {type(right)}")

    @property
    def q(self) -> Quaternion:
        """Return the stored :class:`~kornia.geometry.quaternion.Quaternion`: ``(B, 4)``, or ``(4,)`` unbatched."""
        return self._q

    @staticmethod
    def exp(v: torch.Tensor) -> So3:
        """Convert elements of lie algebra to elements of lie group.

        See more: https://vision.in.tum.de/_media/members/demmeln/nurlanov2021so3log.pdf

        Args:
            v: vector of shape ``(B,3)``.

        Example:
            >>> v = torch.zeros((2, 3))
            >>> s = So3.exp(v)
            >>> s
            tensor([[1., 0., 0., 0.],
                    [1., 0., 0., 0.]])

        """
        KORNIA_CHECK_SHAPE(v, ["*", "3"])
        # cos(theta / 2) and sin(theta / 2) / theta are even in theta, so below 0.5 rad both are evaluated as
        # series in theta**2 = v . v, a polynomial in v. theta = |v| itself has no second derivative at v = 0,
        # so the Hessian of exp at the identity, the standard initialisation for pose optimisation, was nan
        # (#4966), and sin(theta / 2) / theta is a 0/0 there. The series run through theta**12 and theta**10;
        # their truncation error at the switch is under 1e-17, below the resolution of every dtype.
        # torch.where differentiates the branch it does not select, so each branch is evaluated on an input
        # that keeps it finite: the series on 0 above the switch (on theta**2 itself their powers overflow
        # float16 above about 90 rad and 0 * inf = nan), and the closed forms on the norm of the unit vector
        # e_x below it, which keeps |v| out of the graph where it is not differentiable.
        theta_sq = (v * v).sum(-1, keepdim=True)
        small = theta_sq < 0.25
        t2 = torch.where(small, theta_sq, torch.zeros_like(theta_sq))
        w_series = 1 + t2 * (
            -1 / 8
            + t2 * (1 / 384 + t2 * (-1 / 46080 + t2 * (1 / 10321920 + t2 * (-1 / 3715891200 + t2 / 1961990553600))))
        )
        b_series = 0.5 + t2 * (-1 / 48 + t2 * (1 / 3840 + t2 * (-1 / 645120 + t2 * (1 / 185794560 - t2 / 81749606400))))
        unit_x = torch.cat((torch.ones_like(theta_sq), torch.zeros_like(v[..., 1:])), dim=-1)
        safe_theta = torch.where(small, unit_x, v).norm(dim=-1, keepdim=True)
        w = torch.where(small, w_series, torch.cos(0.5 * safe_theta))
        b = torch.where(small, b_series, torch.sin(0.5 * safe_theta) / safe_theta)
        return So3(Quaternion(torch.cat((w, b * v), dim=-1)))

    def log(self) -> torch.Tensor:
        """Convert elements of lie group  to elements of lie algebra.

        Example:
            >>> So3.identity(batch_size=2).log()
            tensor([[0., 0., 0.],
                    [0., 0., 0.]])

        """
        # quaternion_to_axis_angle is the principal logarithm and it measures the angle with atan2: q and -q, the
        # same rotation, give the same vector with |theta| <= pi (#4925), a rotation below 1e-4 rad in float32 keeps
        # its digits instead of collapsing to 0 through 2 * acos(real) (#4897), and the identity keeps the finite
        # gradient 2 * vec / real of #4404.
        # It agrees with Sophus's 2 * atan(|vec| / real) / |vec| * vec away from real = 0:
        # https://github.com/strasdat/Sophus/blob/main/sympy/sophus/so3.py
        return quaternion_to_axis_angle(_unwrap(self.q.data))

    @staticmethod
    def hat(v: Vector3 | torch.Tensor) -> torch.Tensor:
        """Convert elements from vector space to lie algebra. Returns matrix of shape ``(B,3,3)``.

        Args:
            v: Vector3 or torch.Tensor of shape ``(B,3)``.

        Example:
            >>> v = torch.ones((1,3))
            >>> m = So3.hat(v)
            >>> m
            tensor([[[ 0., -1.,  1.],
                     [ 1.,  0., -1.],
                     [-1.,  1.,  0.]]])

        """
        KORNIA_CHECK_SHAPE(v, ["*", "3"])
        if isinstance(v, torch.Tensor):
            # TODO: Figure out why mypy think `v` can be a Vector3 which didn't allow ellipsis on index
            a, b, c = v[..., 0], v[..., 1], v[..., 2]
        else:
            a, b, c = v.x, v.y, v.z
        z = torch.zeros_like(a)
        row0 = torch.stack((z, -c, b), -1)
        row1 = torch.stack((c, z, -a), -1)
        row2 = torch.stack((-b, a, z), -1)
        return torch.stack((row0, row1, row2), -2)

    @staticmethod
    def vee(omega: torch.Tensor) -> torch.Tensor:
        r"""Convert elements from lie algebra to vector space. Returns vector of shape ``(B,3)``.

        .. math::
            omega = \begin{bmatrix} 0 & -c & b \\
            c & 0 & -a \\
            -b & a & 0\end{bmatrix}

        Args:
            omega: 3x3-matrix representing lie algebra.

        Example:
            >>> v = torch.ones((1,3))
            >>> omega = So3.hat(v)
            >>> So3.vee(omega)
            tensor([[1., 1., 1.]])

        """
        KORNIA_CHECK_SHAPE(omega, ["*", "3", "3"])
        a, b, c = omega[..., 2, 1], omega[..., 0, 2], omega[..., 1, 0]
        return torch.stack((a, b, c), -1)

    def matrix(self) -> torch.Tensor:
        r"""Convert the quaternion to a rotation matrix of shape ``(B,3,3)``.

        The matrix is of the form, with :math:`(w, x, y, z)` the unit quaternion :math:`q / |q|`:

        .. math::
            \begin{bmatrix} 1-2y^2-2z^2 & 2xy-2zw & 2xz+2yw \\
            2xy+2zw & 1-2x^2-2z^2 & 2yz-2xw \\
            2xz-2yw & 2yz+2xw & 1-2x^2-2y^2\end{bmatrix}

        It computes in float32 for float16/bfloat16 inputs and returns the input dtype.

        Example:
            >>> s = So3.identity()
            >>> m = s.matrix()
            >>> m
            tensor([[1., 0., 0.],
                    [0., 1., 0.],
                    [0., 0., 1.]])

        """
        # The formula below holds for a unit quaternion only. Normalising here rather than in the constructor keeps
        # the stored quaternion, possibly an nn.Parameter, as the module state.
        dtype = self.q.data.dtype
        q = self.q.to(torch.float32) if _computes_in_float32(dtype) else self.q
        q = q.normalize()
        w = q.w[..., None]
        x, y, z = q.x[..., None], q.y[..., None], q.z[..., None]
        q0 = 1 - 2 * y**2 - 2 * z**2
        q1 = 2 * x * y - 2 * z * w
        q2 = 2 * x * z + 2 * y * w
        row0 = torch.cat((q0, q1, q2), -1)
        q0 = 2 * x * y + 2 * z * w
        q1 = 1 - 2 * x**2 - 2 * z**2
        q2 = 2 * y * z - 2 * x * w
        row1 = torch.cat((q0, q1, q2), -1)
        q0 = 2 * x * z - 2 * y * w
        q1 = 2 * y * z + 2 * x * w
        q2 = 1 - 2 * x**2 - 2 * y**2
        row2 = torch.cat((q0, q1, q2), -1)
        return torch.stack((row0, row1, row2), -2).to(dtype)

    @classmethod
    def from_matrix(cls, matrix: torch.Tensor, check_rotation: bool = False) -> So3:
        """Create So3 from a rotation matrix.

        Args:
            matrix: the rotation matrix to convert of shape ``(B,3,3)``.
            check_rotation: if ``True``, raise ``ValueError`` unless every input
                is a rotation matrix. The default ``False`` keeps the unchecked
                behaviour, under which a reflection such as ``diag(-1, 1, 1)``
                is silently turned into the identity. Note that
                ``So2.from_matrix`` rejects the 2D reflection ``diag(1, -1)``
                regardless.

        Example:
            >>> m = torch.eye(3)
            >>> s = So3.from_matrix(m)
            >>> s
            tensor([1., 0., 0., 0.])

        """
        return cls(Quaternion.from_matrix(matrix, check_rotation=check_rotation))

    @classmethod
    def from_wxyz(cls, wxyz: torch.Tensor) -> So3:
        """Create So3 from a torch.Tensor representing a quaternion.

        Args:
            wxyz: the quaternion to convert of shape ``(B,4)``.

        Example:
            >>> q = torch.tensor([1., 0., 0., 0.])
            >>> s = So3.from_wxyz(q)
            >>> s
            tensor([1., 0., 0., 0.])

        """
        KORNIA_CHECK_SHAPE(wxyz, ["*", "4"])
        return cls(Quaternion(wxyz))

    @classmethod
    def identity(
        cls,
        batch_size: Optional[int] = None,
        device: Union[str, torch.device, None] = None,
        dtype: Union[torch.dtype, None] = None,
    ) -> So3:
        """Create a So3 group representing an identity rotation.

        Args:
            batch_size: the batch size of the underlying data.
            device: device to place the result on.
            dtype: dtype of the result.

        Example:
            >>> s = So3.identity()
            >>> s
            tensor([1., 0., 0., 0.])

            >>> s = So3.identity(batch_size=2)
            >>> s
            tensor([[1., 0., 0., 0.],
                    [1., 0., 0., 0.]])

        """
        return cls(Quaternion.identity(batch_size, device, dtype))

    def inverse(self) -> So3:
        """Return the inverse transformation.

        Example:
            >>> s = So3.identity()
            >>> s.inverse()
            tensor([1., -0., -0., -0.])

        """
        return So3(self.q.conj())

    @classmethod
    def random(
        cls,
        batch_size: Optional[int] = None,
        device: Union[str, torch.device, None] = None,
        dtype: Union[torch.dtype, None] = None,
    ) -> So3:
        """Create a So3 group representing a random rotation.

        Args:
            batch_size: the batch size of the underlying data.
            device: device to place the result on.
            dtype: dtype of the result.

        Example:
            >>> s = So3.random()
            >>> s = So3.random(batch_size=3)

        """
        return cls(Quaternion.random(batch_size, device, dtype))

    @classmethod
    def rot_x(cls, x: torch.Tensor) -> So3:
        """Construct a x-axis rotation.

        Args:
            x: the x-axis rotation angle.

        """
        zs = torch.zeros_like(x)
        return cls.exp(torch.stack((x, zs, zs), -1))

    @classmethod
    def rot_y(cls, y: torch.Tensor) -> So3:
        """Construct a y-axis rotation.

        Args:
            y: the y-axis rotation angle.

        """
        zs = torch.zeros_like(y)
        return cls.exp(torch.stack((zs, y, zs), -1))

    @classmethod
    def rot_z(cls, z: torch.Tensor) -> So3:
        """Construct a z-axis rotation.

        Args:
            z: the z-axis rotation angle.

        """
        zs = torch.zeros_like(z)
        return cls.exp(torch.stack((zs, zs, z), -1))

    def adjoint(self) -> torch.Tensor:
        """Return the adjoint matrix of shape ``(B, 3, 3)``.

        Example:
            >>> s = So3.identity()
            >>> s.adjoint()
            tensor([[1., 0., 0.],
                    [0., 1., 0.],
                    [0., 0., 1.]])

        """
        return self.matrix()

    @staticmethod
    def right_jacobian(vec: torch.Tensor) -> torch.Tensor:
        """Compute the right Jacobian of So3.

        Args:
            vec: the tangent vector of shape ``(B, 3)``.

        Example:
            >>> vec = torch.tensor([1., 2., 3.])
            >>> So3.right_jacobian(vec)
            tensor([[-0.0687,  0.5556, -0.0141],
                    [-0.2267,  0.1779,  0.6236],
                    [ 0.5074,  0.3629,  0.5890]])

        """
        KORNIA_CHECK_SHAPE(vec, ["*", "3"])
        R_skew = vector_to_skew_symmetric_matrix(vec)
        a, b, _ = _so3_jacobian_coefficients(vec)
        I = torch.eye(3, device=vec.device, dtype=vec.dtype)  # noqa: E741
        return I - a * R_skew + b * (R_skew @ R_skew)

    @staticmethod
    def Jr(vec: torch.Tensor) -> torch.Tensor:
        """Alias for right jacobian.

        Args:
            vec: the tangent vector of shape ``(B, 3)``.

        """
        return So3.right_jacobian(vec)

    @staticmethod
    def left_jacobian(vec: torch.Tensor) -> torch.Tensor:
        """Compute the left Jacobian of So3.

        Args:
            vec: the tangent vector of shape ``(B, 3)``.

        Example:
            >>> vec = torch.tensor([1., 2., 3.])
            >>> So3.left_jacobian(vec)
            tensor([[-0.0687, -0.2267,  0.5074],
                    [ 0.5556,  0.1779,  0.3629],
                    [-0.0141,  0.6236,  0.5890]])

        """
        KORNIA_CHECK_SHAPE(vec, ["*", "3"])
        R_skew = vector_to_skew_symmetric_matrix(vec)
        a, b, _ = _so3_jacobian_coefficients(vec)
        I = torch.eye(3, device=vec.device, dtype=vec.dtype)  # noqa: E741
        return I + a * R_skew + b * (R_skew @ R_skew)

    @staticmethod
    def Jl(vec: torch.Tensor) -> torch.Tensor:
        """Alias for left jacobian.

        Args:
            vec: the tangent vector of shape ``(B, 3)``.

        """
        return So3.left_jacobian(vec)
