Penning Trap Simulation Simulate particle behavior inside a Penning Trap

Loading...
Searching...
No Matches
utils.cpp
Go to the documentation of this file.
1
13#include "utils.hpp"
14
15std::string scientific_format(double d, int width, int prec)
16{
17 std::stringstream ss;
18 ss << std::setw(width) << std::setprecision(prec) << std::scientific << d;
19 return ss.str();
20}
21
22std::string scientific_format(const std::vector<double> &v, int width, int prec)
23{
24 std::stringstream ss;
25 for (double elem : v) {
26 ss << scientific_format(elem, width, prec);
27 }
28 return ss.str();
29}
30
31 static void print_message(std::string msg)
32{
33 if (msg.size() > 0) {
34 std::cout << "message: " << msg << "\n\n";
35 } else {
36 std::cout << "\n";
37 }
38}
39
40 void m_assert(bool expr, std::string expr_str, std::string f, std::string file,
41 int line, std::string msg)
42{
43 std::string new_assert(f.size() + (expr ? 4 : 6), '-');
44 std::cout << "\x1B[36m" << new_assert << "\033[0m\n";
45 std::cout << f << ": ";
46 if (expr) {
47 std::cout << "\x1B[32mOK\033[0m\n";
48 print_message(msg);
49 } else {
50 std::cout << "\x1B[31mFAIL\033[0m\n";
51 print_message(msg);
52 std::cout << file << " " << line << ": Assertion \"" << expr_str
53 << "\" Failed\n\n";
54 abort();
55 }
56}
57
58 bool close_to(arma::vec &a, arma::vec &b, double tol)
59{
60 if (a.n_elem != b.n_elem) {
61 return false;
62 }
63
64 for (size_t i = 0; i < a.n_elem; i++) {
65 if (std::abs(a(i) - b(i)) >= tol) {
66 return false;
67 }
68 }
69 return true;
70}
71
72 bool mkpath(std::string path, int mode)
73{
74 std::string cur_dir;
75 std::string::size_type pos = -1;
76 struct stat buf;
77
78 if (path.back() != '/') {
79 path += '/';
80 }
81 while (true) {
82 pos++;
83 pos = path.find('/', pos);
84 if (pos != std::string::npos) {
85 cur_dir = path.substr(0, pos);
86 if (mkdir(cur_dir.c_str(), mode) != 0
87 && stat(cur_dir.c_str(), &buf) != 0) {
88 return -1;
89 }
90 } else {
91 break;
92 }
93 }
94 return 0;
95}
close_to
bool close_to(arma::vec &a, arma::vec &b, double tol)
Test if two armadillo vectors are close to each other.
Definition: utils.cpp:58
scientific_format
std::string scientific_format(double d, int width, int prec)
Turns a double into a string written in scientific format.
Definition: utils.cpp:15
mkpath
bool mkpath(std::string path, int mode)
Make path given.
Definition: utils.cpp:72
m_assert
void m_assert(bool expr, std::string expr_str, std::string f, std::string file, int line, std::string msg)
Test an expression, confirm that test is ok, or abort execution.
Definition: utils.cpp:40
utils.hpp
Function prototypes and macros that are useful.