www.mooseframework.org
MooseUtils.h
Go to the documentation of this file.
1 //* This file is part of the MOOSE framework
2 //* https://www.mooseframework.org
3 //*
4 //* All rights reserved, see COPYRIGHT for full restrictions
5 //* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6 //*
7 //* Licensed under LGPL 2.1, please see LICENSE for details
8 //* https://www.gnu.org/licenses/lgpl-2.1.html
9 
10 #pragma once
11 
12 // MOOSE includes
13 #include "HashMap.h"
14 #include "InfixIterator.h"
15 #include "MooseEnumItem.h"
16 #include "MooseError.h"
17 #include "Moose.h"
18 
19 #include "libmesh/compare_types.h"
20 
21 // C++ includes
22 #include <string>
23 #include <vector>
24 #include <map>
25 #include <list>
26 #include <iterator>
27 
28 // Forward Declarations
29 class InputParameters;
30 class ExecFlagEnum;
31 class MaterialProperties;
32 
33 namespace libMesh
34 {
35 class Elem;
36 namespace Parallel
37 {
38 class Communicator;
39 }
40 }
41 class MultiMooseEnum;
42 namespace MetaPhysicL
43 {
44 template <typename, typename>
45 class DualNumber;
46 }
47 namespace std
48 {
49 template <typename T, typename D>
51 template <typename T, typename D>
53 }
54 
55 namespace MooseUtils
56 {
57 
63 std::string convertLatestCheckpoint(std::string orig, bool base_only = true);
64 
66 int levenshteinDist(const std::string & s1, const std::string & s2);
67 
73 void escape(std::string & str);
74 
78 std::string trim(const std::string & str, const std::string & white_space = " \t\n\v\f\r");
79 
86 std::vector<std::string> split(const std::string & str, const std::string & delimiter);
87 
91 template <typename T>
92 std::string join(const T & strings, const std::string & delimiter);
93 
97 std::size_t fileSize(const std::string & filename);
98 
102 bool pathContains(const std::string & expression,
103  const std::string & string_to_find,
104  const std::string & delims = "/");
105 
113 bool checkFileReadable(const std::string & filename,
114  bool check_line_endings = false,
115  bool throw_on_unreadable = true);
116 
123 bool checkFileWriteable(const std::string & filename, bool throw_on_unwritable = true);
124 
129 void parallelBarrierNotify(const libMesh::Parallel::Communicator & comm, bool messaging = true);
130 
139 void serialBegin(const libMesh::Parallel::Communicator & comm, bool warn = true);
140 
147 void serialEnd(const libMesh::Parallel::Communicator & comm, bool warn = true);
148 
156 bool hasExtension(const std::string & filename, std::string ext, bool strip_exodus_ext = false);
157 
162 std::string stripExtension(const std::string & s);
163 
171 std::pair<std::string, std::string> splitFileName(std::string full_file);
172 
178 std::string camelCaseToUnderscore(const std::string & camel_case_name);
179 
185 std::string underscoreToCamelCase(const std::string & underscore_name, bool leading_upper_case);
186 
190 std::string shortName(const std::string & name);
191 
195 std::string baseName(const std::string & name);
196 
200 std::string hostname();
201 
205 template <typename T1, typename T2>
206 bool
207 doesMapContainValue(const std::map<T1, T2> & the_map, const T2 & value)
208 {
209  for (typename std::map<T1, T2>::const_iterator iter = the_map.begin(); iter != the_map.end();
210  ++iter)
211  if (iter->second == value)
212  return true;
213  return false;
214 }
215 
223 template <typename T,
224  typename T2,
225  typename T3 = T,
226  typename std::enable_if<ScalarTraits<T>::value && ScalarTraits<T2>::value &&
227  ScalarTraits<T3>::value,
228  int>::type = 0>
229 bool
230 absoluteFuzzyEqual(const T & var1,
231  const T2 & var2,
232  const T3 & tol = libMesh::TOLERANCE * libMesh::TOLERANCE)
233 {
234  return (std::abs(var1 - var2) <= tol);
235 }
236 
245 bool absoluteFuzzyGreaterEqual(const libMesh::Real & var1,
246  const libMesh::Real & var2,
247  const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
248 
257 bool absoluteFuzzyGreaterThan(const libMesh::Real & var1,
258  const libMesh::Real & var2,
259  const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
260 
269 bool absoluteFuzzyLessEqual(const libMesh::Real & var1,
270  const libMesh::Real & var2,
271  const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
272 
280 bool absoluteFuzzyLessThan(const libMesh::Real & var1,
281  const libMesh::Real & var2,
282  const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
283 
291 template <typename T,
292  typename T2,
293  typename std::enable_if<ScalarTraits<T>::value && ScalarTraits<T2>::value, int>::type = 0>
294 bool
295 relativeFuzzyEqual(const T & var1,
296  const T2 & var2,
297  const Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE)
298 {
299  return (absoluteFuzzyEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
300 }
301 
310 bool relativeFuzzyGreaterEqual(const libMesh::Real & var1,
311  const libMesh::Real & var2,
312  const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
313 
321 bool relativeFuzzyGreaterThan(const libMesh::Real & var1,
322  const libMesh::Real & var2,
323  const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
324 
333 bool relativeFuzzyLessEqual(const libMesh::Real & var1,
334  const libMesh::Real & var2,
335  const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
336 
344 bool relativeFuzzyLessThan(const libMesh::Real & var1,
345  const libMesh::Real & var2,
346  const libMesh::Real & tol = libMesh::TOLERANCE * libMesh::TOLERANCE);
347 
358  const HashMap<const libMesh::Elem *, HashMap<unsigned int, MaterialProperties>> & props);
359 
384 void
385 indentMessage(const std::string & prefix, std::string & message, const char * color = COLOR_CYAN);
386 
390 std::string & removeColor(std::string & msg);
391 
392 std::list<std::string> listDir(const std::string path, bool files_only = false);
393 
394 bool pathExists(const std::string & path);
395 
402 std::list<std::string> getFilesInDirs(const std::list<std::string> & directory_list);
403 
409 std::string getLatestMeshCheckpointFile(const std::list<std::string> & checkpoint_files);
410 
411 std::string getLatestAppCheckpointFileBase(const std::list<std::string> & checkpoint_files);
412 
413 /*
414  * Checks to see if a string matches a search string
415  * @param name The name to check
416  * @param search_string The search string to check name against
417  */
418 bool wildCardMatch(std::string name, std::string search_string);
419 
426 template <typename T>
427 void
428 tokenize(const std::string & str,
429  std::vector<T> & elements,
430  unsigned int min_len = 1,
431  const std::string & delims = "/")
432 {
433  elements.clear();
434 
435  std::string::size_type last_pos = str.find_first_not_of(delims, 0);
436  std::string::size_type pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
437 
438  while (last_pos != std::string::npos)
439  {
440  elements.push_back(str.substr(last_pos, pos - last_pos));
441  // skip delims between tokens
442  last_pos = str.find_first_not_of(delims, pos);
443  if (last_pos == std::string::npos)
444  break;
445  pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
446  }
447 }
448 
453 template <typename T>
454 bool
455 tokenizeAndConvert(const std::string & str,
456  std::vector<T> & tokenized_vector,
457  const std::string & delimiter = " \t\n\v\f\r")
458 {
459  std::vector<std::string> tokens;
460  MooseUtils::tokenize(str, tokens, 1, delimiter);
461  tokenized_vector.resize(tokens.size());
462  for (unsigned int j = 0; j < tokens.size(); ++j)
463  {
464  std::stringstream ss(trim(tokens[j]));
465  // we have to make sure that the conversion succeeded _and_ that the string
466  // was fully read to avoid situations like [conversion to Real] 3.0abc to work
467  if ((ss >> tokenized_vector[j]).fail() || !ss.eof())
468  return false;
469  }
470  return true;
471 }
472 
478 template <typename T>
479 T
480 convert(const std::string & str, bool throw_on_failure = false)
481 {
482  std::stringstream ss(str);
483  T val;
484  if ((ss >> val).fail() || !ss.eof())
485  {
486  std::string msg =
487  std::string("Unable to convert '") + str + "' to type " + demangle(typeid(T).name());
488 
489  if (throw_on_failure)
490  throw std::invalid_argument(msg);
491  else
492  mooseError(msg);
493  }
494 
495  return val;
496 }
497 
498 template <>
499 short int convert<short int>(const std::string & str, bool throw_on_failure);
500 
501 template <>
502 unsigned short int convert<unsigned short int>(const std::string & str, bool throw_on_failure);
503 
504 template <>
505 int convert<int>(const std::string & str, bool throw_on_failure);
506 
507 template <>
508 unsigned int convert<unsigned int>(const std::string & str, bool throw_on_failure);
509 
510 template <>
511 long int convert<long int>(const std::string & str, bool throw_on_failure);
512 
513 template <>
514 unsigned long int convert<unsigned long int>(const std::string & str, bool throw_on_failure);
515 
516 template <>
517 long long int convert<long long int>(const std::string & str, bool throw_on_failure);
518 
519 template <>
520 unsigned long long int convert<unsigned long long int>(const std::string & str,
521  bool throw_on_failure);
522 
526 void createSymlink(const std::string & target, const std::string & link);
527 
531 void clearSymlink(const std::string & link);
532 
537 std::string toUpper(const std::string & name);
538 
543 std::string toLower(const std::string & name);
544 
549 template <typename T>
550 T
551 concatenate(T c1, const T & c2)
552 {
553  c1.insert(c2.begin(), c2.end());
554  return c1;
555 }
556 
560 template <typename T>
561 std::vector<T>
562 concatenate(std::vector<T> c1, const std::vector<T> & c2)
563 {
564  c1.insert(c1.end(), c2.begin(), c2.end());
565  return c1;
566 }
567 
571 template <typename T>
572 std::vector<T>
573 concatenate(std::vector<T> c1, const T & item)
574 {
575  c1.push_back(item);
576  return c1;
577 }
578 
587 template <typename T>
588 int
589 numDigits(const T & num)
590 {
591  return num > 9 ? static_cast<int>(std::log10(static_cast<double>(num))) + 1 : 1;
592 }
593 
598 
604 int stringToInteger(const std::string & input, bool throw_on_failure = false);
605 
617 void linearPartitionItems(dof_id_type num_items,
618  dof_id_type num_chunks,
619  dof_id_type chunk_id,
620  dof_id_type & num_local_items,
621  dof_id_type & local_items_begin,
622  dof_id_type & local_items_end);
623 
632 processor_id_type
633 linearPartitionChunk(dof_id_type num_items, dof_id_type num_chunks, dof_id_type item_id);
634 
635 } // MooseUtils namespace
636 
640 void removeSubstring(std::string & main, const std::string & sub);
641 
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 or equal to another variable within an absolute ...
T convert(const std::string &str, bool throw_on_failure=false)
convert takes a string representation of a number type and converts it to the number.
Definition: MooseUtils.h:480
A MultiMooseEnum object to hold "execute_on" flags.
Definition: ExecFlagEnum.h:24
MetaPhysicL::DualNumber< T, D > abs(const MetaPhysicL::DualNumber< T, D > &in)
void serialEnd(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 ...
Definition: MooseUtils.C:240
std::string toLower(const std::string &name)
Convert supplied string to lower case.
Definition: MooseUtils.C:707
void tokenize(const std::string &str, std::vector< T > &elements, unsigned int min_len=1, const std::string &delims="/")
This function will split the passed in string on a set of delimiters appending the substrings to the ...
Definition: MooseUtils.h:428
bool absoluteFuzzyEqual(const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
Function to check whether two variables are equal within an absolute tolerance.
Definition: MooseUtils.h:230
HashMap is an abstraction for dictionary data type, we make it thread-safe by locking inserts...
Definition: HashMap.h:18
int stringToInteger(const std::string &input, bool throw_on_failure=false)
Robust string to integer conversion that fails for cases such at "1foo".
Definition: MooseUtils.C:730
std::string toUpper(const std::string &name)
Convert supplied string to upper case.
Definition: MooseUtils.C:699
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:207
void MaterialPropertyStorageDump(const HashMap< const libMesh::Elem *, HashMap< unsigned int, MaterialProperties >> &props)
Function to dump the contents of MaterialPropertyStorage for debugging purposes.
Definition: MooseUtils.C:438
Container for storing material properties.
bool tokenizeAndConvert(const std::string &str, std::vector< T > &tokenized_vector, const std::string &delimiter=" \\\)
tokenizeAndConvert splits a string using delimiter and then converts to type T.
Definition: MooseUtils.h:455
bool doesMapContainValue(const std::map< T1, T2 > &the_map, const T2 &value)
This routine is a simple helper function for searching a map by values instead of keys...
Definition: MooseUtils.h:207
void indentMessage(const std::string &prefix, std::string &message, const char *color=COLOR_CYAN)
Indents the supplied message given the prefix and color.
Definition: MooseUtils.C:479
std::list< std::string > getFilesInDirs(const std::list< std::string > &directory_list)
Retrieves the names of all of the files contained within the list of directories passed into the rout...
Definition: MooseUtils.C:533
The main MOOSE class responsible for handling user-defined parameters in almost every MOOSE system...
std::string stripExtension(const std::string &s)
Removes any file extension from the fiven string s (i.e.
Definition: MooseUtils.C:280
bool absoluteFuzzyLessThan(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...
bool relativeFuzzyLessThan(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...
The following methods are specializations for using the libMesh::Parallel::packed_range_* routines fo...
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)
Linearly partition a number of items.
Definition: MooseUtils.C:737
std::string convertLatestCheckpoint(std::string orig, bool base_only=true)
Replaces "LATEST" placeholders with the latest checkpoint file name.
Definition: MooseUtils.C:45
T concatenate(T c1, const T &c2)
Returns a container that contains the content of second passed in container inserted into the first p...
Definition: MooseUtils.h:551
std::string hostname()
Get the hostname the current process is running on.
Definition: MooseUtils.C:375
std::string camelCaseToUnderscore(const std::string &camel_case_name)
Function for converting a camel case name to a name containing underscores.
Definition: MooseUtils.C:319
std::string shortName(const std::string &name)
Function for stripping name after the file / in parser block.
Definition: MooseUtils.C:363
std::string getLatestAppCheckpointFileBase(const std::list< std::string > &checkpoint_files)
Definition: MooseUtils.C:552
ExecFlagEnum getDefaultExecFlagEnum()
Return the default ExecFlagEnum for MOOSE.
Definition: MooseUtils.C:715
std::vector< std::string > split(const std::string &str, const std::string &delimiter)
Python like split function for strings.
Definition: MooseUtils.C:784
bool checkFileReadable(const std::string &filename, bool check_line_endings=false, bool throw_on_unreadable=true)
Checks to see if a file is readable (exists and permissions)
Definition: MooseUtils.C:146
std::pair< std::string, std::string > splitFileName(std::string full_file)
Function for splitting path and filename.
Definition: MooseUtils.C:289
int convert< int >(const std::string &str, bool throw_on_failure)
Definition: MooseUtils.C:658
void parallelBarrierNotify(const libMesh::Parallel::Communicator &comm, bool messaging=true)
This function implements a parallel barrier function but writes progress to stdout.
void serialBegin(const libMesh::Parallel::Communicator &comm, bool warn=true)
This function marks the begin of a section of code that is executed in serial rank by rank...
Definition: MooseUtils.C:226
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 or equal to another variable within a relative tole...
std::string trim(const std::string &str, const std::string &white_space=" \\\)
Standard scripting language trim function.
Definition: MooseUtils.C:113
std::size_t fileSize(const std::string &filename)
Check the file size.
Definition: MooseUtils.C:837
unsigned int convert< unsigned int >(const std::string &str, bool throw_on_failure)
Definition: MooseUtils.C:665
std::string underscoreToCamelCase(const std::string &underscore_name, bool leading_upper_case)
Function for converting an underscore name to a camel case name.
Definition: MooseUtils.C:331
bool hasExtension(const std::string &filename, std::string ext, bool strip_exodus_ext=false)
Function tests if the supplied filename as the desired extension.
Definition: MooseUtils.C:256
std::string & removeColor(std::string &msg)
remove ANSI escape sequences for teminal color from msg
Definition: MooseUtils.C:471
std::string getLatestMeshCheckpointFile(const std::list< std::string > &checkpoint_files)
Returns the most recent checkpoint or mesh file given a list of files.
Definition: MooseUtils.C:544
bool checkFileWriteable(const std::string &filename, bool throw_on_unwritable=true)
Check if the file is writable (path exists and permissions)
Definition: MooseUtils.C:176
void clearSymlink(const std::string &link)
Remove a symbolic link, if the given filename is a link.
Definition: MooseUtils.C:825
long long int convert< long long int >(const std::string &str, bool throw_on_failure)
Definition: MooseUtils.C:686
processor_id_type linearPartitionChunk(dof_id_type num_items, dof_id_type num_chunks, dof_id_type item_id)
Return the chunk_id that is assigned to handle item_id.
Definition: MooseUtils.C:763
void createSymlink(const std::string &target, const std::string &link)
Create a symbolic link, if the link already exists it is replaced.
Definition: MooseUtils.C:816
short int convert< short int >(const std::string &str, bool throw_on_failure)
Definition: MooseUtils.C:644
void removeSubstring(std::string &main, const std::string &sub)
find, erase, length algorithm for removing a substring from a string
Definition: MooseUtils.C:915
bool relativeFuzzyEqual(const T &var1, const T2 &var2, const Real &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
Function to check whether two variables are equal within a relative tolerance.
Definition: MooseUtils.h:295
MatType type
unsigned long int convert< unsigned long int >(const std::string &str, bool throw_on_failure)
Definition: MooseUtils.C:679
std::string baseName(const std::string &name)
Function for string the information before the final / in a parser block.
Definition: MooseUtils.C:369
int numDigits(const T &num)
Return the number of digits for a number.
Definition: MooseUtils.h:589
bool wildCardMatch(std::string name, std::string search_string)
Definition: MooseUtils.C:560
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 greater than another variable within an absolute tolerance...
MPI_Comm comm
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:507
int levenshteinDist(const std::string &s1, const std::string &s2)
Computes and returns the Levenshtein distance between strings s1 and s2.
Definition: MooseUtils.C:64
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 or equal to another variable within a relative t...
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 or equal to another variable within an absolute tol...
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
long int convert< long int >(const std::string &str, bool throw_on_failure)
Definition: MooseUtils.C:672
unsigned short int convert< unsigned short int >(const std::string &str, bool throw_on_failure)
Definition: MooseUtils.C:651
bool pathContains(const std::string &expression, const std::string &string_to_find, const std::string &delims="/")
This function tokenizes a path and checks to see if it contains the string to look for...
Definition: MooseUtils.C:123
bool pathExists(const std::string &path)
Definition: MooseUtils.C:139
unsigned long long int convert< unsigned long long int >(const std::string &str, bool throw_on_failure)
Definition: MooseUtils.C:693
std::string join(const T &strings, const std::string &delimiter)
Python like join function for strings.
Definition: MooseUtils.C:799
void escape(std::string &str)
This function will escape all of the standard C++ escape characters so that they can be printed...
Definition: MooseUtils.C:95
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 greater than another variable within a relative tolerance...