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

import torch
from torch.nn.functional import mse_loss as mse

# Unlike Python's numeric tower, TorchScript unions need int explicitly to keep integer ranges accepted.
_PSNRMaxVal = float | int | torch.Tensor


def psnr(image: torch.Tensor, target: torch.Tensor, max_val: _PSNRMaxVal) -> torch.Tensor:
    r"""Compute the peak signal-to-noise ratio (PSNR), in dB, between two images.

    ``score = psnr(image, target, max_val)`` takes two images of the same shape ``(*)`` and their data range
    :math:`\text{MAX}_I`, and returns the PSNR for the mean squared error over all :math:`N` elements:

    .. math::

        \text{PSNR} = 10 \log_{10} \bigg(\frac{\text{MAX}_I^2}{\text{MSE}}\bigg), \quad
        \text{MSE} = \frac{1}{N}\sum_{k=1}^{N} (I_k - T_k)^2

    Convention:
        - One MSE is pooled over every element, batch and channels included, so for a batch the score is the PSNR of
          the pooled MSE, not the mean of per-image PSNRs: compute per-image values one image at a time.
          :ref:`Losses and metrics <losses-metrics-conventions>` maps both onto scikit-image and torchmetrics.
        - ``max_val`` is the data range of the images (``1.0`` for ``[0, 1]``, ``255.0`` for ``[0, 255]``), not the
          maximum of the tensor; pixel values are not rescaled.
        - The shapes must match, without broadcasting, and the value is symmetric in the images. Identical inputs
          give an MSE of 0 and ``inf``, while a batch with one identical pair stays finite.
        - Integer and bool images are converted to float32 before computing the MSE, so an integer image paired with
          a half-precision image gives a float32 result. Uint8, int8, int16 and int32 tensor data ranges are widened
          to int64 before squaring to avoid overflow, except when the promoted image dtype is float16 or bfloat16,
          which uses float32 range arithmetic.
        - Float16 and bfloat16 inputs are evaluated in float32 and the result keeps their promoted dtype, also
          promoted with ``max_val.dtype`` for a tensor range: a float32 tensor range gives a float32 result for
          half-precision images.

    Args:
        image: the image with shape ``(*)``.
        target: the reference image with the shape of ``image``.
        max_val: the data range :math:`\text{MAX}_I` of the images, as a float, integer or tensor.

    Returns:
        the PSNR in dB, a 0-d tensor for a scalar range or with the shape of a tensor range.

    See Also:
        - :func:`~kornia.losses.psnr_loss`: the negative PSNR, to minimise.
        - :class:`~kornia.losses.PSNRLoss`: the module form of that loss.
        - :func:`~kornia.metrics.ssim`: a structural measure of the same pair, per pixel and bounded.

    Examples:
        >>> ones = torch.ones(1)
        >>> psnr(ones, 1.2 * ones, 2.) # 10 * log(4/((1.2-1)**2)) / log(10)
        tensor(20.0000)

    Reference:
        https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio#Definition

    """
    if not isinstance(image, torch.Tensor):
        raise TypeError(f"Expected torch.Tensor but got {type(image)}.")

    if not isinstance(target, torch.Tensor):
        raise TypeError(f"Expected torch.Tensor but got {type(target)}.")

    if image.shape != target.shape:
        raise TypeError(f"Expected tensors of equal shapes, but got {image.shape} and {target.shape}")

    # mse has no integer kernel; compute integer images in float32 as ssim does.
    if not image.is_floating_point() and not image.is_complex():
        image = image.to(torch.float32)
    if not target.is_floating_point() and not target.is_complex():
        target = target.to(torch.float32)
    # Give mse_loss one dtype: on two dtypes it aborts the process on MPS, and its backward raises on torch 2.5.1.
    dtype = torch.promote_types(image.dtype, target.dtype)
    compute_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
    image, target = image.to(compute_dtype), target.to(compute_dtype)
    result_dtype = dtype
    if dtype in (torch.float16, torch.bfloat16) and isinstance(max_val, torch.Tensor):
        result_dtype = torch.promote_types(dtype, max_val.dtype)
        # Keep the tensor data range's square and division out of half precision too, without narrowing float64.
        max_val = max_val.to(torch.promote_types(compute_dtype, max_val.dtype))

    # The legacy (TorchScript) ONNX exporter writes ``log10`` as a division by a ``(1,)`` constant, which turns a 0-d
    # result into a one-element vector. Reshaping to the shape of the ratio keeps the eager shape there (``()`` for a
    # scalar ``max_val``, the shape of a tensor one) and is a no-op view eagerly.
    mse_value = mse(image, target, reduction="mean")
    # TorchScript needs the union refined before selecting a pow overload.
    if isinstance(max_val, torch.Tensor):
        if max_val.dtype in (torch.uint8, torch.int8, torch.int16, torch.int32):
            max_val = max_val.to(torch.int64)
        ratio = torch.pow(max_val, 2) / mse_value
    elif isinstance(max_val, int):
        ratio = max_val**2 / mse_value
    else:
        ratio = max_val**2 / mse_value
    result = 10.0 * torch.log10(ratio)
    if dtype in (torch.float16, torch.bfloat16):
        result = result.to(result_dtype)
    return result.reshape(ratio.shape)
