ESPResSo
Extensible Simulation Package for Research on Soft Matter Systems
Loading...
Searching...
No Matches
periodic_fold.hpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2010-2022 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#ifndef CORE_ALGORITHM_PERIODIC_FOLD_HPP
20#define CORE_ALGORITHM_PERIODIC_FOLD_HPP
21
22#include <cmath>
23#include <concepts>
24#include <limits>
25#include <type_traits>
26#include <utility>
27
28// Define a concept that checks if a type T is an integer or a reference to an
29// integer
30template <typename T>
31concept IntegralOrRef = std::integral<std::remove_reference_t<T>>;
32template <typename T>
33concept FloatingPointOrRef = std::floating_point<std::remove_reference_t<T>>;
34
35namespace Algorithm {
36/**
37 * @brief Fold value into primary interval.
38 *
39 * @param x Value to fold
40 * @param i Image count before folding
41 * @param l Length of primary interval
42 * @return x folded into [0, l) and number of folds.
43 */
44template <FloatingPointOrRef T, IntegralOrRef I>
45std::pair<T, I> periodic_fold(T x, I i, T const l) {
46 using limits = std::numeric_limits<I>;
47
48 while ((x < T{0}) && (i > limits::min())) {
49 x += l;
50 --i;
51 }
52
53 while ((x >= l) && (i < limits::max())) {
54 x -= l;
55 ++i;
56 }
57
58 return {x, i};
59}
60
61/**
62 * @brief Fold value into primary interval.
63 *
64 * @param x Value to fold
65 * @param l Length of primary interval
66 * @return x folded into [0, l).
67 */
68template <FloatingPointOrRef T> T periodic_fold(T x, T const l) {
69#ifndef __FAST_MATH__
70 /* Can't fold if either x or l is nan or inf. */
71 if (std::isnan(x) or std::isnan(l) or std::isinf(x) or (l == 0)) {
72 return std::nan("");
73 }
74 if (std::isinf(l)) {
75 return x;
76 }
77#endif // __FAST_MATH__
78
79 while (x < 0) {
80 x += l;
81 }
82
83 while (x >= l) {
84 x -= l;
85 }
86
87 return x;
88}
89} // namespace Algorithm
90
91#endif
std::pair< T, I > periodic_fold(T x, I i, T const l)
Fold value into primary interval.