ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
Vector.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2014-2026 The ESPResSo project
3 *
4 * This file is part of ESPResSo.
5 *
6 * ESPResSo is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * ESPResSo is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#pragma once
21
22/**
23 * @file
24 *
25 * @brief Vector implementation and trait types
26 * for boost qvm interoperability.
27 */
28
29#include <boost/qvm/deduce_vec.hpp>
30#include <boost/qvm/vec_traits.hpp>
31
32#include "utils/Array.hpp"
33#include "utils/attributes.hpp"
35
36#include <algorithm>
37#include <cassert>
38#include <cmath>
39#include <concepts>
40#include <cstddef>
41#include <functional>
42#include <initializer_list>
43#include <iterator>
44#include <numeric>
45#include <ranges>
46#include <span>
47#include <stdexcept>
48#include <tuple>
49#include <type_traits>
50#include <utility>
51#include <vector>
52
53// GCC 16 -fanalyzer reports false positives with range-based algorithms
54#if defined(__GNUC__) and not defined(__clang__)
55#pragma GCC diagnostic push
56#pragma GCC diagnostic ignored "-Wanalyzer-out-of-bounds"
57#endif
58
59namespace Utils {
60
61template <typename T, std::size_t N> class Vector : public Array<T, N> {
62 using Base = Array<T, N>;
63
64public:
65 using Base::at;
66 using Base::Base;
67 using Base::operator[];
68 using Base::back;
69 using Base::begin;
70 using Base::cbegin;
71 using Base::cend;
72 using Base::data;
73 using Base::empty;
74 using Base::end;
75 using Base::fill;
76 using Base::front;
77 using Base::max_size;
78 using Base::size;
79
80 template <class U> struct is_vector : std::false_type {};
81 template <class U, std::size_t Np>
82 struct is_vector<Vector<U, Np>> : std::true_type {};
83
84 Vector() noexcept = default;
85 Vector(Vector const &) noexcept = default;
86 Vector &operator=(Vector const &) noexcept = default;
87
88 void swap(Vector &rhs) { std::ranges::swap_ranges(*this, rhs); }
89
90private:
91 constexpr void copy_init(T const *values) noexcept {
92 for (std::size_t i{0}; i != N; ++i) {
93 (*this)[i] = values[i];
94 }
95 }
96
97public:
98 // range-based ctor that excludes Vector<T,N> to avoid ambiguous calls with
99 // the copy ctor, move ctor and cast operator; std::ranges::input_range is
100 // not used due to conflicts with move assignment in recursive variant types
101 // and T[N] must be excluded to avoid shadowing the noexcept ctor
102 template <class Range>
103 requires(not is_vector<std::remove_cvref_t<Range>>::value and
104 not std::is_same_v<std::remove_cvref_t<Range>, T[N]>)
105 explicit constexpr Vector(Range &&rng)
106 : Vector(std::begin(rng), std::end(rng)) {}
107
108#if __cpp_lib_containers_ranges
109 template <std::ranges::input_range Range>
110 Vector(std::from_range_t, Range &&rng)
111 : Vector(std::begin(rng), std::end(rng)) {}
112#endif
113
114 explicit constexpr Vector(T const (&v)[N]) noexcept : Base() {
115 if constexpr (N != 0) {
116 copy_init(std::cbegin(v));
117 }
118 }
119
120 explicit constexpr Vector(Array<T, N> const &array) noexcept : Base(array) {}
121
122 constexpr Vector(std::initializer_list<T> v) : Base() {
123 if (N != v.size()) {
124 throw std::length_error(
125 "Construction of Vector from Container of wrong length.");
126 }
127 if constexpr (N != 0) {
128 copy_init(v.begin());
129 }
130 }
131
132 template <typename InputIterator>
133 Vector(InputIterator first, InputIterator last) : Base() {
134 if (std::distance(first, last) == N) {
135 std::copy_n(first, N, begin());
136 } else {
137 throw std::length_error(
138 "Construction of Vector from Container of wrong length.");
139 }
140 }
141
142 /** @brief Create a vector that has all entries set to the same value. */
143 DEVICE_QUALIFIER static constexpr Vector<T, N>
144 broadcast(typename Base::value_type const &value) noexcept {
145 Vector<T, N> ret;
146 for (std::size_t i = 0u; i != N; ++i) {
147 ret[i] = value;
148 }
149 return ret;
150 }
151
152 std::vector<T> as_vector() const { return std::vector<T>(begin(), end()); }
153
154 operator std::vector<T>() const { return as_vector(); }
155
156 constexpr std::span<const T, N> as_span() const noexcept {
157 return std::span<const T, N>(begin(), N);
158 }
159
160 constexpr operator std::span<const T, N>() const noexcept {
161 return as_span();
162 }
163
164 template <class U> explicit operator Vector<U, N>() const {
165 Vector<U, N> ret;
166
167 std::ranges::transform(*this, ret.begin(),
168 [](T const &e) { return static_cast<U>(e); });
169
170 return ret;
171 }
172
173 constexpr T norm2() const { return (*this) * (*this); }
174 T norm() const { return std::sqrt(norm2()); }
175
176 /*
177 * @brief Normalize the vector.
178 *
179 * Normalize the vector by its length,
180 * if not zero, otherwise the vector is unchanged.
181 */
183 auto const l = norm();
184 if (l != T(0)) {
185 *this /= l;
186 }
187
188 return *this;
189 }
190
191 /*
192 * @brief Return a normalized copy of the vector.
193 *
194 * Normalize the vector by its length,
195 * if not zero, otherwise the vector is unchanged.
196 */
198 auto const l = norm();
199 return (l != T(0)) ? (*this) / l : *this;
200 }
201};
202
203template <class T> using Vector3 = Vector<T, 3>;
204
205template <std::size_t N> using VectorXd = Vector<double, N>;
211
212template <std::size_t N> using VectorXf = Vector<float, N>;
214
215template <std::size_t N> using VectorXi = Vector<int, N>;
217
218namespace detail {
219template <std::size_t N, typename T, typename U, typename Op>
220auto binary_op(Vector<T, N> const &a, Vector<U, N> const &b, Op op) {
221 // we must use the non-range version std::transform for Vector<T, N> because:
222 // GCC 12 cannot inspect -Wmaybe-uninitialized through std::ranges::transform
223 // Clang/Xcode libc++ cannot select the binary form of std::ranges::transform
224 using R = decltype(std::declval<T>() + std::declval<U>());
225 Vector<R, N> ret;
226
227 // NOLINTNEXTLINE(modernize-use-ranges)
228 std::transform(std::begin(a), std::end(a), std::begin(b), std::begin(ret),
229 op);
230
231 return ret;
232}
233} // namespace detail
234
235#define ESPRESSO_VECTOR_COMPARISON(op) \
236 template <std::size_t N, typename T> \
237 constexpr bool \
238 operator op(Vector<T, N> const &a, Vector<T, N> const &b) noexcept( \
239 noexcept(std::declval<T const &>() op std::declval<T const &>())) { \
240 for (std::size_t i = 0u; i < N; ++i) { \
241 if (not(a[i] op b[i])) { \
242 return false; \
243 } \
244 } \
245 return true; \
246 }
247// synthesize all operators, except a!=b which C++20 rewrites as !(a==b)
253#undef ESPRESSO_VECTOR_COMPARISON
254
255template <std::size_t N, typename T, typename U>
256auto operator+(Vector<T, N> const &a, Vector<U, N> const &b) {
257 return detail::binary_op(a, b, std::plus<>());
258}
259
260template <std::size_t N, typename T>
262 Vector<T, N> const &b) {
263 std::ranges::transform(a, b, std::begin(a), std::plus<T>());
264 return a;
265}
266
267template <std::size_t N, typename T, typename U>
268auto operator-(Vector<T, N> const &a, Vector<U, N> const &b) {
269 return detail::binary_op(a, b, std::minus<>());
270}
271
272template <std::size_t N, typename T>
274 Vector<T, N> ret;
275 std::ranges::transform(a, std::begin(ret), std::negate<T>());
276 return ret;
277}
278
279template <std::size_t N, typename T>
280ESPRESSO_ATTR_ALWAYS_INLINE inline Vector<T, N> &
282 std::ranges::transform(a, b, std::begin(a), std::minus<T>());
283 return a;
284}
285
286/* Scalar multiplication */
287template <std::size_t N, typename T, class U>
288 requires(std::is_arithmetic_v<U>)
289constexpr auto operator*(U const &a, Vector<T, N> const &b) {
290 using R = decltype(a * std::declval<T>());
291 Vector<R, N> ret;
292 std::ranges::transform(b, std::begin(ret), [a](T const &v) { return a * v; });
293 return ret;
294}
295
296template <std::size_t N, typename T, class U>
297 requires(std::is_arithmetic_v<U>)
298constexpr auto operator*(Vector<T, N> const &a, U const &b) {
299 using R = decltype(std::declval<T>() * b);
300 Vector<R, N> ret;
301 std::ranges::transform(a, std::begin(ret), [b](T const &v) { return b * v; });
302 return ret;
303}
304
305template <std::size_t N, typename T>
306auto &operator*=(Vector<T, N> &b, T const &a) {
307 std::ranges::transform(b, std::begin(b), [a](T const &v) { return a * v; });
308 return b;
309}
310
311/* Scalar division */
312template <std::size_t N, typename T, class U>
313auto operator/(Vector<T, N> const &a, U const &b) {
314 using R = decltype(std::declval<T>() / b);
315 Vector<R, N> ret;
316 std::ranges::transform(a, std::begin(ret), [b](T const &v) { return v / b; });
317 return ret;
318}
319
320template <std::size_t N, typename T, class U>
321auto operator/(U const &a, Vector<T, N> const &b) {
322 using R = decltype(a / std::declval<T>());
323 Vector<R, N> ret;
324 std::ranges::transform(b, std::begin(ret), [a](T const &v) { return a / v; });
325 return ret;
326}
327
328template <std::size_t N, typename T>
329auto &operator/=(Vector<T, N> &a, T const &b) {
330 std::ranges::transform(a, std::begin(a), [b](T const &v) { return v / b; });
331 return a;
332}
333
334namespace detail {
335template <class T> using is_vector = Vector<int, 1>::is_vector<T>;
336} // namespace detail
337
338/* Scalar product */
339template <std::size_t N, typename T, class U>
340 requires(not(detail::is_vector<T>::value or detail::is_vector<U>::value))
341auto constexpr operator*(Vector<T, N> const &a, Vector<U, N> const &b) {
342 using R = decltype(std::declval<T>() * std::declval<U>());
343 // std::inner_product isn't always inlined on Intel CPUs even with -O3,
344 // but a for loop can be inlined
345 R acc{};
346 for (std::size_t i = 0u; i < N; ++i) {
347 acc += a[i] * b[i];
348 }
349 return acc;
350}
351
352template <std::size_t N, typename T, class U>
353 requires(std::is_integral_v<T> and std::is_integral_v<U>)
354auto operator%(Vector<T, N> const &a, Vector<U, N> const &b) {
355 using R = decltype(std::declval<T>() % std::declval<U>());
356 Vector<R, N> ret;
357 std::ranges::transform(a, b, std::begin(ret), std::modulus<>());
358 return ret;
359}
360
361/* Componentwise square root */
362template <std::size_t N, typename T> auto sqrt(Vector<T, N> const &a) {
363 using std::sqrt;
364 using R = decltype(sqrt(std::declval<T>()));
365 Vector<R, N> ret;
366 std::ranges::transform(a, ret.begin(), [](T const &v) { return sqrt(v); });
367 return ret;
368}
369
370template <class T>
372 // use noexcept constructor to elide the exception logic
373 T v[3] = {a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2],
374 a[0] * b[1] - a[1] * b[0]};
375 return Vector<T, 3>(v);
376}
377
378// Product of array elements.
379template <class T, std::size_t N> T product(Vector<T, N> const &v) {
380 return std::accumulate(v.cbegin(), v.cend(), T{1}, std::multiplies<T>());
381}
382
383template <class T, class U, std::size_t N>
385 using R = decltype(std::declval<T>() * std::declval<U>());
386 auto constexpr proj = std::identity{}; // required by Clang/Xcode libc++
387 Vector<R, N> ret;
388 std::ranges::transform(a, b, ret.begin(), std::multiplies<>(), proj, proj);
389 return ret;
390}
391
392// specialization for when one or both operands is a scalar depending on
393// compile time features (e.g. when PARTICLE_ANISOTROPY is not enabled)
394template <typename T, typename U>
395 requires(not(detail::is_vector<T>::value and detail::is_vector<U>::value))
396auto hadamard_product(T const &a, U const &b) {
397 return a * b;
398}
399
400template <class T, class U, std::size_t N>
402 using R = decltype(std::declval<T>() / std::declval<U>());
403 auto constexpr proj = std::identity{}; // required by Clang/Xcode libc++
404 Vector<R, N> ret;
405 std::ranges::transform(a, b, std::begin(ret), std::divides<>(), proj, proj);
406 return ret;
407}
408
409// specialization for when one or both operands is a scalar depending on
410// compile time features (e.g. when PARTICLE_ANISOTROPY is not enabled)
411template <typename T, typename U>
412 requires(not(detail::is_vector<T>::value and detail::is_vector<U>::value))
413auto hadamard_division(T const &a, U const &b) {
414 return a / b;
415}
416
417template <typename T> Vector<T, 3> unit_vector(unsigned int i) {
418 if (i == 0u)
419 return {T{1}, T{0}, T{0}};
420 if (i == 1u)
421 return {T{0}, T{1}, T{0}};
422 if (i == 2u)
423 return {T{0}, T{0}, T{1}};
424 throw std::domain_error("coordinate out of range");
425}
426
427/**
428 * @brief Meta function to turn a Vector<T, 1> into T.
429 */
430template <typename T> struct decay_to_scalar {};
431template <typename T, std::size_t N> struct decay_to_scalar<Vector<T, N>> {
433};
434
435template <typename T> struct decay_to_scalar<Vector<T, 1>> {
436 using type = T;
437};
438
439template <std::size_t I, class T, std::size_t N>
440T &get(Vector<T, N> &a) noexcept {
441 return a[I];
442}
443
444template <std::size_t I, class T, std::size_t N>
445T const &get(Vector<T, N> const &a) noexcept {
446 return a[I];
447}
448
449} // namespace Utils
450
451// Tuple-like interface for structured bindings.
452// Specializing these for user-defined types is permitted by [namespace.std],
453// but Clang-Tidy 22 reports partial specializations as a false positive.
454// NOLINTBEGIN(bugprone-std-namespace-modification)
455
456template <std::size_t I, class T, std::size_t N>
457struct std::tuple_element<I, Utils::Vector<T, N>> {
458 static_assert(I < N, "Utils::Vector index must be in range");
459 using type = T;
460};
461
462template <class T, std::size_t N>
463struct std::tuple_size<Utils::Vector<T, N>>
464 : std::integral_constant<std::size_t, N> {};
465
466// NOLINTEND(bugprone-std-namespace-modification)
467
468namespace boost::qvm {
469
470template <class T, std::size_t N> struct vec_traits<::Utils::Vector<T, N>> {
471
472 static constexpr std::size_t dim = N;
473 using scalar_type = T;
474
475 template <std::size_t I>
476 static constexpr inline scalar_type &write_element(::Utils::Vector<T, N> &v) {
477 return v[I];
478 }
479
480 template <std::size_t I>
481 static constexpr inline scalar_type
483 return v[I];
484 }
485
486 static inline scalar_type read_element_idx(std::size_t i,
487 ::Utils::Vector<T, N> const &v) {
488 return v[i];
489 }
490 static inline scalar_type &write_element_idx(std::size_t i,
492 return v[i];
493 }
494};
495
496template <typename T> struct deduce_vec<Utils::Vector<T, 3>, 3> {
498};
499
500} // namespace boost::qvm
501
504UTILS_ARRAY_BOOST_CLASS(Utils::Vector, N, object_serializable)
506
507#if defined(__GNUC__) and not defined(__clang__)
508#pragma GCC diagnostic pop
509#endif
Array implementation with CUDA support.
#define ESPRESSO_VECTOR_COMPARISON(op)
Definition Vector.hpp:235
#define UTILS_ARRAY_BOOST_MPI_T(Container, N)
Mark array types as MPI data types.
Definition array.hpp:50
#define UTILS_ARRAY_BOOST_BIT_S(Container, N)
Mark array types as MPI bitwise serializable.
Definition array.hpp:63
#define UTILS_ARRAY_BOOST_CLASS(Container, N, ImplementationLevel)
Redefinition of BOOST_CLASS_IMPLEMENTATION for array types.
Definition array.hpp:78
#define UTILS_ARRAY_BOOST_TRACK(Container, N, TrackingLevel)
Redefinition of BOOST_CLASS_TRACKING for array types.
Definition array.hpp:97
Compiler-attribute macros shared across ESPResSo headers.
#define ESPRESSO_ATTR_ALWAYS_INLINE
Vector() noexcept=default
Vector & normalize()
Definition Vector.hpp:182
T norm() const
Definition Vector.hpp:174
constexpr Vector(T const (&v)[N]) noexcept
Definition Vector.hpp:114
void swap(Vector &rhs)
Definition Vector.hpp:88
DEVICE_QUALIFIER constexpr iterator begin() noexcept
Definition Array.hpp:141
Vector normalized() const
Definition Vector.hpp:197
DEVICE_QUALIFIER constexpr const_iterator cbegin() const noexcept
Definition Array.hpp:149
std::vector< T > as_vector() const
Definition Vector.hpp:152
Vector(InputIterator first, InputIterator last)
Definition Vector.hpp:133
constexpr Vector(std::initializer_list< T > v)
Definition Vector.hpp:122
DEVICE_QUALIFIER constexpr const_iterator cend() const noexcept
Definition Array.hpp:161
constexpr std::span< const T, N > as_span() const noexcept
Definition Vector.hpp:156
DEVICE_QUALIFIER constexpr iterator end() noexcept
Definition Array.hpp:153
static DEVICE_QUALIFIER constexpr Vector< T, N > broadcast(typename Base::value_type const &value) noexcept
Create a vector that has all entries set to the same value.
Definition Vector.hpp:144
constexpr Vector(Range &&rng)
Definition Vector.hpp:105
constexpr T norm2() const
Definition Vector.hpp:173
constexpr Vector(Array< T, N > const &array) noexcept
Definition Vector.hpp:120
#define DEVICE_QUALIFIER
VectorXd< 9 > Vector9d
Definition Vector.hpp:210
auto operator+(Vector< T, N > const &a, Vector< U, N > const &b)
Definition Vector.hpp:256
Vector< T, 3 > unit_vector(unsigned int i)
Definition Vector.hpp:417
T product(Vector< T, N > const &v)
Definition Vector.hpp:379
VectorXd< 2 > Vector2d
Definition Vector.hpp:206
VectorXd< 4 > Vector4d
Definition Vector.hpp:208
VectorXd< 3 > Vector3d
Definition Vector.hpp:207
Vector< T, 3 > vector_product(Vector< T, 3 > const &a, Vector< T, 3 > const &b)
Definition Vector.hpp:371
Vector< double, N > VectorXd
Definition Vector.hpp:205
T & get(Array< T, N > &a) noexcept
Definition Array.hpp:210
Vector< int, N > VectorXi
Definition Vector.hpp:215
auto operator/(Vector< T, N > const &a, U const &b)
Definition Vector.hpp:313
ESPRESSO_ATTR_ALWAYS_INLINE auto & operator+=(Vector< T, N > &a, Vector< T, N > const &b)
Definition Vector.hpp:261
Vector< T, 3 > Vector3
Definition Vector.hpp:203
VectorXi< 3 > Vector3i
Definition Vector.hpp:216
VectorXf< 3 > Vector3f
Definition Vector.hpp:213
ESPRESSO_ATTR_ALWAYS_INLINE Vector< T, N > & operator-=(Vector< T, N > &a, Vector< T, N > const &b)
Definition Vector.hpp:281
auto hadamard_division(Vector< T, N > const &a, Vector< U, N > const &b)
Definition Vector.hpp:401
auto & operator*=(Vector< T, N > &b, T const &a)
Definition Vector.hpp:306
VectorXd< 6 > Vector6d
Definition Vector.hpp:209
auto hadamard_product(Vector< T, N > const &a, Vector< U, N > const &b)
Definition Vector.hpp:384
auto operator-(Vector< T, N > const &a, Vector< U, N > const &b)
Definition Vector.hpp:268
auto sqrt(Vector< T, N > const &a)
Definition Vector.hpp:362
auto & operator/=(Vector< T, N > &a, T const &b)
Definition Vector.hpp:329
Vector< float, N > VectorXf
Definition Vector.hpp:212
STL namespace.
DEVICE_QUALIFIER constexpr reference at(size_type i)
Definition Array.hpp:98
DEVICE_QUALIFIER constexpr bool empty() const noexcept
Definition Array.hpp:165
DEVICE_QUALIFIER constexpr reference back()
Definition Array.hpp:127
DEVICE_QUALIFIER constexpr pointer data() noexcept
Definition Array.hpp:133
DEVICE_QUALIFIER constexpr size_type max_size() const noexcept
Definition Array.hpp:169
DEVICE_QUALIFIER constexpr iterator begin() noexcept
Definition Array.hpp:141
DEVICE_QUALIFIER constexpr const_iterator cbegin() const noexcept
Definition Array.hpp:149
DEVICE_QUALIFIER constexpr const_iterator cend() const noexcept
Definition Array.hpp:161
DEVICE_QUALIFIER constexpr size_type size() const noexcept
Definition Array.hpp:167
DEVICE_QUALIFIER constexpr reference front()
Definition Array.hpp:123
DEVICE_QUALIFIER constexpr iterator end() noexcept
Definition Array.hpp:153
DEVICE_QUALIFIER void fill(const value_type &value)
Definition Array.hpp:171
Meta function to turn a Vector<T, 1> into T.
Definition Vector.hpp:430
static constexpr scalar_type read_element(::Utils::Vector< T, N > const &v)
Definition Vector.hpp:482
static scalar_type & write_element_idx(std::size_t i, ::Utils::Vector< T, N > &v)
Definition Vector.hpp:490
static constexpr scalar_type & write_element(::Utils::Vector< T, N > &v)
Definition Vector.hpp:476
static scalar_type read_element_idx(std::size_t i, ::Utils::Vector< T, N > const &v)
Definition Vector.hpp:486