We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Error in ERGAS metric
In the definition of ERGAS, it should be `\ ratio` rather than `* ratio` 

For example see ERGAS defined in [Du et al](https://ieeexplore.ieee.org/abstract/document/4317530), [Meng et al](https://ieeexplore.ieee.org/document/9082183)

https://github.com/Lightning-AI/torchmetrics/blob/4230cfef3d2020fffff873565acea01ad883d3e4/src/torchmetrics/functional/image/ergas.py#L82

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/torchmetrics/functional/image/ergas.py`
Content:
```
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 typing import Tuple
15 
16 import torch
17 from torch import Tensor
18 from typing_extensions import Literal
19 
20 from torchmetrics.utilities.checks import _check_same_shape
21 from torchmetrics.utilities.distributed import reduce
22 
23 
24 def _ergas_update(preds: Tensor, target: Tensor) -> Tuple[Tensor, Tensor]:
25     """Update and returns variables required to compute Erreur Relative Globale Adimensionnelle de Synthèse.
26 
27     Args:
28         preds: Predicted tensor
29         target: Ground truth tensor
30 
31     """
32     if preds.dtype != target.dtype:
33         raise TypeError(
34             "Expected `preds` and `target` to have the same data type."
35             f" Got preds: {preds.dtype} and target: {target.dtype}."
36         )
37     _check_same_shape(preds, target)
38     if len(preds.shape) != 4:
39         raise ValueError(
40             "Expected `preds` and `target` to have BxCxHxW shape."
41             f" Got preds: {preds.shape} and target: {target.shape}."
42         )
43     return preds, target
44 
45 
46 def _ergas_compute(
47     preds: Tensor,
48     target: Tensor,
49     ratio: float = 4,
50     reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
51 ) -> Tensor:
52     """Erreur Relative Globale Adimensionnelle de Synthèse.
53 
54     Args:
55         preds: estimated image
56         target: ground truth image
57         ratio: ratio of high resolution to low resolution
58         reduction: a method to reduce metric score over labels.
59 
60             - ``'elementwise_mean'``: takes the mean (default)
61             - ``'sum'``: takes the sum
62             - ``'none'`` or ``None``: no reduction will be applied
63 
64     Example:
65         >>> gen = torch.manual_seed(42)
66         >>> preds = torch.rand([16, 1, 16, 16], generator=gen)
67         >>> target = preds * 0.75
68         >>> preds, target = _ergas_update(preds, target)
69         >>> torch.round(_ergas_compute(preds, target))
70         tensor(154.)
71 
72     """
73     b, c, h, w = preds.shape
74     preds = preds.reshape(b, c, h * w)
75     target = target.reshape(b, c, h * w)
76 
77     diff = preds - target
78     sum_squared_error = torch.sum(diff * diff, dim=2)
79     rmse_per_band = torch.sqrt(sum_squared_error / (h * w))
80     mean_target = torch.mean(target, dim=2)
81 
82     ergas_score = 100 * ratio * torch.sqrt(torch.sum((rmse_per_band / mean_target) ** 2, dim=1) / c)
83     return reduce(ergas_score, reduction)
84 
85 
86 def error_relative_global_dimensionless_synthesis(
87     preds: Tensor,
88     target: Tensor,
89     ratio: float = 4,
90     reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
91 ) -> Tensor:
92     """Erreur Relative Globale Adimensionnelle de Synthèse.
93 
94     Args:
95         preds: estimated image
96         target: ground truth image
97         ratio: ratio of high resolution to low resolution
98         reduction: a method to reduce metric score over labels.
99 
100             - ``'elementwise_mean'``: takes the mean (default)
101             - ``'sum'``: takes the sum
102             - ``'none'`` or ``None``: no reduction will be applied
103 
104     Return:
105         Tensor with RelativeG score
106 
107     Raises:
108         TypeError:
109             If ``preds`` and ``target`` don't have the same data type.
110         ValueError:
111             If ``preds`` and ``target`` don't have ``BxCxHxW shape``.
112 
113     Example:
114         >>> from torchmetrics.functional.image import error_relative_global_dimensionless_synthesis
115         >>> gen = torch.manual_seed(42)
116         >>> preds = torch.rand([16, 1, 16, 16], generator=gen)
117         >>> target = preds * 0.75
118         >>> ergds = error_relative_global_dimensionless_synthesis(preds, target)
119         >>> torch.round(ergds)
120         tensor(154.)
121 
122     References:
123         [1] Qian Du; Nicholas H. Younan; Roger King; Vijay P. Shah, "On the Performance Evaluation of
124         Pan-Sharpening Techniques" in IEEE Geoscience and Remote Sensing Letters, vol. 4, no. 4, pp. 518-522,
125         15 October 2007, doi: 10.1109/LGRS.2007.896328.
126 
127     """
128     preds, target = _ergas_update(preds, target)
129     return _ergas_compute(preds, target, ratio, reduction)
130
```

Path: `src/torchmetrics/image/ergas.py`
Content:
```
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 
15 from typing import Any, List, Optional, Sequence, Union
16 
17 from torch import Tensor
18 from typing_extensions import Literal
19 
20 from torchmetrics.functional.image.ergas import _ergas_compute, _ergas_update
21 from torchmetrics.metric import Metric
22 from torchmetrics.utilities import rank_zero_warn
23 from torchmetrics.utilities.data import dim_zero_cat
24 from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
25 from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
26 
27 if not _MATPLOTLIB_AVAILABLE:
28     __doctest_skip__ = ["ErrorRelativeGlobalDimensionlessSynthesis.plot"]
29 
30 
31 class ErrorRelativeGlobalDimensionlessSynthesis(Metric):
32     """Calculate `Relative dimensionless global error synthesis`_ (ERGAS).
33 
34     This metric is used to calculate the accuracy of Pan sharpened image considering normalized average error of each
35     band of the result image.
36 
37     As input to ``forward`` and ``update`` the metric accepts the following input
38 
39     - ``preds`` (:class:`~torch.Tensor`): Predictions from model
40     - ``target`` (:class:`~torch.Tensor`): Ground truth values
41 
42     As output of `forward` and `compute` the metric returns the following output
43 
44     - ``ergas`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average ERGAS
45       value over sample else returns tensor of shape ``(N,)`` with ERGAS values per sample
46 
47     Args:
48         ratio: ratio of high resolution to low resolution
49         reduction: a method to reduce metric score over labels.
50 
51             - ``'elementwise_mean'``: takes the mean (default)
52             - ``'sum'``: takes the sum
53             - ``'none'`` or ``None``: no reduction will be applied
54 
55         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
56 
57     Example:
58         >>> import torch
59         >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
60         >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))
61         >>> target = preds * 0.75
62         >>> ergas = ErrorRelativeGlobalDimensionlessSynthesis()
63         >>> torch.round(ergas(preds, target))
64         tensor(154.)
65 
66     """
67 
68     higher_is_better: bool = False
69     is_differentiable: bool = True
70     full_state_update: bool = False
71     plot_lower_bound: float = 0.0
72 
73     preds: List[Tensor]
74     target: List[Tensor]
75 
76     def __init__(
77         self,
78         ratio: float = 4,
79         reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
80         **kwargs: Any,
81     ) -> None:
82         super().__init__(**kwargs)
83         rank_zero_warn(
84             "Metric `UniversalImageQualityIndex` will save all targets and"
85             " predictions in buffer. For large datasets this may lead"
86             " to large memory footprint."
87         )
88 
89         self.add_state("preds", default=[], dist_reduce_fx="cat")
90         self.add_state("target", default=[], dist_reduce_fx="cat")
91         self.ratio = ratio
92         self.reduction = reduction
93 
94     def update(self, preds: Tensor, target: Tensor) -> None:
95         """Update state with predictions and targets."""
96         preds, target = _ergas_update(preds, target)
97         self.preds.append(preds)
98         self.target.append(target)
99 
100     def compute(self) -> Tensor:
101         """Compute explained variance over state."""
102         preds = dim_zero_cat(self.preds)
103         target = dim_zero_cat(self.target)
104         return _ergas_compute(preds, target, self.ratio, self.reduction)
105 
106     def plot(
107         self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
108     ) -> _PLOT_OUT_TYPE:
109         """Plot a single or multiple values from the metric.
110 
111         Args:
112             val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
113                 If no value is provided, will automatically call `metric.compute` and plot that result.
114             ax: An matplotlib axis object. If provided will add plot to that axis
115 
116         Returns:
117             Figure and Axes object
118 
119         Raises:
120             ModuleNotFoundError:
121                 If `matplotlib` is not installed
122 
123         .. plot::
124             :scale: 75
125 
126             >>> # Example plotting a single value
127             >>> import torch
128             >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
129             >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))
130             >>> target = preds * 0.75
131             >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()
132             >>> metric.update(preds, target)
133             >>> fig_, ax_ = metric.plot()
134 
135         .. plot::
136             :scale: 75
137 
138             >>> # Example plotting multiple values
139             >>> import torch
140             >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis
141             >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))
142             >>> target = preds * 0.75
143             >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()
144             >>> values = [ ]
145             >>> for _ in range(10):
146             ...     values.append(metric(preds, target))
147             >>> fig_, ax_ = metric.plot(values)
148 
149         """
150         return self._plot(val, ax)
151
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/torchmetrics/functional/image/ergas.py b/src/torchmetrics/functional/image/ergas.py
--- a/src/torchmetrics/functional/image/ergas.py
+++ b/src/torchmetrics/functional/image/ergas.py
@@ -89,7 +89,7 @@
     ratio: float = 4,
     reduction: Literal["elementwise_mean", "sum", "none", None] = "elementwise_mean",
 ) -> Tensor:
