From c2a67a84134c0563d482b0b4df95dee3003004c4 Mon Sep 17 00:00:00 2001
From: "Joachim Wuttke (h)" <j.wuttke@fz-juelich.de>
Date: Thu, 22 Dec 2022 23:38:44 +0100
Subject: [PATCH] meanRelativeDifference: throw if data fields are empty or
 contain only zeroes

---
 Device/Histo/DiffUtil.cpp | 26 +++++++++++++++++++++-----
 1 file changed, 21 insertions(+), 5 deletions(-)

diff --git a/Device/Histo/DiffUtil.cpp b/Device/Histo/DiffUtil.cpp
index 23dacb1195c..2d143eda600 100644
--- a/Device/Histo/DiffUtil.cpp
+++ b/Device/Histo/DiffUtil.cpp
@@ -50,13 +50,29 @@ Datafield* DiffUtil::relativeDifferenceField(const Datafield& dat, const Datafie
 double DiffUtil::meanRelativeDifference(const SimulationResult& dat, const SimulationResult& ref)
 {
     if (dat.size() != ref.size())
-        throw std::runtime_error("Error in DiffUtil::meanRelativeDifference: "
-                                 "different number of elements");
+        throw std::runtime_error("Invalid call to meanRelativeDifference: "
+                                 "different number of elements in dat and ref datasets");
     if (dat.empty())
-        return 0.0;
-    double sum_of_diff = 0.0;
-    for (size_t i = 0; i < dat.size(); ++i)
+        throw std::runtime_error("Invalid call to meanRelativeDifference: "
+                                 "empty dat and ref datasets");
+
+    double sum_of_diff = 0.;
+    double sum_of_fdat = 0.;
+    double sum_of_fref = 0.;
+    for (size_t i = 0; i < dat.size(); ++i) {
         sum_of_diff += Numeric::relativeDifference(dat[i], ref[i]);
+        sum_of_fdat += fabs(dat[i]);
+        sum_of_fref += fabs(ref[i]);
+    }
+    if (sum_of_fdat == 0 && sum_of_fref)
+        throw std::runtime_error("Invalid call to meanRelativeDifference: "
+                                 "dat and ref only contain zeroes");
+    if (sum_of_fdat == 0)
+        throw std::runtime_error("Invalid call to meanRelativeDifference: "
+                                 "dat only contains zeroes");
+    if (sum_of_fref == 0)
+        throw std::runtime_error("Invalid call to meanRelativeDifference: "
+                                 "ref only contains zeroes");
     return sum_of_diff / dat.size();
 }
 
-- 
GitLab