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