/
MooseUtils.h
643 lines (565 loc) · 21.8 KB
/
MooseUtils.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#ifndef MOOSEUTILS_H
#define MOOSEUTILS_H
// MOOSE includes
#include "HashMap.h"
#include "InfixIterator.h"
#include "MooseEnumItem.h"
#include "MooseError.h"
#include "Moose.h"
#include "libmesh/compare_types.h"
// C++ includes
#include <string>
#include <vector>
#include <map>
#include <list>
#include <iterator>
// Forward Declarations
class InputParameters;
class ExecFlagEnum;
class MaterialProperties;
namespace libMesh
{
class Elem;
namespace Parallel
{
class Communicator;
}
}
class MultiMooseEnum;
namespace MetaPhysicL
{
template <typename, typename>
class DualNumber;
}
namespace std
{
template <typename T, typename D>
MetaPhysicL::DualNumber<T, D> abs(const MetaPhysicL::DualNumber<T, D> & in);
template <typename T, typename D>
MetaPhysicL::DualNumber<T, D> abs(MetaPhysicL::DualNumber<T, D> && in);
}
namespace MooseUtils
{
/**
* Replaces "LATEST" placeholders with the latest checkpoint file name. If base_only is true, then
* only return the base-name of the checkpoint directory - otherwise, a full mesh
* checkpoint file path is returned.
*/
std::string convertLatestCheckpoint(std::string orig, bool base_only = true);
/// Computes and returns the Levenshtein distance between strings s1 and s2.
int levenshteinDist(const std::string & s1, const std::string & s2);
/**
* This function will escape all of the standard C++ escape characters so that they can be printed.
* The
* passed in parameter is modified in place
*/
void escape(std::string & str);
/**
* Standard scripting language trim function
*/
std::string trim(const std::string & str, const std::string & white_space = " \t\n\v\f\r");
/**
* Python like split function for strings.
*
* NOTE: This is similar to the tokenize function, but it maintains empty items, which tokenize does
* not. For example, "foo;bar;;" becomes {"foo", "bar", "", ""}.
*/
std::vector<std::string> split(const std::string & str, const std::string & delimiter);
/**
* Python like join function for strings.
*/
template <typename T>
std::string join(const T & strings, const std::string & delimiter);
/**
* Check the file size.
*/
std::size_t fileSize(const std::string & filename);
/**
* This function tokenizes a path and checks to see if it contains the string to look for
*/
bool pathContains(const std::string & expression,
const std::string & string_to_find,
const std::string & delims = "/");
/**
* Checks to see if a file is readable (exists and permissions)
* @param filename The filename to check
* @param check_line_endings Whether or not to see if the file contains DOS line endings.
* @param throw_on_unreadable Whether or not to throw a MOOSE error if the file doesn't exist
* @return a Boolean indicating whether the file exists and is readable
*/
bool checkFileReadable(const std::string & filename,
bool check_line_endings = false,
bool throw_on_unreadable = true);
/**
* Check if the file is writable (path exists and permissions)
* @param filename The filename you want to see if you can write to.
* @param throw_on_unwritable Whether or not to throw a MOOSE error if the file is not writable
* return a Boolean indicating whether the file exists and is writable
*/
bool checkFileWriteable(const std::string & filename, bool throw_on_unwritable = true);
/**
* This function implements a parallel barrier function but writes progress
* to stdout.
*/
void parallelBarrierNotify(const libMesh::Parallel::Communicator & comm, bool messaging = true);
/**
* This function marks the begin of a section of code that is executed in serial
* rank by rank. The section must be closed with a call to serialEnd.
* These functions are intended for debugging use to obtain clean terminal output
* from multiple ranks (use --keep-cout).
* @param comm The communicator to use
* @param warn Whether or not to warn that something is being serialized
*/
void serialBegin(const libMesh::Parallel::Communicator & comm, bool warn = true);
/**
* Closes a section of code that is executed in serial rank by rank, and that was
* opened with a call to serialBegin. No MPI communication can happen in this block.
* @param comm The communicator to use
* @param warn Whether or not to warn that something is being serialized
*/
void serialEnd(const libMesh::Parallel::Communicator & comm, bool warn = true);
/**
* Function tests if the supplied filename as the desired extension
* @param filename The filename to test the extension
* @param ext The extension to test for (do not include the .)
* @param strip_exodus_ext When true, this function ignores -s* from the end of the extension
* @return True if the filename has the supplied extension
*/
bool hasExtension(const std::string & filename, std::string ext, bool strip_exodus_ext = false);
/**
* Removes any file extension from the fiven string s (i.e. any ".[extension]" suffix of s) and
* returns the result.
*/
std::string stripExtension(const std::string & s);
/**
* Function for splitting path and filename
* @param full_file A complete filename and path
* @return A std::pair<std::string, std::string> containing the path and filename
*
* If the supplied filename does not contain a path, it returns "." as the path
*/
std::pair<std::string, std::string> splitFileName(std::string full_file);
/**
* Function for converting a camel case name to a name containing underscores.
* @param camel_case_name A string containing camel casing
* @return a string containing no capital letters with underscores as appropriate
*/
std::string camelCaseToUnderscore(const std::string & camel_case_name);
/**
* Function for converting an underscore name to a camel case name.
* @param underscore_name A string containing underscores
* @return a string containing camel casing
*/
std::string underscoreToCamelCase(const std::string & underscore_name, bool leading_upper_case);
/**
* Function for stripping name after the file / in parser block
*/
std::string shortName(const std::string & name);
/**
* Function for string the information before the final / in a parser block
*/
std::string baseName(const std::string & name);
/**
* Get the hostname the current process is running on
*/
std::string hostname();
/**
* This routine is a simple helper function for searching a map by values instead of keys
*/
template <typename T1, typename T2>
bool
doesMapContainValue(const std::map<T1, T2> & the_map, const T2 & value)
{
for (typename std::map<T1, T2>::const_iterator iter = the_map.begin(); iter != the_map.end();
++iter)
if (iter->second == value)
return true;
return false;
}
/**
* Function to check whether two variables are equal within an absolute tolerance
* @param var1 The first variable to be checked
* @param var2 The second variable to be checked
* @param tol The tolerance to be used
* @return true if var1 and var2 are equal within tol
*/
template <typename T,
typename T2,
typename T3 = T,
typename std::enable_if<ScalarTraits<T>::value && ScalarTraits<T2>::value &&
ScalarTraits<T3>::value,
int>::type = 0>
bool
absoluteFuzzyEqual(const T & var1,
const T2 & var2,
const T3 & tol = libMesh::TOLERANCE * libMesh::TOLERANCE)
{
return (std::abs(var1 - var2) <= tol);
}
/**
* Function to check whether a variable is greater than or equal to another variable within an
* absolute tolerance
* @param var1 The first variable to be checked
* @param var2 The second variable to be checked
* @param tol The tolerance to be used
* @return true if var1 > var2 or var1 == var2 within tol
*/
bool absoluteFuzzyGreaterEqual(const libMesh::Real & var1,
const libMesh::Real & var2,
const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
/**
* Function to check whether a variable is greater than another variable within an absolute
* tolerance
* @param var1 The first variable to be checked
* @param var2 The second variable to be checked
* @param tol The tolerance to be used
* @return true if var1 > var2 and var1 != var2 within tol
*/
bool absoluteFuzzyGreaterThan(const libMesh::Real & var1,
const libMesh::Real & var2,
const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
/**
* Function to check whether a variable is less than or equal to another variable within an absolute
* tolerance
* @param var1 The first variable to be checked
* @param var2 The second variable to be checked
* @param tol The tolerance to be used
* @return true if var1 < var2 or var1 == var2 within tol
*/
bool absoluteFuzzyLessEqual(const libMesh::Real & var1,
const libMesh::Real & var2,
const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
/**
* Function to check whether a variable is less than another variable within an absolute tolerance
* @param var1 The first variable to be checked
* @param var2 The second variable to be checked
* @param tol The tolerance to be used
* @return true if var1 < var2 and var1 != var2 within tol
*/
bool absoluteFuzzyLessThan(const libMesh::Real & var1,
const libMesh::Real & var2,
const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
/**
* Function to check whether two variables are equal within a relative tolerance
* @param var1 The first variable to be checked
* @param var2 The second variable to be checked
* @param tol The relative tolerance to be used
* @return true if var1 and var2 are equal within relative tol
*/
template <typename T,
typename T2,
typename std::enable_if<ScalarTraits<T>::value && ScalarTraits<T2>::value, int>::type = 0>
bool
relativeFuzzyEqual(const T & var1,
const T2 & var2,
const Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE)
{
return (absoluteFuzzyEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
}
/**
* Function to check whether a variable is greater than or equal to another variable within a
* relative tolerance
* @param var1 The first variable to be checked
* @param var2 The second variable to be checked
* @param tol The tolerance to be used
* @return true if var1 > var2 or var1 == var2 within relative tol
*/
bool relativeFuzzyGreaterEqual(const libMesh::Real & var1,
const libMesh::Real & var2,
const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
/**
* Function to check whether a variable is greater than another variable within a relative tolerance
* @param var1 The first variable to be checked
* @param var2 The second variable to be checked
* @param tol The tolerance to be used
* @return true if var1 > var2 and var1 != var2 within relative tol
*/
bool relativeFuzzyGreaterThan(const libMesh::Real & var1,
const libMesh::Real & var2,
const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
/**
* Function to check whether a variable is less than or equal to another variable within a relative
* tolerance
* @param var1 The first variable to be checked
* @param var2 The second variable to be checked
* @param tol The tolerance to be used
* @return true if var1 < var2 or var1 == var2 within relative tol
*/
bool relativeFuzzyLessEqual(const libMesh::Real & var1,
const libMesh::Real & var2,
const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
/**
* Function to check whether a variable is less than another variable within a relative tolerance
* @param var1 The first variable to be checked
* @param var2 The second variable to be checked
* @param tol The tolerance to be used
* @return true if var1 < var2 and var1 != var2 within relative tol
*/
bool relativeFuzzyLessThan(const libMesh::Real & var1,
const libMesh::Real & var2,
const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
/**
* Function to dump the contents of MaterialPropertyStorage for debugging purposes
* @param props The storage item to dump, this should be
* MaterialPropertyStorage.props()/propsOld()/propsOlder().
*
* Currently this only words for scalar material properties. Something to do as needed would be to
* create a method in MaterialProperty
* that may be overloaded to dump the type using template specialization.
*/
void MaterialPropertyStorageDump(
const HashMap<const libMesh::Elem *, HashMap<unsigned int, MaterialProperties>> & props);
/**
* Indents the supplied message given the prefix and color
* @param prefix The prefix to use for indenting
* @param message The message that will be indented
* @param color The color to apply to the prefix (default CYAN)
*
* Takes a message like the following and indents it with another color code (see below)
*
* Input messsage:
* COLOR_YELLOW
* *** Warning ***
* Something bad has happened and we want to draw attention to it with color
* COLOR_DEFAULT
*
* Output message:
* COLOR_CYAN sub_app: COLOR_YELLOW
* COLOR_CYAN sub_app: COLOR_YELLOW *** Warning ***
* COLOR_CYAN sub_app: COLOR_YELLOW Something bad has happened and we want to draw attention to it
* with color
* COLOR_DEFAULT
*
* Also handles single line color codes
* COLOR_CYAN sub_app: 0 Nonline |R| = COLOR_GREEN 1.0e-10 COLOR_DEFAULT
*/
void
indentMessage(const std::string & prefix, std::string & message, const char * color = COLOR_CYAN);
/**
* remove ANSI escape sequences for teminal color from msg
*/
std::string & removeColor(std::string & msg);
std::list<std::string> listDir(const std::string path, bool files_only = false);
bool pathExists(const std::string & path);
/**
* Retrieves the names of all of the files contained within the list of directories passed into the
* routine.
* The names returned will be the paths to the files relative to the current directory.
* @param directory_list The list of directories to retrieve files from.
*/
std::list<std::string> getFilesInDirs(const std::list<std::string> & directory_list);
/**
* Returns the most recent checkpoint or mesh file given a list of files.
* If a suitable file isn't found the empty string is returned
* @param checkpoint_files the list of files to analyze
*/
std::string getLatestMeshCheckpointFile(const std::list<std::string> & checkpoint_files);
std::string getLatestAppCheckpointFileBase(const std::list<std::string> & checkpoint_files);
/*
* Checks to see if a string matches a search string
* @param name The name to check
* @param search_string The search string to check name against
*/
bool wildCardMatch(std::string name, std::string search_string);
/**
* This function will split the passed in string on a set of delimiters appending the substrings
* to the passed in vector. The delimiters default to "/" but may be supplied as well. In addition
* if min_len is supplied, the minimum token length will be greater than the supplied value.
* T should be std::string or a MOOSE derived string class.
*/
template <typename T>
void
tokenize(const std::string & str,
std::vector<T> & elements,
unsigned int min_len = 1,
const std::string & delims = "/")
{
elements.clear();
std::string::size_type last_pos = str.find_first_not_of(delims, 0);
std::string::size_type pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
while (last_pos != std::string::npos)
{
elements.push_back(str.substr(last_pos, pos - last_pos));
// skip delims between tokens
last_pos = str.find_first_not_of(delims, pos);
if (last_pos == std::string::npos)
break;
pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
}
}
/**
* tokenizeAndConvert splits a string using delimiter and then converts to type T.
* If the conversion fails tokenizeAndConvert returns false, otherwise true.
*/
template <typename T>
bool
tokenizeAndConvert(const std::string & str,
std::vector<T> & tokenized_vector,
const std::string & delimiter = " \t\n\v\f\r")
{
std::vector<std::string> tokens;
MooseUtils::tokenize(str, tokens, 1, delimiter);
tokenized_vector.resize(tokens.size());
for (unsigned int j = 0; j < tokens.size(); ++j)
{
std::stringstream ss(trim(tokens[j]));
// we have to make sure that the conversion succeeded _and_ that the string
// was fully read to avoid situations like [conversion to Real] 3.0abc to work
if ((ss >> tokenized_vector[j]).fail() || !ss.eof())
return false;
}
return true;
}
/**
* convert takes a string representation of a number type and converts it to the number.
* This method is here to get around deficiencies in the STL stoi and stod methods where they
* might successfully convert part of a string to a number when we'd like to throw an error.
*/
template <typename T>
T
convert(const std::string & str, bool throw_on_failure = false)
{
std::stringstream ss(str);
T val;
if ((ss >> val).fail() || !ss.eof())
{
std::string msg =
std::string("Unable to convert '") + str + "' to type " + demangle(typeid(T).name());
if (throw_on_failure)
throw std::invalid_argument(msg);
else
mooseError(msg);
}
return val;
}
template <>
short int convert<short int>(const std::string & str, bool throw_on_failure);
template <>
unsigned short int convert<unsigned short int>(const std::string & str, bool throw_on_failure);
template <>
int convert<int>(const std::string & str, bool throw_on_failure);
template <>
unsigned int convert<unsigned int>(const std::string & str, bool throw_on_failure);
template <>
long int convert<long int>(const std::string & str, bool throw_on_failure);
template <>
unsigned long int convert<unsigned long int>(const std::string & str, bool throw_on_failure);
template <>
long long int convert<long long int>(const std::string & str, bool throw_on_failure);
template <>
unsigned long long int convert<unsigned long long int>(const std::string & str,
bool throw_on_failure);
/**
* Create a symbolic link, if the link already exists it is replaced.
*/
void createSymlink(const std::string & target, const std::string & link);
/**
* Remove a symbolic link, if the given filename is a link.
*/
void clearSymlink(const std::string & link);
/**
* Convert supplied string to upper case.
* @params name The string to convert upper case.
*/
std::string toUpper(const std::string & name);
/**
* Convert supplied string to lower case.
* @params name The string to convert upper case.
*/
std::string toLower(const std::string & name);
/**
* Returns a container that contains the content of second passed in container
* inserted into the first passed in container (set or map union).
*/
template <typename T>
T
concatenate(T c1, const T & c2)
{
c1.insert(c2.begin(), c2.end());
return c1;
}
/**
* Returns a vector that contains is the concatenation of the two passed in vectors.
*/
template <typename T>
std::vector<T>
concatenate(std::vector<T> c1, const std::vector<T> & c2)
{
c1.insert(c1.end(), c2.begin(), c2.end());
return c1;
}
/**
* Returns the passed in vector with the item appended to it.
*/
template <typename T>
std::vector<T>
concatenate(std::vector<T> c1, const T & item)
{
c1.push_back(item);
return c1;
}
/**
* Return the number of digits for a number.
*
* This can foster quite a large discussion:
* https://stackoverflow.com/questions/1489830/efficient-way-to-determine-number-of-digits-in-an-integer
*
* For our purposes I like the following algorithm.
*/
template <typename T>
int
numDigits(const T & num)
{
return num > 9 ? static_cast<int>(std::log10(static_cast<double>(num))) + 1 : 1;
}
/**
* Return the default ExecFlagEnum for MOOSE.
*/
ExecFlagEnum getDefaultExecFlagEnum();
/**
* Robust string to integer conversion that fails for cases such at "1foo".
* @param input The string to convert.
* @param throw_on_failure Throw an invalid_argument exception instead of mooseError.
*/
int stringToInteger(const std::string & input, bool throw_on_failure = false);
/**
* Linearly partition a number of items
*
* @param num_items The number of items to partition
* @param num_chunks The number of chunks to partition into
* @param chunk_id The ID of the chunk you are trying to get information about (typically the
* current MPI rank)
* @param num_local_items Output: The number of items for this chunk_id
* @param local_items_begin Output: The first item for this chunk_id
* @param local_items_end Output: One past the final item for this chunk_id
*/
void linearPartitionItems(dof_id_type num_items,
dof_id_type num_chunks,
dof_id_type chunk_id,
dof_id_type & num_local_items,
dof_id_type & local_items_begin,
dof_id_type & local_items_end);
/**
* Return the chunk_id that is assigned to handle item_id
*
* @param num_items Global number of items to partition
* @param num_chunks Total number of chunks to split into
* @param item_id The item to find the chunk_id for
* @return The chunk_id of the chunk that contains item_id
*/
processor_id_type
linearPartitionChunk(dof_id_type num_items, dof_id_type num_chunks, dof_id_type item_id);
} // MooseUtils namespace
/**
* find, erase, length algorithm for removing a substring from a string
*/
void removeSubstring(std::string & main, const std::string & sub);
#endif // MOOSEUTILS_H