d_s.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. # Copyright The Lightning team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from collections.abc import Sequence
  15. from typing import Any, List, Optional, Union
  16. from torch import Tensor
  17. from typing_extensions import Literal
  18. from torchmetrics.functional.image.d_s import _spatial_distortion_index_compute, _spatial_distortion_index_update
  19. from torchmetrics.metric import Metric
  20. from torchmetrics.utilities import rank_zero_warn
  21. from torchmetrics.utilities.data import dim_zero_cat
  22. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCHVISION_AVAILABLE
  23. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  24. if not _MATPLOTLIB_AVAILABLE:
  25. __doctest_skip__ = ["SpatialDistortionIndex.plot"]
  26. if not _TORCHVISION_AVAILABLE:
  27. __doctest_skip__ = ["SpatialDistortionIndex", "SpatialDistortionIndex.plot"]
  28. class SpatialDistortionIndex(Metric):
  29. r"""Compute Spatial Distortion Index (SpatialDistortionIndex_) also now as D_s.
  30. The metric is used to compare the spatial distortion between two images. A value of 0 indicates no distortion
  31. (optimal value) and corresponds to the case where the high resolution panchromatic image is equal to the low
  32. resolution panchromatic image. The metric is defined as:
  33. .. math::
  34. D_s = \\sqrt[q]{\frac{1}{L}\\sum_{l=1}^L|Q(\\hat{G_l}, P) - Q(\tilde{G}, \tilde{P})|^q}
  35. where :math:`Q` is the universal image quality index (see this
  36. :class:`~torchmetrics.image.UniversalImageQualityIndex` for more info), :math:`\\hat{G_l}` is the l-th band of the
  37. high resolution multispectral image, :math:`\tilde{G}` is the high resolution panchromatic image, :math:`P` is the
  38. high resolution panchromatic image, :math:`\tilde{P}` is the low resolution panchromatic image, :math:`L` is the
  39. number of bands and :math:`q` is the order of the norm applied on the difference.
  40. As input to ``forward`` and ``update`` the metric accepts the following input
  41. - ``preds`` (:class:`~torch.Tensor`): High resolution multispectral image of shape ``(N,C,H,W)``.
  42. - ``target`` (:class:`~Dict`): A dictionary containing the following keys:
  43. - ``ms`` (:class:`~torch.Tensor`): Low resolution multispectral image of shape ``(N,C,H',W')``.
  44. - ``pan`` (:class:`~torch.Tensor`): High resolution panchromatic image of shape ``(N,C,H,W)``.
  45. - ``pan_lr`` (:class:`~torch.Tensor`): Low resolution panchromatic image of shape ``(N,C,H',W')``.
  46. where H and W must be multiple of H' and W'.
  47. As output of `forward` and `compute` the metric returns the following output
  48. - ``sdi`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average SDI value
  49. over sample else returns tensor of shape ``(N,)`` with SDI values per sample
  50. Args:
  51. norm_order: Order of the norm applied on the difference.
  52. window_size: Window size of the filter applied to degrade the high resolution panchromatic image.
  53. reduction: a method to reduce metric score over labels.
  54. - ``'elementwise_mean'``: takes the mean (default)
  55. - ``'sum'``: takes the sum
  56. - ``'none'``: no reduction will be applied
  57. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  58. Example:
  59. >>> from torch import rand
  60. >>> from torchmetrics.image import SpatialDistortionIndex
  61. >>> preds = rand([16, 3, 32, 32])
  62. >>> target = {
  63. ... 'ms': rand([16, 3, 16, 16]),
  64. ... 'pan': rand([16, 3, 32, 32]),
  65. ... }
  66. >>> sdi = SpatialDistortionIndex()
  67. >>> sdi(preds, target)
  68. tensor(0.0090)
  69. """
  70. higher_is_better: bool = False
  71. is_differentiable: bool = True
  72. full_state_update: bool = False
  73. plot_lower_bound: float = 0.0
  74. plot_upper_bound: float = 1.0
  75. preds: List[Tensor]
  76. ms: List[Tensor]
  77. pan: List[Tensor]
  78. pan_lr: List[Tensor]
  79. def __init__(
  80. self,
  81. norm_order: int = 1,
  82. window_size: int = 7,
  83. reduction: Literal["elementwise_mean", "sum", "none"] = "elementwise_mean",
  84. **kwargs: Any,
  85. ) -> None:
  86. super().__init__(**kwargs)
  87. rank_zero_warn(
  88. "Metric `SpatialDistortionIndex` will save all targets and"
  89. " predictions in buffer. For large datasets this may lead"
  90. " to large memory footprint."
  91. )
  92. if not isinstance(norm_order, int) or norm_order <= 0:
  93. raise ValueError(f"Expected `norm_order` to be a positive integer. Got norm_order: {norm_order}.")
  94. self.norm_order = norm_order
  95. if not isinstance(window_size, int) or window_size <= 0:
  96. raise ValueError(f"Expected `window_size` to be a positive integer. Got window_size: {window_size}.")
  97. self.window_size = window_size
  98. allowed_reductions = ("elementwise_mean", "sum", "none")
  99. if reduction not in allowed_reductions:
  100. raise ValueError(f"Expected argument `reduction` be one of {allowed_reductions} but got {reduction}")
  101. self.reduction = reduction
  102. self.add_state("preds", default=[], dist_reduce_fx="cat")
  103. self.add_state("ms", default=[], dist_reduce_fx="cat")
  104. self.add_state("pan", default=[], dist_reduce_fx="cat")
  105. self.add_state("pan_lr", default=[], dist_reduce_fx="cat")
  106. def update(self, preds: Tensor, target: dict[str, Tensor]) -> None:
  107. """Update state with preds and target.
  108. Args:
  109. preds: High resolution multispectral image.
  110. target: A dictionary containing the following keys:
  111. - ``'ms'``: low resolution multispectral image.
  112. - ``'pan'``: high resolution panchromatic image.
  113. - ``'pan_lr'``: (optional) low resolution panchromatic image.
  114. Raises:
  115. ValueError:
  116. If ``target`` doesn't have ``ms`` and ``pan``.
  117. """
  118. if "ms" not in target:
  119. raise ValueError(f"Expected `target` to have key `ms`. Got target: {target.keys()}.")
  120. if "pan" not in target:
  121. raise ValueError(f"Expected `target` to have key `pan`. Got target: {target.keys()}.")
  122. ms = target["ms"]
  123. pan = target["pan"]
  124. pan_lr = target.get("pan_lr")
  125. preds, ms, pan, pan_lr = _spatial_distortion_index_update(preds, ms, pan, pan_lr)
  126. self.preds.append(preds)
  127. self.ms.append(target["ms"])
  128. self.pan.append(target["pan"])
  129. if "pan_lr" in target:
  130. self.pan_lr.append(target["pan_lr"])
  131. def compute(self) -> Tensor:
  132. """Compute and returns spatial distortion index."""
  133. preds = dim_zero_cat(self.preds)
  134. ms = dim_zero_cat(self.ms)
  135. pan = dim_zero_cat(self.pan)
  136. pan_lr = dim_zero_cat(self.pan_lr) if len(self.pan_lr) > 0 else None
  137. target = {"ms": ms, "pan": pan}
  138. target.update({"pan_lr": pan_lr} if pan_lr is not None else {})
  139. return _spatial_distortion_index_compute(
  140. preds, ms, pan, pan_lr, self.norm_order, self.window_size, self.reduction
  141. )
  142. def plot(
  143. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  144. ) -> _PLOT_OUT_TYPE:
  145. """Plot a single or multiple values from the metric.
  146. Args:
  147. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  148. If no value is provided, will automatically call `metric.compute` and plot that result.
  149. ax: An matplotlib axis object. If provided will add plot to that axis
  150. Returns:
  151. Figure and Axes object
  152. Raises:
  153. ModuleNotFoundError:
  154. If `matplotlib` is not installed
  155. .. plot::
  156. :scale: 75
  157. >>> # Example plotting a single value
  158. >>> from torch import rand
  159. >>> from torchmetrics.image import SpatialDistortionIndex
  160. >>> preds = rand([16, 3, 32, 32])
  161. >>> target = {
  162. ... 'ms': rand([16, 3, 16, 16]),
  163. ... 'pan': rand([16, 3, 32, 32]),
  164. ... }
  165. >>> metric = SpatialDistortionIndex()
  166. >>> metric.update(preds, target)
  167. >>> fig_, ax_ = metric.plot()
  168. .. plot::
  169. :scale: 75
  170. >>> # Example plotting multiple values
  171. >>> from torch import rand
  172. >>> from torchmetrics.image import SpatialDistortionIndex
  173. >>> preds = rand([16, 3, 32, 32])
  174. >>> target = {
  175. ... 'ms': rand([16, 3, 16, 16]),
  176. ... 'pan': rand([16, 3, 32, 32]),
  177. ... }
  178. >>> metric = SpatialDistortionIndex()
  179. >>> values = [ ]
  180. >>> for _ in range(10):
  181. ... values.append(metric(preds, target))
  182. >>> fig_, ax_ = metric.plot(values)
  183. """
  184. return self._plot(val, ax)