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