Alamo
Util.cpp
Go to the documentation of this file.
1#include "Util.H"
2#include "Color.H"
3
4#include <chrono>
5#include <cstdlib>
6#include <filesystem>
7#include <stdexcept>
8
9#include "AMReX_ParallelDescriptor.H"
10#include "AMReX_Utility.H"
11
12#include "IO/ParmParse.H"
13#include "IO/WriteMetaData.H"
14#include "IO/FileNameParse.H"
15#include "Color.H"
16#include "Numeric/Stencil.H"
17
18namespace Util
19{
20
21std::string filename = "";
22std::string globalprefix = "";
23std::pair<std::string,std::string> file_overwrite;
24bool initialized = false;
25bool finalized = false;
26
27std::string GetFileName()
28{
29 if (filename == "")
30 {
32 IO::ParmParse pp_amr("amr");
33
34 if (pp_amr.contains("plot_file") && pp.contains("plot_file"))
35 Util::Abort("plot_file specified in too many locations");
36 else if (pp_amr.contains("plot_file"))
37 {
38 if (amrex::ParallelDescriptor::IOProcessor())
39 amrex::Warning("amr.plot_file will be depricated; use plot_file instead");
40 pp_amr.query("plot_file", filename);
41
42 }
43 else if (pp.contains("plot_file"))
44 {
45 pp_query("plot_file", filename); // Name of directory containing all output data
46 }
48 // else
49 // if (amrex::ParallelDescriptor::IOProcessor())
50 // Util::Abort("No plot file specified! (Specify plot_file = \"plot_file_name\" in input file");
51 }
52 return filename;
53}
54void CopyFileToOutputDir(std::string a_path, bool fullpath, std::string prefix)
55{
56 try
57 {
58 if (filename == "")
59 Util::Exception(INFO,"Cannot back up files yet because the output directory has not been specified");
60
61 std::string basefilename = std::filesystem::path(a_path).filename();
62 std::string absolutepath = std::filesystem::absolute(std::filesystem::path(a_path)).string();
63 std::string abspathfilename = absolutepath;
64 std::replace(abspathfilename.begin(),abspathfilename.end(),'/','_');
65 if (prefix != "")
66 {
67 abspathfilename = prefix + "__" + abspathfilename;
68 basefilename = prefix + "__" + abspathfilename;
69 }
70
71 if (amrex::ParallelDescriptor::IOProcessor())
72 {
73 std::string destinationpath;
74 if (fullpath) destinationpath = filename+"/"+abspathfilename;
75 else destinationpath = filename+"/"+basefilename;
76
77 // Copy the file where the file name is the absolute path, with / replaced with _
78 if (std::filesystem::exists(destinationpath))
79 Util::Exception(INFO,"Trying to copy ",destinationpath," but it already exists.");
80 std::filesystem::copy_file(a_path,destinationpath);
81 }
82 }
83 catch (std::filesystem::filesystem_error const& ex)
84 {
86 "file system error: \n",
87 " what(): " , ex.what() , '\n',
88 " path1(): " , ex.path1() , '\n',
89 " path2(): " , ex.path2() , '\n',
90 " code().value(): " , ex.code().value() , '\n',
91 " code().message(): " , ex.code().message() , '\n',
92 " code().category(): " , ex.code().category().name());
93 }
94}
95
96std::pair<std::string,std::string> GetOverwrittenFile()
97{
98 return file_overwrite;
99}
100
101void SignalHandler(int s)
102{
103 if (amrex::ParallelDescriptor::IOProcessor())
104 {
105 std::string filename = GetFileName();
107 if (s == SIGSEGV) status = IO::Status::Segfault;
108 else if (s == SIGINT) status = IO::Status::Interrupt;
109 if (s == SIGABRT) status = IO::Status::Abort;
110 if (filename != "")
112 }
113
114#ifdef MEME
115 IO::ParmParse pp;
116 if (!pp.contains("nomeme"))
117 {
118 time_t timer; time(&timer);
119 std::stringstream cmd;
120 cmd << "xdg-open " << BUILD_DIR << "/src/Util/Meme/cat0" << (1+((int)timer)%6) << ".gif &";
121 std::system(cmd.str().c_str());
122 std::cout << Color::Bold << Color::FG::Red << "PROGRAM FAILED!" << Color::Reset << " (Compile without -DMEME, or set nomeme = 1 in the input file to disable this!)";
123 }
124#endif
125
126 amrex::BLBackTrace::handler(s);
127}
128
129
131{
132 int argc = 0;
133 char **argv = nullptr;
134 Initialize(argc,argv);
135 initialized = true;
136}
137void Initialize (int argc, char* argv[])
138{
139 srand (time(NULL));
140
141 amrex::Initialize(argc, argv);
142
143 IO::ParmParse pp_amrex("amrex");
144 pp_amrex.add("throw_exception",1);
145 //amrex.throw_exception=1
146
147 signal(SIGSEGV, Util::SignalHandler);
148 signal(SIGINT, Util::SignalHandler);
149 signal(SIGABRT, Util::SignalHandler);
150
151 std::string filename = GetFileName();
152
153 if (amrex::ParallelDescriptor::IOProcessor() && filename != "")
154 {
157 }
158
159 IO::ParmParse pp;
160 std::string length, time, mass, temperature, current, amount, luminousintensity;
161 // Set the system length unit
162 pp.query_default("system.length",length,"m");
163 // Set the system time unit
164 pp.query_default("system.time",time,"s");
165 // Set the system mass unit
166 pp.query_default("system.mass",mass,"kg");
167 // Set the system temperature unit
168 pp.query_default("system.temperature",temperature,"K");
169 // Set the system current unit
170 pp.query_default("system.current",current,"A");
171 // Set the system amount unit
172 pp.query_default("system.amount",amount,"mol");
173 // Set the system luminous intensity unit
174 pp.query_default("system.luminousintensity",luminousintensity,"cd");
175 try
176 {
177 Unit::setLengthUnit(length);
178 Unit::setTimeUnit(time);
179 Unit::setMassUnit(mass);
180 Unit::setTemperatureUnit(temperature);
181 Unit::setCurrentUnit(current);
182 Unit::setAmountUnit(amount);
183 Unit::setLuminousIntensityUnit(luminousintensity);
184 }
185 catch (std::runtime_error &e)
186 {
187 Util::Exception(INFO, "Error in setting system units: ", e.what());
188 }
189
190 //
191 // This is some logic to unit-ize the geometry.prob_lo, geometry.prob_hi input variables/
192 // We also do some checking to make sure the geometry is valid.
193 //
194 // Note that here, unlike most places, we actually **replace and overwrite** the
195 // geom.prob_* variables, since they are read deep inside amrex infrastructure.
196 //
197 {
198 IO::ParmParse pp("geometry");
199
200 if (pp.contains("prob_lo"))
201 {
202 std::vector<Set::Scalar> prob_lo, prob_hi;
203 // Location of the lower+left+bottom corner
204 pp.queryarr("prob_lo", prob_lo, Unit::Length());
205 // Location of the upper_right_top corner
206 pp.queryarr("prob_hi", prob_hi, Unit::Length());
207 pp.remove("prob_lo");
208 pp.remove("prob_hi");
209
210 Util::Assert( INFO,TEST(prob_lo[0] < prob_hi[0]),
211 "Invalid domain specified: ", prob_lo[0], " < x < ", prob_hi[0], " is incorrect.");
212 Util::Assert( INFO,TEST(prob_lo[1] < prob_hi[1]),
213 "Invalid domain specified: ", prob_lo[0], " < y < ", prob_hi[0], " is incorrect.");
214#if AMREX_SPACEDIM>2
215 Util::Assert( INFO,TEST(prob_lo[2] < prob_hi[2]),
216 "Invalid domain specified: ", prob_lo[0], " < z < ", prob_hi[0], " is incorrect.");
217#endif
218
219 Util::DebugMessage(INFO,"Domain lower left corner: ", Set::Vector(prob_lo.data()).transpose());
220 Util::DebugMessage(INFO,"Domain upper right corenr: ", Set::Vector(prob_hi.data()).transpose());
221
222 pp.addarr("prob_lo",prob_lo);
223 pp.addarr("prob_hi",prob_hi);
224 }
225 }
226}
227
229{
230 std::string filename = GetFileName();
231 if (filename != "")
233 amrex::Finalize();
234 finalized = true;
235}
236
237
238
239void
240Abort (const char * msg) { Terminate(msg, SIGABRT, true); }
241
242void
243Terminate(const char * /* msg */, int signal, bool /*backtrace*/)
244{
245 SignalHandler(signal);
246}
247
248std::pair<std::string,std::string>
249CreateCleanDirectory (const std::string &path, bool callbarrier)
250{
251 std::pair<std::string,std::string> ret("","");
252
253 if(amrex::ParallelDescriptor::IOProcessor()) {
254 if(amrex::FileExists(path)) {
255 std::time_t t = std::time(0);
256 std::tm * now = std::localtime(&t);
257 int year = now->tm_year+1900;
258 int month = now->tm_mon+1;
259 int day = now->tm_mday;
260 int hour = now->tm_hour;
261 int minute = now->tm_min;
262 int second = now->tm_sec;
263
264 std::stringstream ss;
265 ss << year
266 << std::setfill('0') << std::setw(2) << month
267 << std::setfill('0') << std::setw(2) << day
268 << std::setfill('0') << std::setw(2) << hour
269 << std::setfill('0') << std::setw(2) << minute
270 << std::setfill('0') << std::setw(2) << second;
271
272 std::string newoldname(path + ".old." + ss.str());
273 if (amrex::system::verbose) {
274 amrex::Print() << "Util::CreateCleanDirectory(): " << path
275 << " exists. Renaming to: " << newoldname << std::endl;
276 }
277 std::rename(path.c_str(), newoldname.c_str());
278 ret.first = path;
279 ret.second = newoldname;
280 }
281 if( ! amrex::UtilCreateDirectory(path, 0755)) {
282 amrex::CreateDirectoryFailed(path);
283 }
284 }
285 if(callbarrier) {
286 // Force other processors to wait until directory is built.
287 amrex::ParallelDescriptor::Barrier("amrex::UtilCreateCleanDirectory");
288 }
289 return ret;
290}
291
292
293namespace Test
294{
295int Message(std::string testname)
296{
297 if (amrex::ParallelDescriptor::IOProcessor())
298 std::cout << std::left
299 << Color::FG::White << Color::Bold << testname << Color::Reset << std::endl;
300 return 0;
301}
302int Message(std::string testname, int failed)
303{
304 if (amrex::ParallelDescriptor::IOProcessor())
305 {
306 winsize w;
307 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
308 std::stringstream ss;
309 if (!failed)
310 ss << "[" << Color::FG::Green << Color::Bold << "PASS" << Color::Reset << "]";
311 else
312 ss << "[" << Color::FG::Red << Color::Bold << "FAIL" << Color::Reset << "]";
313
314 int terminalwidth = 80; //std::min(w.ws_col,(short unsigned int) 100);
315
316 std::cout << std::left
317 << testname
318 << std::setw(terminalwidth - testname.size() + ss.str().size() - 6) << std::right << std::setfill('.') << ss.str() << std::endl;
319 }
320 return failed;
321}
322int SubMessage(std::string testname, int failed)
323{
324 if (amrex::ParallelDescriptor::IOProcessor())
325 {
326 winsize w;
327 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
328 std::stringstream ss;
329 if (!failed)
330 ss << "[" << Color::FG::LightGreen << Color::Bold << "PASS" << Color::Reset << "]";
331 else
332 ss << "[" << Color::FG::Red << Color::Bold << "FAIL" << Color::Reset << "]";
333
334 int terminalwidth = 80;
335
336 std::cout << std::left
337 << " ├ "
338 << testname
339 << std::setw(terminalwidth - testname.size() + ss.str().size() - 12) << std::right << std::setfill('.') << ss.str() << std::endl;
340 }
341 return failed;
342}
343int SubFinalMessage(int failed)
344{
345 if (amrex::ParallelDescriptor::IOProcessor())
346 {
347 winsize w;
348 ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
349 std::stringstream ss;
350 std::cout << std::left << " └ ";
351
352 if (!failed)
353 std::cout << Color::FG::Green << Color::Bold << failed << " tests failed" << Color::Reset << std::endl;
354 else
355 std::cout << Color::FG::Red << Color::Bold << failed << " tests failed" << Color::Reset << std::endl;
356 }
357 return failed;
358}
359
360}
361
362void AverageCellcenterToNode(amrex::MultiFab& node_mf, const int &dcomp, const amrex::MultiFab &cell_mf, const int &scomp, const int &ncomp/*, const int ngrow=0*/)
363{
364 Util::Assert(INFO,TEST(dcomp + ncomp <= node_mf.nComp()));
365 Util::Assert(INFO,TEST(scomp + ncomp <= cell_mf.nComp()));
366 //Util::Assert(INFO,TEST(cell_mf.boxArray() == node_mf.boxArray()));
367 Util::Assert(INFO,TEST(cell_mf.DistributionMap() == cell_mf.DistributionMap()));
368 Util::Assert(INFO,TEST(cell_mf.nGrow() > 0));
369 for (amrex::MFIter mfi(node_mf,amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi)
370 {
371 amrex::Box bx = mfi.nodaltilebox();
372 amrex::Array4<Set::Scalar> const& node = node_mf.array(mfi);
373 amrex::Array4<const Set::Scalar> const& cell = cell_mf.array(mfi);
374 for (int n = 0; n < ncomp; n++)
375 amrex::ParallelFor (bx,[=] AMREX_GPU_DEVICE(int i, int j, int k) {
376 node(i,j,k,dcomp+n) = Numeric::Interpolate::CellToNodeAverage(cell,i,j,k,scomp+n);
377 });
378 }
379}
380
381
382}
std::time_t t
#define pp_query(...)
Definition ParmParse.H:108
#define TEST(x)
Definition Util.H:22
#define INFO
Definition Util.H:21
bool contains(std::string name)
Definition ParmParse.H:173
int queryarr(std::string name, std::vector< T > &value)
Definition ParmParse.H:529
int query_default(std::string name, T &value, T defaultvalue)
Definition ParmParse.H:293
static std::string Green
Definition Color.H:21
static std::string LightGreen
Definition Color.H:29
static std::string Red
Definition Color.H:20
static std::string White
Definition Color.H:34
static std::string Bold
Definition Color.H:9
static std::string Reset
Definition Color.H:8
void WriteMetaData(std::string plot_file, Status status, int per)
void FileNameParse(std::string &filename)
Internal function to do processing of the file name.
@ Segfault
@ Complete
@ Running
@ Interrupt
@ Abort
Eigen::Matrix< amrex::Real, AMREX_SPACEDIM, 1 > Vector
Definition Base.H:19
Definition GB.H:8
int Message(std::string testname)
Definition Util.cpp:295
int SubMessage(std::string testname, int failed)
Definition Util.cpp:322
int SubFinalMessage(int failed)
Definition Util.cpp:343
A collection of utility routines.
Definition Set.cpp:8
std::pair< std::string, std::string > CreateCleanDirectory(const std::string &path, bool callbarrier)
Definition Util.cpp:249
void DebugMessage(std::string, std::string, int, Args const &...)
Definition Util.H:173
std::string GetFileName()
Definition Util.cpp:27
bool finalized
Definition Util.cpp:25
void Abort(const char *msg)
Definition Util.cpp:240
std::string globalprefix
Definition Util.cpp:22
void Finalize()
Definition Util.cpp:228
std::string filename
Definition Util.cpp:21
void AverageCellcenterToNode(amrex::MultiFab &node_mf, const int &dcomp, const amrex::MultiFab &cell_mf, const int &scomp, const int &ncomp)
Definition Util.cpp:362
bool initialized
Definition Util.cpp:24
AMREX_FORCE_INLINE void Assert(std::string file, std::string func, int line, std::string smt, bool pass, Args const &... args)
Definition Util.H:55
std::pair< std::string, std::string > file_overwrite
Definition Util.cpp:23
void CopyFileToOutputDir(std::string a_path, bool fullpath, std::string prefix)
Definition Util.cpp:54
void Initialize()
Definition Util.cpp:130
std::pair< std::string, std::string > GetOverwrittenFile()
Definition Util.cpp:96
void Exception(std::string file, std::string func, int line, Args const &... args)
Definition Util.H:223
void Terminate(const char *, int signal, bool)
Definition Util.cpp:243
void SignalHandler(int s)
Definition Util.cpp:101
static AMREX_FORCE_INLINE T CellToNodeAverage(const amrex::Array4< const T > &f, const int &i, const int &j, const int &k, const int &m, std::array< StencilType, AMREX_SPACEDIM > stencil=DefaultType)
Definition Stencil.H:1313
static void setTimeUnit(std::string unit)
Definition Unit.H:373
static void setLuminousIntensityUnit(std::string unit)
Definition Unit.H:413
static void setLengthUnit(std::string unit)
Definition Unit.H:365
static void setMassUnit(std::string unit)
Definition Unit.H:381
static void setTemperatureUnit(std::string unit)
Definition Unit.H:389
static void setCurrentUnit(std::string unit)
Definition Unit.H:397
static void setAmountUnit(std::string unit)
Definition Unit.H:405
static Unit Length()
Definition Unit.H:194