o
    Ñôjš%  ã                   @   sÊ   d dl mZ d dlmZmZmZmZ d dlmZ d dl	m
Z
 d dlmZmZ d dlmZmZ d dlmZ d dlmZ d d	lmZ d d
lmZmZ d dlmZmZ esUdgZes[ddgZG dd„ deƒZdS )é    )ÚSequence)ÚAnyÚListÚOptionalÚUnion)ÚTensor)ÚLiteral)Ú"_spectral_distortion_index_computeÚ!_spectral_distortion_index_update)Ú!_spatial_distortion_index_computeÚ _spatial_distortion_index_update)ÚMetric)Úrank_zero_warn)Údim_zero_cat)Ú_MATPLOTLIB_AVAILABLEÚ_TORCHVISION_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEúQualityWithNoReference.plotÚQualityWithNoReferencec                       s  e Zd ZU dZdZeed< dZeed< dZeed< dZ	e
ed< d	Ze
ed
< ee ed< ee ed< ee ed< ee ed< 					d&de
de
dededed deddf‡ fdd„Zdedeeef ddfdd„Zdefd d!„Z	d'd"eeeee f  d#ee defd$d%„Z‡  ZS )(r   aì  Compute Quality with No Reference (QualityWithNoReference_) also now as QNR.

    The metric is used to compare the joint spectral and spatial distortion between two images.

    As input to ``forward`` and ``update`` the metric accepts the following input

    - ``preds`` (:class:`~torch.Tensor`): High resolution multispectral image of shape ``(N,C,H,W)``.
    - ``target`` (:class:`~Dict`): A dictionary containing the following keys:

      - ``ms`` (:class:`~torch.Tensor`): Low resolution multispectral image of shape ``(N,C,H',W')``.
      - ``pan`` (:class:`~torch.Tensor`): High resolution panchromatic image of shape ``(N,C,H,W)``.
      - ``pan_lr`` (:class:`~torch.Tensor`): (optional) Low resolution panchromatic image of shape ``(N,C,H',W')``.

    where H and W must be multiple of H' and W'.

    When ``pan_lr`` is ``None``, a uniform filter will be applied on ``pan`` to produce a degraded image. The degraded
    image is then resized to match the size of ``ms`` and served as ``pan_lr`` in the calculation.

    As output of `forward` and `compute` the metric returns the following output

    - ``qnr`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average QNR value
      over sample else returns tensor of shape ``(N,)`` with QNR values per sample

    Args:
        alpha: Relevance of spectral distortion.
        beta: Relevance of spatial distortion.
        norm_order: Order of the norm applied on the difference.
        window_size: Window size of the filter applied to degrade the high resolution panchromatic image.
        reduction: a method to reduce metric score over labels.

            - ``'elementwise_mean'``: takes the mean (default)
            - ``'sum'``: takes the sum
            - ``'none'``: no reduction will be applied

        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Example:
        >>> from torch import rand
        >>> from torchmetrics.image import QualityWithNoReference
        >>> preds = rand([16, 3, 32, 32])
        >>> target = {
        ...     'ms': rand([16, 3, 16, 16]),
        ...     'pan': rand([16, 3, 32, 32]),
        ... }
        >>> qnr = QualityWithNoReference()
        >>> qnr(preds, target)
        tensor(0.9694)

    TÚhigher_is_betterÚis_differentiableFÚfull_state_updateg        Úplot_lower_boundg      ð?Úplot_upper_boundÚpredsÚmsÚpanÚpan_lré   é   Úelementwise_meanÚalphaÚbetaÚ
norm_orderÚwindow_sizeÚ	reduction©r!   ÚsumÚnoneÚkwargsÚreturnNc                    s,  t ƒ jdi |¤Ž tdƒ t|ttfƒr|dk r td|› d�ƒ‚|| _t|ttfƒr.|dk r6td|› d�ƒ‚|| _t|tƒrB|dkrJtd|› d�ƒ‚|| _	t|tƒrV|dkr^td|› d�ƒ‚|| _
d}||vrqtd	|› d
|› �ƒ‚|| _| jdg dd� | jdg dd� | jdg dd� | jdg dd� d S )NzŒMetric `QualityWithNoReference` will save all targets and predictions in buffer. For large datasets this may lead to large memory footprint.r   z>Expected `alpha` to be a non-negative real number. Got alpha: Ú.z<Expected `beta` to be a non-negative real number. Got beta: z@Expected `norm_order` to be a positive integer. Got norm_order: zBExpected `window_size` to be a positive integer. Got window_size: r'   z(Expected argument `reduction` be one of z	 but got r   Úcat)ÚdefaultÚdist_reduce_fxr   r   r   © )ÚsuperÚ__init__r   Ú
isinstanceÚintÚfloatÚ
ValueErrorr"   r#   r$   r%   r&   Ú	add_state)Úselfr"   r#   r$   r%   r&   r*   Úallowed_reductions©Ú	__class__r0   úi/var/www/html/academy/tools/voices/clone/cosy-venv/lib/python3.10/site-packages/torchmetrics/image/qnr.pyr2   b   s0   	ÿzQualityWithNoReference.__init__Útargetc                 C   sÂ   d|vrt d| ¡ › d�ƒ‚d|vrt d| ¡ › d�ƒ‚|d }|d }| d¡}t||ƒ\}}t||||ƒ\}}}}| j |¡ | j |d ¡ | j |d ¡ d|v r_| j	 |d ¡ dS dS )aì  Update state with preds and target.

        Args:
            preds: High resolution multispectral image.
            target: A dictionary containing the following keys:

                - ``'ms'``: low resolution multispectral image.
                - ``'pan'``: high resolution panchromatic image.
                - ``'pan_lr'``: (optional) low resolution panchromatic image.

        Raises:
            ValueError:
                If ``target`` doesn't have ``ms`` and ``pan``.

        r   z0Expected `target` to have key `ms`. Got target: r,   r   z1Expected `target` to have key `pan`. Got target: r   N)
r6   ÚkeysÚgetr
   r   r   Úappendr   r   r   )r8   r   r=   r   r   r   r0   r0   r<   Úupdate†   s   
ÿzQualityWithNoReference.updatec                 C   s‚   t | jƒ}t | jƒ}t | jƒ}t| jƒdkrt | jƒnd}t||| j| jƒ}t	||||| j| j
| jƒ}d| | j d| | j  S )z.Compute and returns quality with no reference.r   Nr   )r   r   r   r   Úlenr   r	   r$   r&   r   r%   r"   r#   )r8   r   r   r   r   Úd_lambdaÚd_sr0   r0   r<   Úcompute¥   s   


ÿzQualityWithNoReference.computeÚvalÚaxc                 C   s   |   ||¡S )aˆ  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> # Example plotting a single value
            >>> from torch import rand
            >>> from torchmetrics.image import QualityWithNoReference
            >>> preds = rand([16, 3, 32, 32])
            >>> target = {
            ...     'ms': rand([16, 3, 16, 16]),
            ...     'pan': rand([16, 3, 32, 32]),
            ... }
            >>> metric = QualityWithNoReference()
            >>> metric.update(preds, target)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> from torch import rand
            >>> from torchmetrics.image import QualityWithNoReference
            >>> preds = rand([16, 3, 32, 32])
            >>> target = {
            ...     'ms': rand([16, 3, 16, 16]),
            ...     'pan': rand([16, 3, 32, 32]),
            ... }
            >>> metric = QualityWithNoReference()
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(preds, target))
            >>> fig_, ax_ = metric.plot(values)

        )Ú_plot)r8   rF   rG   r0   r0   r<   Úplot±   s   2r   )r   r   r   r    r!   )NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚboolÚ__annotations__r   r   r   r5   r   r   r   r4   r   r   r2   ÚdictÚstrrA   rE   r   r   r   r   r   rI   Ú__classcell__r0   r0   r:   r<   r   $   sR   
 2úþýüûúùø$ÿÿÿþN)Úcollections.abcr   Útypingr   r   r   r   Útorchr   Útyping_extensionsr   Ú&torchmetrics.functional.image.d_lambdar	   r
   Ú!torchmetrics.functional.image.d_sr   r   Útorchmetrics.metricr   Útorchmetrics.utilitiesr   Útorchmetrics.utilities.datar   Útorchmetrics.utilities.importsr   r   Útorchmetrics.utilities.plotr   r   Ú__doctest_skip__r   r0   r0   r0   r<   Ú<module>   s    