[RFC PATCH 09/11] ipa: libipa: vector: Add sum() and normalize() functions

Laurent Pinchart laurent.pinchart at ideasonboard.com
Sun Nov 17 23:17:10 CET 2024


Add functions to calculate the sum of a vector, and to normalize it.
They are useful for algorithms.

Signed-off-by: Laurent Pinchart <laurent.pinchart at ideasonboard.com>
---
 src/ipa/libipa/vector.cpp | 17 +++++++++++++++++
 src/ipa/libipa/vector.h   | 12 ++++++++++++
 2 files changed, 29 insertions(+)

diff --git a/src/ipa/libipa/vector.cpp b/src/ipa/libipa/vector.cpp
index 14816cdb5d09..0662e598c086 100644
--- a/src/ipa/libipa/vector.cpp
+++ b/src/ipa/libipa/vector.cpp
@@ -296,6 +296,23 @@ namespace ipa {
  * \return The length of the vector
  */
 
+/**
+ * \fn Vector::normalize()
+ * \brief Normalize the vector
+ */
+
+/**
+ * \fn Vector::sum() const
+ * \brief Calculate the sum of all the vector elements
+ * \tparam R The type of the sum
+ *
+ * The type R of the sum defaults to the type T of the elements, but can be set
+ * explicitly to use a different type in case the type T would risk
+ * overflowing.
+ *
+ * \return The sum of all the vector elements
+ */
+
 /**
  * \fn Vector<T, Rows> operator*(const Matrix<T, Rows, Cols> &m, const Vector<T, Cols> &v)
  * \brief Multiply a matrix by a vector
diff --git a/src/ipa/libipa/vector.h b/src/ipa/libipa/vector.h
index 949dc4650aa4..b3a6412497c9 100644
--- a/src/ipa/libipa/vector.h
+++ b/src/ipa/libipa/vector.h
@@ -9,6 +9,7 @@
 #include <algorithm>
 #include <array>
 #include <cmath>
+#include <numeric>
 #include <optional>
 #include <ostream>
 
@@ -245,6 +246,17 @@ public:
 		return std::sqrt(length2());
 	}
 
+	void normalize()
+	{
+		*this /= sum();
+	}
+
+	template<typename R = T>
+	constexpr R sum() const
+	{
+		return std::accumulate(data_.begin(), data_.end(), R{});
+	}
+
 private:
 	static constexpr Vector apply(const Vector &lhs, const Vector &rhs, std::function<T(T, T)> func)
 	{
-- 
Regards,

Laurent Pinchart



More information about the libcamera-devel mailing list