-    """Erreur Relative Globale Adimensionnelle de Synthèse.
+    """Calculates `Error relative global dimensionless synthesis`_ (ERGAS) metric.
 
     Args:
         preds: estimated image
@@ -119,11 +119,6 @@
         >>> torch.round(ergds)
         tensor(154.)
 
-    References:
-        [1] Qian Du; Nicholas H. Younan; Roger King; Vijay P. Shah, "On the Performance Evaluation of
-        Pan-Sharpening Techniques" in IEEE Geoscience and Remote Sensing Letters, vol. 4, no. 4, pp. 518-522,
-        15 October 2007, doi: 10.1109/LGRS.2007.896328.
-
     """
     preds, target = _ergas_update(preds, target)
     return _ergas_compute(preds, target, ratio, reduction)
diff --git a/src/torchmetrics/image/ergas.py b/src/torchmetrics/image/ergas.py
--- a/src/torchmetrics/image/ergas.py
+++ b/src/torchmetrics/image/ergas.py
@@ -29,10 +29,18 @@
 
 
 class ErrorRelativeGlobalDimensionlessSynthesis(Metric):
-    """Calculate `Relative dimensionless global error synthesis`_ (ERGAS).
+    r"""Calculate the `Error relative global dimensionless synthesis`_  (ERGAS) metric.
 
     This metric is used to calculate the accuracy of Pan sharpened image considering normalized average error of each
-    band of the result image.
+    band of the result image. It is defined as:
+
+    .. math::
+        ERGAS = 100 * \frac{h}{l} \\sqrt{\frac{1}{N} \\sum_{k=1}^{N} \frac{RMSE(B_k)^2}{\\mu_k^2}}
+
+    where :math:`h` and :math:`l` denote the spatial resolution (pixel size) of the high and low resolution images,
+    often shorted to the ratio between them :math:`r=h/l`. :math:`N` is the number of spectral bands, :math:`RMSE(B_k)`
+    is the root mean square error of the k-th band between low and high resolution images, and :math:`\\mu_k` is the
+    mean value of the k-th band of the reference image.
 
     As input to ``forward`` and ``update`` the metric accepts the following input
 
@@ -45,7 +53,7 @@
       value over sample else returns tensor of shape ``(N,)`` with ERGAS values per sample
 
     Args:
-        ratio: ratio of high resolution to low resolution
+        ratio: ratio of high resolution to low resolution.
         reduction: a method to reduce metric score over labels.
 
             - ``'elementwise_mean'``: takes the mean (default)

{"golden_diff": "diff --git a/src/torchmetrics/functional/image/ergas.py b/src/torchmetrics/functional/image/ergas.py\n--- a/src/torchmetrics/functional/image/ergas.py\n+++ b/src/torchmetrics/functional/image/ergas.py\n@@ -89,7 +89,7 @@\n     ratio: float = 4,\n     reduction: Literal[\"elementwise_mean\", \"sum\", \"none\", None] = \"elementwise_mean\",\n ) -> Tensor:\n-    \"\"\"Erreur Relative Globale Adimensionnelle de Synth\u00e8se.\n+    \"\"\"Calculates `Error relative global dimensionless synthesis`_ (ERGAS) metric.\n \n     Args:\n         preds: estimated image\n@@ -119,11 +119,6 @@\n         >>> torch.round(ergds)\n         tensor(154.)\n \n-    References:\n-        [1] Qian Du; Nicholas H. Younan; Roger King; Vijay P. Shah, \"On the Performance Evaluation of\n-        Pan-Sharpening Techniques\" in IEEE Geoscience and Remote Sensing Letters, vol. 4, no. 4, pp. 518-522,\n-        15 October 2007, doi: 10.1109/LGRS.2007.896328.\n-\n     \"\"\"\n     preds, target = _ergas_update(preds, target)\n     return _ergas_compute(preds, target, ratio, reduction)\ndiff --git a/src/torchmetrics/image/ergas.py b/src/torchmetrics/image/ergas.py\n--- a/src/torchmetrics/image/ergas.py\n+++ b/src/torchmetrics/image/ergas.py\n@@ -29,10 +29,18 @@\n \n \n class ErrorRelativeGlobalDimensionlessSynthesis(Metric):\n-    \"\"\"Calculate `Relative dimensionless global error synthesis`_ (ERGAS).\n+    r\"\"\"Calculate the `Error relative global dimensionless synthesis`_  (ERGAS) metric.\n \n     This metric is used to calculate the accuracy of Pan sharpened image considering normalized average error of each\n-    band of the result image.\n+    band of the result image. It is defined as:\n+\n+    .. math::\n+        ERGAS = 100 * \\frac{h}{l} \\\\sqrt{\\frac{1}{N} \\\\sum_{k=1}^{N} \\frac{RMSE(B_k)^2}{\\\\mu_k^2}}\n+\n+    where :math:`h` and :math:`l` denote the spatial resolution (pixel size) of the high and low resolution images,\n+    often shorted to the ratio between them :math:`r=h/l`. :math:`N` is the number of spectral bands, :math:`RMSE(B_k)`\n+    is the root mean square error of the k-th band between low and high resolution images, and :math:`\\\\mu_k` is the\n+    mean value of the k-th band of the reference image.\n \n     As input to ``forward`` and ``update`` the metric accepts the following input\n \n@@ -45,7 +53,7 @@\n       value over sample else returns tensor of shape ``(N,)`` with ERGAS values per sample\n \n     Args:\n-        ratio: ratio of high resolution to low resolution\n+        ratio: ratio of high resolution to low resolution.\n         reduction: a method to reduce metric score over labels.\n \n             - ``'elementwise_mean'``: takes the mean (default)\n", "issue": "Error in ERGAS metric\nIn the definition of ERGAS, it should be `\\ ratio` rather than `* ratio` \r\n\r\nFor example see ERGAS defined in [Du et al](https://ieeexplore.ieee.org/abstract/document/4317530), [Meng et al](https://ieeexplore.ieee.org/document/9082183)\r\n\r\nhttps://github.com/Lightning-AI/torchmetrics/blob/4230cfef3d2020fffff873565acea01ad883d3e4/src/torchmetrics/functional/image/ergas.py#L82\n", "before_files": [{"content": "# Copyright The Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Tuple\n\nimport torch\nfrom torch import Tensor\nfrom typing_extensions import Literal\n\nfrom torchmetrics.utilities.checks import _check_same_shape\nfrom torchmetrics.utilities.distributed import reduce\n\n\ndef _ergas_update(preds: Tensor, target: Tensor) -> Tuple[Tensor, Tensor]:\n    \"\"\"Update and returns variables required to compute Erreur Relative Globale Adimensionnelle de Synth\u00e8se.\n\n    Args:\n        preds: Predicted tensor\n        target: Ground truth tensor\n\n    \"\"\"\n    if preds.dtype != target.dtype:\n        raise TypeError(\n            \"Expected `preds` and `target` to have the same data type.\"\n            f\" Got preds: {preds.dtype} and target: {target.dtype}.\"\n        )\n    _check_same_shape(preds, target)\n    if len(preds.shape) != 4:\n        raise ValueError(\n            \"Expected `preds` and `target` to have BxCxHxW shape.\"\n            f\" Got preds: {preds.shape} and target: {target.shape}.\"\n        )\n    return preds, target\n\n\ndef _ergas_compute(\n    preds: Tensor,\n    target: Tensor,\n    ratio: float = 4,\n    reduction: Literal[\"elementwise_mean\", \"sum\", \"none\", None] = \"elementwise_mean\",\n) -> Tensor:\n    \"\"\"Erreur Relative Globale Adimensionnelle de Synth\u00e8se.\n\n    Args:\n        preds: estimated image\n        target: ground truth image\n        ratio: ratio of high resolution to low resolution\n        reduction: a method to reduce metric score over labels.\n\n            - ``'elementwise_mean'``: takes the mean (default)\n            - ``'sum'``: takes the sum\n            - ``'none'`` or ``None``: no reduction will be applied\n\n    Example:\n        >>> gen = torch.manual_seed(42)\n        >>> preds = torch.rand([16, 1, 16, 16], generator=gen)\n        >>> target = preds * 0.75\n        >>> preds, target = _ergas_update(preds, target)\n        >>> torch.round(_ergas_compute(preds, target))\n        tensor(154.)\n\n    \"\"\"\n    b, c, h, w = preds.shape\n    preds = preds.reshape(b, c, h * w)\n    target = target.reshape(b, c, h * w)\n\n    diff = preds - target\n    sum_squared_error = torch.sum(diff * diff, dim=2)\n    rmse_per_band = torch.sqrt(sum_squared_error / (h * w))\n    mean_target = torch.mean(target, dim=2)\n\n    ergas_score = 100 * ratio * torch.sqrt(torch.sum((rmse_per_band / mean_target) ** 2, dim=1) / c)\n    return reduce(ergas_score, reduction)\n\n\ndef error_relative_global_dimensionless_synthesis(\n    preds: Tensor,\n    target: Tensor,\n    ratio: float = 4,\n    reduction: Literal[\"elementwise_mean\", \"sum\", \"none\", None] = \"elementwise_mean\",\n) -> Tensor:\n    \"\"\"Erreur Relative Globale Adimensionnelle de Synth\u00e8se.\n\n    Args:\n        preds: estimated image\n        target: ground truth image\n        ratio: ratio of high resolution to low resolution\n        reduction: a method to reduce metric score over labels.\n\n            - ``'elementwise_mean'``: takes the mean (default)\n            - ``'sum'``: takes the sum\n            - ``'none'`` or ``None``: no reduction will be applied\n\n    Return:\n        Tensor with RelativeG score\n\n    Raises:\n        TypeError:\n            If ``preds`` and ``target`` don't have the same data type.\n        ValueError:\n            If ``preds`` and ``target`` don't have ``BxCxHxW shape``.\n\n    Example:\n        >>> from torchmetrics.functional.image import error_relative_global_dimensionless_synthesis\n        >>> gen = torch.manual_seed(42)\n        >>> preds = torch.rand([16, 1, 16, 16], generator=gen)\n        >>> target = preds * 0.75\n        >>> ergds = error_relative_global_dimensionless_synthesis(preds, target)\n        >>> torch.round(ergds)\n        tensor(154.)\n\n    References:\n        [1] Qian Du; Nicholas H. Younan; Roger King; Vijay P. Shah, \"On the Performance Evaluation of\n        Pan-Sharpening Techniques\" in IEEE Geoscience and Remote Sensing Letters, vol. 4, no. 4, pp. 518-522,\n        15 October 2007, doi: 10.1109/LGRS.2007.896328.\n\n    \"\"\"\n    preds, target = _ergas_update(preds, target)\n    return _ergas_compute(preds, target, ratio, reduction)\n", "path": "src/torchmetrics/functional/image/ergas.py"}, {"content": "# Copyright The Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Any, List, Optional, Sequence, Union\n\nfrom torch import Tensor\nfrom typing_extensions import Literal\n\nfrom torchmetrics.functional.image.ergas import _ergas_compute, _ergas_update\nfrom torchmetrics.metric import Metric\nfrom torchmetrics.utilities import rank_zero_warn\nfrom torchmetrics.utilities.data import dim_zero_cat\nfrom torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE\nfrom torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE\n\nif not _MATPLOTLIB_AVAILABLE:\n    __doctest_skip__ = [\"ErrorRelativeGlobalDimensionlessSynthesis.plot\"]\n\n\nclass ErrorRelativeGlobalDimensionlessSynthesis(Metric):\n    \"\"\"Calculate `Relative dimensionless global error synthesis`_ (ERGAS).\n\n    This metric is used to calculate the accuracy of Pan sharpened image considering normalized average error of each\n    band of the result image.\n\n    As input to ``forward`` and ``update`` the metric accepts the following input\n\n    - ``preds`` (:class:`~torch.Tensor`): Predictions from model\n    - ``target`` (:class:`~torch.Tensor`): Ground truth values\n\n    As output of `forward` and `compute` the metric returns the following output\n\n    - ``ergas`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average ERGAS\n      value over sample else returns tensor of shape ``(N,)`` with ERGAS values per sample\n\n    Args:\n        ratio: ratio of high resolution to low resolution\n        reduction: a method to reduce metric score over labels.\n\n            - ``'elementwise_mean'``: takes the mean (default)\n            - ``'sum'``: takes the sum\n            - ``'none'`` or ``None``: no reduction will be applied\n\n        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.\n\n    Example:\n        >>> import torch\n        >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis\n        >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))\n        >>> target = preds * 0.75\n        >>> ergas = ErrorRelativeGlobalDimensionlessSynthesis()\n        >>> torch.round(ergas(preds, target))\n        tensor(154.)\n\n    \"\"\"\n\n    higher_is_better: bool = False\n    is_differentiable: bool = True\n    full_state_update: bool = False\n    plot_lower_bound: float = 0.0\n\n    preds: List[Tensor]\n    target: List[Tensor]\n\n    def __init__(\n        self,\n        ratio: float = 4,\n        reduction: Literal[\"elementwise_mean\", \"sum\", \"none\", None] = \"elementwise_mean\",\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(**kwargs)\n        rank_zero_warn(\n            \"Metric `UniversalImageQualityIndex` will save all targets and\"\n            \" predictions in buffer. For large datasets this may lead\"\n            \" to large memory footprint.\"\n        )\n\n        self.add_state(\"preds\", default=[], dist_reduce_fx=\"cat\")\n        self.add_state(\"target\", default=[], dist_reduce_fx=\"cat\")\n        self.ratio = ratio\n        self.reduction = reduction\n\n    def update(self, preds: Tensor, target: Tensor) -> None:\n        \"\"\"Update state with predictions and targets.\"\"\"\n        preds, target = _ergas_update(preds, target)\n        self.preds.append(preds)\n        self.target.append(target)\n\n    def compute(self) -> Tensor:\n        \"\"\"Compute explained variance over state.\"\"\"\n        preds = dim_zero_cat(self.preds)\n        target = dim_zero_cat(self.target)\n        return _ergas_compute(preds, target, self.ratio, self.reduction)\n\n    def plot(\n        self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None\n    ) -> _PLOT_OUT_TYPE:\n        \"\"\"Plot a single or multiple values from the metric.\n\n        Args:\n            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.\n                If no value is provided, will automatically call `metric.compute` and plot that result.\n            ax: An matplotlib axis object. If provided will add plot to that axis\n\n        Returns:\n            Figure and Axes object\n\n        Raises:\n            ModuleNotFoundError:\n                If `matplotlib` is not installed\n\n        .. plot::\n            :scale: 75\n\n            >>> # Example plotting a single value\n            >>> import torch\n            >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis\n            >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))\n            >>> target = preds * 0.75\n            >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()\n            >>> metric.update(preds, target)\n            >>> fig_, ax_ = metric.plot()\n\n        .. plot::\n            :scale: 75\n\n            >>> # Example plotting multiple values\n            >>> import torch\n            >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis\n            >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))\n            >>> target = preds * 0.75\n            >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()\n            >>> values = [ ]\n            >>> for _ in range(10):\n            ...     values.append(metric(preds, target))\n            >>> fig_, ax_ = metric.plot(values)\n\n        \"\"\"\n        return self._plot(val, ax)\n", "path": "src/torchmetrics/image/ergas.py"}], "after_files": [{"content": "# Copyright The Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Tuple\n\nimport torch\nfrom torch import Tensor\nfrom typing_extensions import Literal\n\nfrom torchmetrics.utilities.checks import _check_same_shape\nfrom torchmetrics.utilities.distributed import reduce\n\n\ndef _ergas_update(preds: Tensor, target: Tensor) -> Tuple[Tensor, Tensor]:\n    \"\"\"Update and returns variables required to compute Erreur Relative Globale Adimensionnelle de Synth\u00e8se.\n\n    Args:\n        preds: Predicted tensor\n        target: Ground truth tensor\n\n    \"\"\"\n    if preds.dtype != target.dtype:\n        raise TypeError(\n            \"Expected `preds` and `target` to have the same data type.\"\n            f\" Got preds: {preds.dtype} and target: {target.dtype}.\"\n        )\n    _check_same_shape(preds, target)\n    if len(preds.shape) != 4:\n        raise ValueError(\n            \"Expected `preds` and `target` to have BxCxHxW shape.\"\n            f\" Got preds: {preds.shape} and target: {target.shape}.\"\n        )\n    return preds, target\n\n\ndef _ergas_compute(\n    preds: Tensor,\n    target: Tensor,\n    ratio: float = 4,\n    reduction: Literal[\"elementwise_mean\", \"sum\", \"none\", None] = \"elementwise_mean\",\n) -> Tensor:\n    \"\"\"Erreur Relative Globale Adimensionnelle de Synth\u00e8se.\n\n    Args:\n        preds: estimated image\n        target: ground truth image\n        ratio: ratio of high resolution to low resolution\n        reduction: a method to reduce metric score over labels.\n\n            - ``'elementwise_mean'``: takes the mean (default)\n            - ``'sum'``: takes the sum\n            - ``'none'`` or ``None``: no reduction will be applied\n\n    Example:\n        >>> gen = torch.manual_seed(42)\n        >>> preds = torch.rand([16, 1, 16, 16], generator=gen)\n        >>> target = preds * 0.75\n        >>> preds, target = _ergas_update(preds, target)\n        >>> torch.round(_ergas_compute(preds, target))\n        tensor(154.)\n\n    \"\"\"\n    b, c, h, w = preds.shape\n    preds = preds.reshape(b, c, h * w)\n    target = target.reshape(b, c, h * w)\n\n    diff = preds - target\n    sum_squared_error = torch.sum(diff * diff, dim=2)\n    rmse_per_band = torch.sqrt(sum_squared_error / (h * w))\n    mean_target = torch.mean(target, dim=2)\n\n    ergas_score = 100 * ratio * torch.sqrt(torch.sum((rmse_per_band / mean_target) ** 2, dim=1) / c)\n    return reduce(ergas_score, reduction)\n\n\ndef error_relative_global_dimensionless_synthesis(\n    preds: Tensor,\n    target: Tensor,\n    ratio: float = 4,\n    reduction: Literal[\"elementwise_mean\", \"sum\", \"none\", None] = \"elementwise_mean\",\n) -> Tensor:\n    \"\"\"Calculates `Error relative global dimensionless synthesis`_ (ERGAS) metric.\n\n    Args:\n        preds: estimated image\n        target: ground truth image\n        ratio: ratio of high resolution to low resolution\n        reduction: a method to reduce metric score over labels.\n\n            - ``'elementwise_mean'``: takes the mean (default)\n            - ``'sum'``: takes the sum\n            - ``'none'`` or ``None``: no reduction will be applied\n\n    Return:\n        Tensor with RelativeG score\n\n    Raises:\n        TypeError:\n            If ``preds`` and ``target`` don't have the same data type.\n        ValueError:\n            If ``preds`` and ``target`` don't have ``BxCxHxW shape``.\n\n    Example:\n        >>> from torchmetrics.functional.image import error_relative_global_dimensionless_synthesis\n        >>> gen = torch.manual_seed(42)\n        >>> preds = torch.rand([16, 1, 16, 16], generator=gen)\n        >>> target = preds * 0.75\n        >>> ergds = error_relative_global_dimensionless_synthesis(preds, target)\n        >>> torch.round(ergds)\n        tensor(154.)\n\n    \"\"\"\n    preds, target = _ergas_update(preds, target)\n    return _ergas_compute(preds, target, ratio, reduction)\n", "path": "src/torchmetrics/functional/image/ergas.py"}, {"content": "# Copyright The Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom typing import Any, List, Optional, Sequence, Union\n\nfrom torch import Tensor\nfrom typing_extensions import Literal\n\nfrom torchmetrics.functional.image.ergas import _ergas_compute, _ergas_update\nfrom torchmetrics.metric import Metric\nfrom torchmetrics.utilities import rank_zero_warn\nfrom torchmetrics.utilities.data import dim_zero_cat\nfrom torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE\nfrom torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE\n\nif not _MATPLOTLIB_AVAILABLE:\n    __doctest_skip__ = [\"ErrorRelativeGlobalDimensionlessSynthesis.plot\"]\n\n\nclass ErrorRelativeGlobalDimensionlessSynthesis(Metric):\n    r\"\"\"Calculate the `Error relative global dimensionless synthesis`_  (ERGAS) metric.\n\n    This metric is used to calculate the accuracy of Pan sharpened image considering normalized average error of each\n    band of the result image. It is defined as:\n\n    .. math::\n        ERGAS = 100 * \\frac{h}{l} \\\\sqrt{\\frac{1}{N} \\\\sum_{k=1}^{N} \\frac{RMSE(B_k)^2}{\\\\mu_k^2}}\n\n    where :math:`h` and :math:`l` denote the spatial resolution (pixel size) of the high and low resolution images,\n    often shorted to the ratio between them :math:`r=h/l`. :math:`N` is the number of spectral bands, :math:`RMSE(B_k)`\n    is the root mean square error of the k-th band between low and high resolution images, and :math:`\\\\mu_k` is the\n    mean value of the k-th band of the reference image.\n\n    As input to ``forward`` and ``update`` the metric accepts the following input\n\n    - ``preds`` (:class:`~torch.Tensor`): Predictions from model\n    - ``target`` (:class:`~torch.Tensor`): Ground truth values\n\n    As output of `forward` and `compute` the metric returns the following output\n\n    - ``ergas`` (:class:`~torch.Tensor`): if ``reduction!='none'`` returns float scalar tensor with average ERGAS\n      value over sample else returns tensor of shape ``(N,)`` with ERGAS values per sample\n\n    Args:\n        ratio: ratio of high resolution to low resolution.\n        reduction: a method to reduce metric score over labels.\n\n            - ``'elementwise_mean'``: takes the mean (default)\n            - ``'sum'``: takes the sum\n            - ``'none'`` or ``None``: no reduction will be applied\n\n        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.\n\n    Example:\n        >>> import torch\n        >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis\n        >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))\n        >>> target = preds * 0.75\n        >>> ergas = ErrorRelativeGlobalDimensionlessSynthesis()\n        >>> torch.round(ergas(preds, target))\n        tensor(154.)\n\n    \"\"\"\n\n    higher_is_better: bool = False\n    is_differentiable: bool = True\n    full_state_update: bool = False\n    plot_lower_bound: float = 0.0\n\n    preds: List[Tensor]\n    target: List[Tensor]\n\n    def __init__(\n        self,\n        ratio: float = 4,\n        reduction: Literal[\"elementwise_mean\", \"sum\", \"none\", None] = \"elementwise_mean\",\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(**kwargs)\n        rank_zero_warn(\n            \"Metric `UniversalImageQualityIndex` will save all targets and\"\n            \" predictions in buffer. For large datasets this may lead\"\n            \" to large memory footprint.\"\n        )\n\n        self.add_state(\"preds\", default=[], dist_reduce_fx=\"cat\")\n        self.add_state(\"target\", default=[], dist_reduce_fx=\"cat\")\n        self.ratio = ratio\n        self.reduction = reduction\n\n    def update(self, preds: Tensor, target: Tensor) -> None:\n        \"\"\"Update state with predictions and targets.\"\"\"\n        preds, target = _ergas_update(preds, target)\n        self.preds.append(preds)\n        self.target.append(target)\n\n    def compute(self) -> Tensor:\n        \"\"\"Compute explained variance over state.\"\"\"\n        preds = dim_zero_cat(self.preds)\n        target = dim_zero_cat(self.target)\n        return _ergas_compute(preds, target, self.ratio, self.reduction)\n\n    def plot(\n        self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None\n    ) -> _PLOT_OUT_TYPE:\n        \"\"\"Plot a single or multiple values from the metric.\n\n        Args:\n            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.\n                If no value is provided, will automatically call `metric.compute` and plot that result.\n            ax: An matplotlib axis object. If provided will add plot to that axis\n\n        Returns:\n            Figure and Axes object\n\n        Raises:\n            ModuleNotFoundError:\n                If `matplotlib` is not installed\n\n        .. plot::\n            :scale: 75\n\n            >>> # Example plotting a single value\n            >>> import torch\n            >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis\n            >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))\n            >>> target = preds * 0.75\n            >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()\n            >>> metric.update(preds, target)\n            >>> fig_, ax_ = metric.plot()\n\n        .. plot::\n            :scale: 75\n\n            >>> # Example plotting multiple values\n            >>> import torch\n            >>> from torchmetrics.image import ErrorRelativeGlobalDimensionlessSynthesis\n            >>> preds = torch.rand([16, 1, 16, 16], generator=torch.manual_seed(42))\n            >>> target = preds * 0.75\n            >>> metric = ErrorRelativeGlobalDimensionlessSynthesis()\n            >>> values = [ ]\n            >>> for _ in range(10):\n            ...     values.append(metric(preds, target))\n            >>> fig_, ax_ = metric.plot(values)\n\n        \"\"\"\n        return self._plot(val, ax)\n", "path": "src/torchmetrics/image/ergas.py"}]}