MAIA bb96820c
Multiphysics at AIA
Loading...
Searching...
No Matches
functions.h
Go to the documentation of this file.
1// Copyright (C) 2024 The m-AIA AUTHORS
2//
3// This file is part of m-AIA (https://git.rwth-aachen.de/aia/m-AIA/m-AIA)
4//
5// SPDX-License-Identifier: LGPL-3.0-only
6
7#ifndef MAIA_FUNCTIONS_H_
8#define MAIA_FUNCTIONS_H_
9
10#include <algorithm>
11#include <cmath>
12#include <iostream>
13#include <sstream>
14#include <string_view>
15#include <sys/stat.h>
16#include <vector>
17#ifdef PVPLUGIN
18#include <mpi.h>
21#include "src/compiler_config.h"
22#include "src/config.h"
23#else
24#include "COMM/mpioverride.h"
25#include "INCLUDE/maiamacro.h"
26#include "INCLUDE/maiatypes.h"
27#include "compiler_config.h"
28#include "config.h"
29#endif
30
36ATTRIBUTES1(ATTRIBUTE_NORETURN)
37void mTerm(const MInt errorCode, const MString& location, const MString& message = "");
38#define TERM(exitval) TERMM(exitval, "")
39#define TERMM(exitval, msg) \
40 do { \
41 mTerm(exitval, AT_, msg); \
42 } while(false)
43
45#define TERMM_IF_COND(termCondition, msg) \
46 do { \
47 if(termCondition) { \
48 TERMM(1, msg); \
49 } \
50 } while(false)
51
53#define TERMM_IF_NOT_COND(termNotCondition, msg) \
54 do { \
55 TERMM_IF_COND(!(termNotCondition), msg); \
56 } while(false)
57
58
59#ifdef MAIA_TIMER_CHECKS
61#define CHECK_TIMERS_IO(message) \
62 do { \
63 maia::dlb::g_dlbTimerController.checkIOTimerStatus(AT_); \
64 } while(false)
65#else
66#define CHECK_TIMERS_IO(message) \
67 do { \
68 } while(false)
69#endif
70
71
73inline MFloat cpuTime() {
74 timespec tp;
75 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tp);
76 const MFloat t_user = (tp.tv_sec + (MFloat)tp.tv_nsec / 1e9);
77 return t_user;
78}
79
80inline MFloat wallTime() { return MPI_Wtime(); }
81
82
83// Should only be used with MFloat!
84template <class Real>
85inline Real ABS(const Real x) {
86 return std::fabs(x);
87}
88
89template <class T>
90constexpr inline T mMin(const T& x, const T& y) {
91 return std::min(x, y);
92}
93template <class T>
94constexpr inline T mMax(const T& x, const T& y) {
95 return std::max(x, y);
96}
97template <class T>
98inline T MIN3(const T& x, const T& y, const T& z) {
99 return std::min(std::min(x, y), z);
100}
101template <class T>
102inline T MAX3(const T& x, const T& y, const T& z) {
103 return std::max(std::max(x, y), z);
104}
105
106template <class T>
107constexpr const T& Clamp(const T& v, const T& lo, const T& hi) {
108 TERMM_IF_COND((hi < lo), "");
109 return (v < lo) ? lo : (hi < v) ? hi : v;
110}
111
112// \brief Copies file \p fromName to file \p toName .
113MInt copyFile(const MString& fromName, const MString& toName);
115MBool fileExists(const MString& fileName);
116
117// ()^2
118template <class Real>
119constexpr Real POW2(const Real x) {
120 return (x * x);
121}
122template <class Real>
123constexpr Real POW3(const Real x) {
124 return (x * x * x);
125}
126template <class Real>
127constexpr Real POW4(const Real x) {
128 return (x * x * x * x);
129}
130template <class Real>
131constexpr Real POW5(const Real x) {
132 return (x * x * x * x * x);
133}
134template <class Real>
135constexpr Real POW6(const Real x) {
136 return (x * x * x * x * x * x);
137}
138
145template <typename T>
146T constexpr POWX(T base, MUint exponent) {
147 return (exponent == 0) ? 1 : base * POWX(base, exponent - 1);
148}
149
150template <typename T>
151typename std::enable_if<std::is_unsigned<T>::value, int>::type inline constexpr signum(T x) {
152 return T(0) < x;
153}
154
155template <typename T>
156typename std::enable_if<std::is_signed<T>::value, int>::type inline constexpr signum(T x) {
157 return (T(0) < x) - (x < T(0));
158}
159
160// the same as above but 0 -> 1
161template <typename T>
162typename std::enable_if<std::is_unsigned<T>::value, int>::type inline constexpr signum0(T x) {
163 return T(0) <= x;
164}
165
166template <typename T>
167typename std::enable_if<std::is_signed<T>::value, int>::type inline constexpr signum0(T x) {
168 return (T(0) <= x) - (x < T(0));
169}
170
171
172/* \brief Sutherland Law Makro for calculating the viscosity by
173 * mue = T^3/2 * (1+S/T_0)(T + S/T_0)
174 * with the default values S=110.4 k and T_0 = 273.15 K
175 *
176 * @author Stephan Schlimpert, 12.12.2010
177 *
178 * TODO labels:totest,toenhance this is WRONG and should be replaced (if T is an expression it will be
179 * evaluated 3 times!)
180 */
181#define SUTHERLANDLAW(T) (((T)*sqrt((T)) * (m_sutherlandPlusOne)) / ((T) + (m_sutherlandConstant)))
182
183/* Index Macro for m_bandNghbrIdsG:
184 * IDX_LSSETDIR(cell,dir,set) = (cell * m_maxNoSets + set ) * m_noDirs + dir
185 *
186 * NOTE: ls-Solver useage only!
187 *
188 * @author Claudia Guenther, Jan. 2012
189 */
190#define IDX_LSSETDIR(i, j, k) (((i)*m_maxNoSets + (k)) * m_noDirs + (j))
191
192/* Index Macro for m_candidateNodeValues:
193 * IDX_LSSETNODES(cell,node,set) = (cell * m_maxNoSets + set ) * m_noCellNodes + node
194 *
195 * NOTE: fv-mb-Solver useage only!
196 *
197 * @author Claudia Guenther, July 2013
198 */
199#define IDX_LSSETNODES(i, j, k) (((i)*m_noLevelSetsUsedForMb + (k)) * m_noCellNodes + (j))
200
201
202/* Index set Macro
203 * IDX_LSSET(cell,set) = (cell * m_maxNoSets + set )
204 *
205 * NOTE: ls-Solver and cartesiansolver useage!
206 *
207 * @author Claudia Guenther, Jan. 2012
208 */
209#define IDX_LSSET(i, j) ((i)*m_maxNoSets + (j))
210
211/* Index Macro for m_levelSetValues:
212 * IDX_LSSETMB(cell,set) = (cell * m_noLevelSetsUsedForMb + set )
213 * Index Macro for m_pointIsInside[ cellId ][.]:
214 * IDX_LSSETMB(point,set) = (point * m_noLevelSetsUsedForMb + set )
215 *
216 * NOTE: fv-mb-Solver useage only!
217 *
218 * @author Claudia Guenther, July 2013
219 */
220#define IDX_LSSETMB(i, j) ((i)*m_noLevelSetsUsedForMb + (j))
221
243#ifdef MAIA_ASSERTS
244#define ASSERT(condition, message) \
245 do { \
246 if(!(condition)) { \
247 std::cerr << "Assertion `" #condition "` failed in " << __FILE__ << " line " << __LINE__ << ": " << message \
248 << std::endl; \
249 mTerm(1, AT_, "ASSERTION FAILED"); \
250 } \
251 } while(false)
252#else
253#define ASSERT(condition, message) \
254 do { \
255 } while(false && (condition))
256#endif
257
258#ifdef MAIA_ASSERT_ACCESSORS
259#define ASSERT_ACCESSOR(condition, message) ASSERT(condition, message)
260#else
261#define ASSERT_ACCESSOR(condition, message) \
262 do { \
263 } while(false && (condition))
264#endif
265
266namespace detail_ {
267template <class T, class U>
268struct APPROX_ERROR {};
269} // namespace detail_
270
271template <class T, class U>
272MBool approx(const T&, const U&, const T) {
274 error();
275 return true;
276}
277
278template <>
279inline MBool approx<MFloat, MFloat>(const MFloat& a, const MFloat& b, const MFloat eps) {
280 return std::fabs(a - b) < eps;
281}
282
283template <class T>
284MBool isApproxInt(const T&, const T) {
286 error();
287 return true;
288}
289
299template <>
300inline MBool isApproxInt<MFloat>(const MFloat& a, const MFloat eps) {
301 return approx(std::fabs(std::round(a) - a), 0.0, eps);
302}
303
317inline MInt ipow(MInt base, MInt exp) {
318 ASSERT(exp >= 0, "Error in ipow: exponent is less than zero (must be greater or equal to zero)!");
319
320 MInt result = 1;
321 while(exp) {
322 if(exp & 1) {
323#ifndef NDEBUG
324 // This piece of code checks (if no -DNDEBUG flag was given during compilation) if signed integer overflow
325 // occurs, and if yes, aborts the program. Signed integer overflow is detected if the result of the last
326 // multiplication can not be reversed.
327 MInt result_test = result * base;
328 ASSERT(((base != 0 && result_test / base == result) || base == 0), "Error in ipow: signed integer overflow!");
329#endif
330 result *= base;
331 }
332 exp >>= 1;
333 base *= base;
334 }
335
336 return result;
337}
338
339
340void checkMultiSolverGridExtents(const MInt nDim, const MFloat* centerOfGravity, const MFloat lengthLevel0,
341 const MInt minLevel, const MFloat* targetGridCenterOfGravity,
342 const MFloat targetGridLengthLevel0, const MInt targetGridMinLevel);
343
344MInt loadPointCoordinatesFromFile(const MString inputFileName, const MInt nDim, std::vector<MFloat>& coordinates);
345
346#ifndef PVPLUGIN
347void writeMemoryStatistics(const MPI_Comm comm, const MInt noDomains, const MInt domainId, const MString at,
348 const MString comment = "");
349#endif
350
351inline int intSwap(int f) { // Change endian of int
352 union {
353 int f;
354 unsigned char b[4];
355 } dat1{}, dat2{};
356
357 dat1.f = f;
358 dat2.b[0] = dat1.b[3];
359 dat2.b[1] = dat1.b[2];
360 dat2.b[2] = dat1.b[1];
361 dat2.b[3] = dat1.b[0];
362 return dat2.f;
363}
364
365inline float floatSwap(float f) { // Change endian of float
366 union {
367 float f;
368 unsigned char b[4];
369 } dat1{}, dat2{};
370
371 dat1.f = f;
372 dat2.b[0] = dat1.b[3];
373 dat2.b[1] = dat1.b[2];
374 dat2.b[2] = dat1.b[1];
375 dat2.b[3] = dat1.b[0];
376 return dat2.f;
377}
378
379inline double doubleSwap(double f) { // Change endian of double
380 union {
381 double f;
382 unsigned char b[8];
383 } dat1{}, dat2{};
384
385 dat1.f = f;
386 dat2.b[0] = dat1.b[7];
387 dat2.b[1] = dat1.b[6];
388 dat2.b[2] = dat1.b[5];
389 dat2.b[3] = dat1.b[4];
390 dat2.b[4] = dat1.b[3];
391 dat2.b[5] = dat1.b[2];
392 dat2.b[6] = dat1.b[1];
393 dat2.b[7] = dat1.b[0];
394 return dat2.f;
395}
396
397// todo labels:toenhance c++17
398// inline std::string_view ltrim(std::string_view s)
399//{
400// s.remove_prefix(std::distance(s.cbegin(), std::find_if(s.cbegin(), s.cend(),
401// [](int c) {return !std::isspace(c);})));
402//
403// return s;
404//}
405//
406// inline std::string_view rtrim(std::string_view s)
407//{
408// s.remove_suffix(std::distance(s.crbegin(), std::find_if(s.crbegin(), s.crend(),
409// [](int c) {return !std::isspace(c);})));
410//
411// return s;
412//}
413//
414// inline std::string_view trim(std::string_view s)
415//{
416// return ltrim(rtrim(s));
417//}
418
419// trim from start
420static inline std::string ltrim(std::string& s) {
421 s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); }));
422 return s;
423}
424
425// trim from end
426static inline std::string rtrim(std::string& s) {
427 s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end());
428 return s;
429}
430
431// trim from both ends
432static inline std::string trim(std::string& s) {
433 ltrim(s);
434 rtrim(s);
435 return s;
436}
437
438template <class ContainerT>
439inline void tokenize(const std::string& str, ContainerT& tokens, const std::string& delimiters = " ",
440 MBool trimEmpty = false) {
441 std::string::size_type pos = 0;
442 std::string::size_type lastPos = 0;
443 std::string::size_type length = str.length();
444
445 using value_type = typename ContainerT::value_type;
446 using size_type = typename ContainerT::size_type;
447
448 while(lastPos < length + 1) {
449 pos = str.find_first_of(delimiters, lastPos);
450 if(pos == std::string::npos) {
451 pos = length;
452 }
453
454 if(pos != lastPos || !trimEmpty) {
455 tokens.push_back(value_type(str.data() + lastPos, (size_type)pos - lastPos));
456 }
457
458 lastPos = pos + 1;
459 }
460}
461
462inline void createDir(const std::string& dir) {
463 struct stat s {};
464 if(stat(dir.c_str(), &s) < 0) {
465 // Create directory if it does not yet exist
466 mkdir(dir.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IXGRP | S_IXGRP);
467 }
468}
469
470#endif
void mTerm(const MInt errorCode, const MString &location, const MString &message)
Definition: functions.cpp:29
constexpr Real POW4(const Real x)
Definition: functions.h:127
T MIN3(const T &x, const T &y, const T &z)
Definition: functions.h:98
ATTRIBUTES1(ATTRIBUTE_NORETURN) void mTerm(const MInt errorCode
controlled termination of maia with a user defined error message
float floatSwap(float f)
Definition: functions.h:365
const MString const MString & message
Definition: functions.h:37
constexpr Real POW3(const Real x)
Definition: functions.h:123
constexpr const T & Clamp(const T &v, const T &lo, const T &hi)
Definition: functions.h:107
std::enable_if< std::is_unsigned< T >::value, int >::type constexpr signum(T x)
Definition: functions.h:151
MBool isApproxInt(const T &, const T)
Definition: functions.h:284
MBool approx< MFloat, MFloat >(const MFloat &a, const MFloat &b, const MFloat eps)
Definition: functions.h:279
constexpr Real POW6(const Real x)
Definition: functions.h:135
constexpr Real POW5(const Real x)
Definition: functions.h:131
constexpr Real POW2(const Real x)
Definition: functions.h:119
Real ABS(const Real x)
Definition: functions.h:85
void checkMultiSolverGridExtents(const MInt nDim, const MFloat *centerOfGravity, const MFloat lengthLevel0, const MInt minLevel, const MFloat *targetGridCenterOfGravity, const MFloat targetGridLengthLevel0, const MInt targetGridMinLevel)
Checks if the given grid extents and cell sizes match when creating a multisolver grid and correspond...
Definition: functions.cpp:112
MInt copyFile(const MString &fromName, const MString &toName)
Copies file fromName to file toName.
Definition: functions.cpp:83
MBool approx(const T &, const U &, const T)
Definition: functions.h:272
MFloat cpuTime()
Return the process cpu time (user time) (high-resolution timer - do not use clock())
Definition: functions.h:73
int intSwap(int f)
Definition: functions.h:351
MInt loadPointCoordinatesFromFile(const MString inputFileName, const MInt nDim, std::vector< MFloat > &coordinates)
Loads point coordinates from an input file.
Definition: functions.cpp:182
constexpr T mMin(const T &x, const T &y)
Definition: functions.h:90
MInt ipow(MInt base, MInt exp)
Integer exponent function for non-negative exponents.
Definition: functions.h:317
void writeMemoryStatistics(const MPI_Comm comm, const MInt noDomains, const MInt domainId, const MString at, const MString comment="")
Write memory statistics.
Definition: functions.cpp:218
MBool isApproxInt< MFloat >(const MFloat &a, const MFloat eps)
Return true if argument is approximately an integer.
Definition: functions.h:300
double doubleSwap(double f)
Definition: functions.h:379
T constexpr POWX(T base, MUint exponent)
Compile time power calculation.
Definition: functions.h:146
void createDir(const std::string &dir)
Definition: functions.h:462
constexpr T mMax(const T &x, const T &y)
Definition: functions.h:94
std::enable_if< std::is_unsigned< T >::value, int >::type constexpr signum0(T x)
Definition: functions.h:162
MFloat wallTime()
Definition: functions.h:80
const MString & location
Definition: functions.h:37
T MAX3(const T &x, const T &y, const T &z)
Definition: functions.h:102
void tokenize(const std::string &str, ContainerT &tokens, const std::string &delimiters=" ", MBool trimEmpty=false)
Definition: functions.h:439
MBool fileExists(const MString &fileName)
Returns true if the file fileName exists, false otherwise.
Definition: functions.cpp:73
int32_t MInt
Definition: maiatypes.h:62
uint32_t MUint
Definition: maiatypes.h:63
std::basic_string< char > MString
Definition: maiatypes.h:55
double MFloat
Definition: maiatypes.h:52
bool MBool
Definition: maiatypes.h:58
Definition: contexttypes.h:19
define array structures