www.mooseframework.org
Classes | Functions
MooseUtils Namespace Reference

Classes

class  DelimitedFileReader
 Utility class for reading delimited data (e.g., CSV data). More...
 
class  SharedPool
 Originally From https://stackoverflow.com/a/27837534/2042320. More...
 

Functions

std::string convertLatestCheckpoint (std::string orig, bool base_only=true)
 Replaces "LATEST" placeholders with the latest checkpoint file name. More...
 
int levenshteinDist (const std::string &s1, const std::string &s2)
 Computes and returns the Levenshtein distance between strings s1 and s2. More...
 
void escape (std::string &str)
 This function will escape all of the standard C++ escape characters so that they can be printed. More...
 
std::string trim (const std::string &str, const std::string &white_space=" \\\)
 Standard scripting language trim function. More...
 
std::vector< std::string > split (const std::string &str, const std::string &delimiter)
 Python like split function for strings. More...
 
template<typename T >
std::string join (const T &strings, const std::string &delimiter)
 Python like join function for strings. More...
 
std::size_t fileSize (const std::string &filename)
 Check the file size. More...
 
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. More...
 
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) More...
 
bool checkFileWriteable (const std::string &filename, bool throw_on_unwritable=true)
 Check if the file is writable (path exists and permissions) More...
 
void parallelBarrierNotify (const libMesh::Parallel::Communicator &comm, bool messaging=true)
 This function implements a parallel barrier function but writes progress to stdout. More...
 
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. More...
 
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 serialBegin. More...
 
bool hasExtension (const std::string &filename, std::string ext, bool strip_exodus_ext=false)
 Function tests if the supplied filename as the desired extension. More...
 
std::string stripExtension (const std::string &s)
 Removes any file extension from the fiven string s (i.e. More...
 
std::pair< std::string, std::string > splitFileName (std::string full_file)
 Function for splitting path and filename. More...
 
std::string camelCaseToUnderscore (const std::string &camel_case_name)
 Function for converting a camel case name to a name containing underscores. More...
 
std::string underscoreToCamelCase (const std::string &underscore_name, bool leading_upper_case)
 Function for converting an underscore name to a camel case name. More...
 
std::string shortName (const std::string &name)
 Function for stripping name after the file / in parser block. More...
 
std::string baseName (const std::string &name)
 Function for string the information before the final / in a parser block. More...
 
std::string hostname ()
 Get the hostname the current process is running on. More...
 
template<typename T1 , typename T2 >
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. More...
 
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)
 Function to check whether two variables are equal within an absolute tolerance. More...
 
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 tolerance. More...
 
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. More...
 
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 tolerance. More...
 
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. More...
 
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)
 Function to check whether two variables are equal within a relative tolerance. More...
 
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 tolerance. More...
 
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. More...
 
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 tolerance. More...
 
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. More...
 
void MaterialPropertyStorageDump (const HashMap< const libMesh::Elem *, HashMap< unsigned int, MaterialProperties >> &props)
 Function to dump the contents of MaterialPropertyStorage for debugging purposes. More...
 
void indentMessage (const std::string &prefix, std::string &message, const char *color=COLOR_CYAN)
 Indents the supplied message given the prefix and color. More...
 
std::string & removeColor (std::string &msg)
 remove ANSI escape sequences for teminal color from msg More...
 
std::list< std::string > listDir (const std::string path, bool files_only=false)
 
bool pathExists (const std::string &path)
 
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 routine. More...
 
std::string getLatestMeshCheckpointFile (const std::list< std::string > &checkpoint_files)
 Returns the most recent checkpoint or mesh file given a list of files. More...
 
std::string getLatestAppCheckpointFileBase (const std::list< std::string > &checkpoint_files)
 
bool wildCardMatch (std::string name, std::string search_string)
 
template<typename T >
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 passed in vector. More...
 
template<typename T >
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. More...
 
template<typename 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. More...
 
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)
 
void createSymlink (const std::string &target, const std::string &link)
 Create a symbolic link, if the link already exists it is replaced. More...
 
void clearSymlink (const std::string &link)
 Remove a symbolic link, if the given filename is a link. More...
 
std::string toUpper (const std::string &name)
 Convert supplied string to upper case. More...
 
std::string toLower (const std::string &name)
 Convert supplied string to lower case. More...
 
template<typename T >
concatenate (T c1, const T &c2)
 Returns a container that contains the content of second passed in container inserted into the first passed in container (set or map union). More...
 
template<typename T >
std::vector< T > concatenate (std::vector< T > c1, const std::vector< T > &c2)
 Returns a vector that contains is the concatenation of the two passed in vectors. More...
 
template<typename T >
std::vector< T > concatenate (std::vector< T > c1, const T &item)
 Returns the passed in vector with the item appended to it. More...
 
template<typename T >
int numDigits (const T &num)
 Return the number of digits for a number. More...
 
ExecFlagEnum getDefaultExecFlagEnum ()
 Return the default ExecFlagEnum for MOOSE. More...
 
int stringToInteger (const std::string &input, bool throw_on_failure=false)
 Robust string to integer conversion that fails for cases such at "1foo". More...
 
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. More...
 
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. More...
 
template<class T , typename... Args>
auto reset (int, T &obj, Args... args) -> decltype(obj.reset(args...), void())
 
template<class T , typename... Args>
void reset (double, T &, Args...)
 
void parallelBarrierNotify (const Parallel::Communicator &comm, bool messaging)
 
bool absoluteFuzzyGreaterEqual (const Real &var1, const Real &var2, const Real &tol)
 
bool absoluteFuzzyGreaterThan (const Real &var1, const Real &var2, const Real &tol)
 
bool absoluteFuzzyLessEqual (const Real &var1, const Real &var2, const Real &tol)
 
bool absoluteFuzzyLessThan (const Real &var1, const Real &var2, const Real &tol)
 
bool relativeFuzzyGreaterEqual (const Real &var1, const Real &var2, const Real &tol)
 
bool relativeFuzzyGreaterThan (const Real &var1, const Real &var2, const Real &tol)
 
bool relativeFuzzyLessEqual (const Real &var1, const Real &var2, const Real &tol)
 
bool relativeFuzzyLessThan (const Real &var1, const Real &var2, const Real &tol)
 
template<typename T >
convertStringToInt (const std::string &str, bool throw_on_failure)
 
template std::string join< std::vector< std::string > > (const std::vector< std::string > &, const std::string &)
 
template std::string join< std::set< std::string > > (const std::set< std::string > &, const std::string &)
 
template std::string join< std::vector< MooseEnumItem > > (const std::vector< MooseEnumItem > &, const std::string &)
 
template std::string join< std::set< MooseEnumItem > > (const std::set< MooseEnumItem > &, const std::string &)
 

Function Documentation

◆ absoluteFuzzyEqual()

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 MooseUtils::absoluteFuzzyEqual ( const T &  var1,
const T2 &  var2,
const T3 &  tol = libMesh::TOLERANCE * libMesh::TOLERANCE 
)

◆ absoluteFuzzyGreaterEqual() [1/2]

bool MooseUtils::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 tolerance.

Parameters
var1The first variable to be checked
var2The second variable to be checked
tolThe tolerance to be used
Returns
true if var1 > var2 or var1 == var2 within tol

Referenced by ComparisonPostprocessor::comparisonIsTrue(), TimePeriod::execute(), and relativeFuzzyGreaterEqual().

◆ absoluteFuzzyGreaterEqual() [2/2]

bool MooseUtils::absoluteFuzzyGreaterEqual ( const Real &  var1,
const Real &  var2,
const Real &  tol 
)

Definition at line 388 of file MooseUtils.C.

389 {
390  return (var1 >= (var2 - tol));
391 }

◆ absoluteFuzzyGreaterThan() [1/2]

bool MooseUtils::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.

Parameters
var1The first variable to be checked
var2The second variable to be checked
tolThe tolerance to be used
Returns
true if var1 > var2 and var1 != var2 within tol

Referenced by ComparisonPostprocessor::comparisonIsTrue(), relativeFuzzyGreaterThan(), and Axisymmetric2D3DSolutionFunction::value().

◆ absoluteFuzzyGreaterThan() [2/2]

bool MooseUtils::absoluteFuzzyGreaterThan ( const Real &  var1,
const Real &  var2,
const Real &  tol 
)

Definition at line 394 of file MooseUtils.C.

395 {
396  return (var1 > (var2 + tol));
397 }

◆ absoluteFuzzyLessEqual() [1/2]

bool MooseUtils::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 tolerance.

Parameters
var1The first variable to be checked
var2The second variable to be checked
tolThe tolerance to be used
Returns
true if var1 < var2 or var1 == var2 within tol

Referenced by ComparisonPostprocessor::comparisonIsTrue(), and relativeFuzzyLessEqual().

◆ absoluteFuzzyLessEqual() [2/2]

bool MooseUtils::absoluteFuzzyLessEqual ( const Real &  var1,
const Real &  var2,
const Real &  tol 
)

Definition at line 400 of file MooseUtils.C.

401 {
402  return (var1 <= (var2 + tol));
403 }

◆ absoluteFuzzyLessThan() [1/2]

bool MooseUtils::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.

Parameters
var1The first variable to be checked
var2The second variable to be checked
tolThe tolerance to be used
Returns
true if var1 < var2 and var1 != var2 within tol

Referenced by FormattedTable::addData(), ComparisonPostprocessor::comparisonIsTrue(), TimePeriod::execute(), and relativeFuzzyLessThan().

◆ absoluteFuzzyLessThan() [2/2]

bool MooseUtils::absoluteFuzzyLessThan ( const Real &  var1,
const Real &  var2,
const Real &  tol 
)

Definition at line 406 of file MooseUtils.C.

407 {
408  return (var1 < (var2 - tol));
409 }

◆ baseName()

std::string MooseUtils::baseName ( const std::string &  name)

Function for string the information before the final / in a parser block.

Definition at line 367 of file MooseUtils.C.

Referenced by Action::getBaseName(), and Parser::walkRaw().

368 {
369  return name.substr(0, name.find_last_of('/') != std::string::npos ? name.find_last_of('/') : 0);
370 }

◆ camelCaseToUnderscore()

std::string MooseUtils::camelCaseToUnderscore ( const std::string &  camel_case_name)

Function for converting a camel case name to a name containing underscores.

Parameters
camel_case_nameA string containing camel casing
Returns
a string containing no capital letters with underscores as appropriate

Definition at line 317 of file MooseUtils.C.

Referenced by MooseApp::appNameToLibName().

318 {
319  string replaced = camel_case_name;
320  // Put underscores in front of each contiguous set of capital letters
321  pcrecpp::RE("(?!^)(?<![A-Z_])([A-Z]+)").GlobalReplace("_\\1", &replaced);
322 
323  // Convert all capital letters to lower case
324  std::transform(replaced.begin(), replaced.end(), replaced.begin(), ::tolower);
325  return replaced;
326 }

◆ checkFileReadable()

bool MooseUtils::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)

Parameters
filenameThe filename to check
check_line_endingsWhether or not to see if the file contains DOS line endings.
throw_on_unreadableWhether or not to throw a MOOSE error if the file doesn't exist
Returns
a Boolean indicating whether the file exists and is readable

Definition at line 146 of file MooseUtils.C.

Referenced by FileMesh::buildMesh(), MooseApp::dynamicRegistration(), ExodusTimeSequenceStepper::ExodusTimeSequenceStepper(), NearestPointBase< LayeredAverage >::fillPoints(), MultiApp::fillPositions(), Exodus::output(), Parser::parse(), MooseUtils::DelimitedFileReader::read(), RestartableDataIO::readRestartableDataHeader(), SolutionUserObject::readXda(), and Resurrector::restartFromFile().

147 {
148  std::ifstream in(filename.c_str(), std::ifstream::in);
149  if (in.fail())
150  {
151  if (throw_on_unreadable)
152  mooseError(
153  (std::string("Unable to open file \"") + filename +
154  std::string("\". Check to make sure that it exists and that you have read permission."))
155  .c_str());
156  else
157  return false;
158  }
159 
160  if (check_line_endings)
161  {
162  std::istream_iterator<char> iter(in);
163  std::istream_iterator<char> eos;
164  in >> std::noskipws;
165  while (iter != eos)
166  if (*iter++ == '\r')
167  mooseError(filename + " contains Windows(DOS) line endings which are not supported.");
168  }
169 
170  in.close();
171 
172  return true;
173 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:208

◆ checkFileWriteable()

bool MooseUtils::checkFileWriteable ( const std::string &  filename,
bool  throw_on_unwritable = true 
)

Check if the file is writable (path exists and permissions)

Parameters
filenameThe filename you want to see if you can write to.
throw_on_unwritableWhether or not to throw a MOOSE error if the file is not writable return a Boolean indicating whether the file exists and is writable

Definition at line 176 of file MooseUtils.C.

177 {
178  std::ofstream out(filename.c_str(), std::ofstream::out);
179  if (out.fail())
180  {
181  if (throw_on_unwritable)
182  mooseError(
183  (std::string("Unable to open file \"") + filename +
184  std::string("\". Check to make sure that it exists and that you have write permission."))
185  .c_str());
186  else
187  return false;
188  }
189 
190  out.close();
191 
192  return true;
193 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:208

◆ clearSymlink()

void MooseUtils::clearSymlink ( const std::string &  link)

Remove a symbolic link, if the given filename is a link.

Definition at line 823 of file MooseUtils.C.

Referenced by createSymlink(), and CSV::initialSetup().

824 {
825  struct stat sbuf;
826  if (lstat(link.c_str(), &sbuf) == 0)
827  {
828  int err = unlink(link.c_str());
829  if (err != 0)
830  mooseError("Failed to remove symbolic link (via 'unlink') to ", link);
831  }
832 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:208

◆ concatenate() [1/3]

template<typename T >
T MooseUtils::concatenate ( c1,
const T &  c2 
)

Returns a container that contains the content of second passed in container inserted into the first passed in container (set or map union).

Definition at line 552 of file MooseUtils.h.

Referenced by MaterialDerivativeTestKernelBase< Real >::MaterialDerivativeTestKernelBase().

553 {
554  c1.insert(c2.begin(), c2.end());
555  return c1;
556 }

◆ concatenate() [2/3]

template<typename T >
std::vector<T> MooseUtils::concatenate ( std::vector< T >  c1,
const std::vector< T > &  c2 
)

Returns a vector that contains is the concatenation of the two passed in vectors.

Definition at line 563 of file MooseUtils.h.

564 {
565  c1.insert(c1.end(), c2.begin(), c2.end());
566  return c1;
567 }

◆ concatenate() [3/3]

template<typename T >
std::vector<T> MooseUtils::concatenate ( std::vector< T >  c1,
const T &  item 
)

Returns the passed in vector with the item appended to it.

Definition at line 574 of file MooseUtils.h.

575 {
576  c1.push_back(item);
577  return c1;
578 }

◆ convert()

template<typename T >
T MooseUtils::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.

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.

Definition at line 481 of file MooseUtils.h.

482 {
483  std::stringstream ss(str);
484  T val;
485  if ((ss >> val).fail() || !ss.eof())
486  {
487  std::string msg =
488  std::string("Unable to convert '") + str + "' to type " + demangle(typeid(T).name());
489 
490  if (throw_on_failure)
491  throw std::invalid_argument(msg);
492  else
493  mooseError(msg);
494  }
495 
496  return val;
497 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:208

◆ convert< int >()

template<>
int MooseUtils::convert< int > ( const std::string &  str,
bool  throw_on_failure 
)

Definition at line 656 of file MooseUtils.C.

Referenced by SystemBase::copyVars(), and stringToInteger().

657 {
658  return convertStringToInt<int>(str, throw_on_failure);
659 }

◆ convert< long int >()

template<>
long int MooseUtils::convert< long int > ( const std::string &  str,
bool  throw_on_failure 
)

Definition at line 670 of file MooseUtils.C.

671 {
672  return convertStringToInt<long int>(str, throw_on_failure);
673 }

◆ convert< long long int >()

template<>
long long int MooseUtils::convert< long long int > ( const std::string &  str,
bool  throw_on_failure 
)

Definition at line 684 of file MooseUtils.C.

685 {
686  return convertStringToInt<long long int>(str, throw_on_failure);
687 }

◆ convert< short int >()

template<>
short int MooseUtils::convert< short int > ( const std::string &  str,
bool  throw_on_failure 
)

Definition at line 642 of file MooseUtils.C.

643 {
644  return convertStringToInt<short int>(str, throw_on_failure);
645 }

◆ convert< unsigned int >()

template<>
unsigned int MooseUtils::convert< unsigned int > ( const std::string &  str,
bool  throw_on_failure 
)

Definition at line 663 of file MooseUtils.C.

664 {
665  return convertStringToInt<unsigned int>(str, throw_on_failure);
666 }

◆ convert< unsigned long int >()

template<>
unsigned long int MooseUtils::convert< unsigned long int > ( const std::string &  str,
bool  throw_on_failure 
)

Definition at line 677 of file MooseUtils.C.

678 {
679  return convertStringToInt<unsigned long int>(str, throw_on_failure);
680 }

◆ convert< unsigned long long int >()

template<>
unsigned long long int MooseUtils::convert< unsigned long long int > ( const std::string &  str,
bool  throw_on_failure 
)

Definition at line 691 of file MooseUtils.C.

692 {
693  return convertStringToInt<unsigned long long int>(str, throw_on_failure);
694 }

◆ convert< unsigned short int >()

template<>
unsigned short int MooseUtils::convert< unsigned short int > ( const std::string &  str,
bool  throw_on_failure 
)

Definition at line 649 of file MooseUtils.C.

650 {
651  return convertStringToInt<unsigned short int>(str, throw_on_failure);
652 }

◆ convertLatestCheckpoint()

std::string MooseUtils::convertLatestCheckpoint ( std::string  orig,
bool  base_only = true 
)

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.

Definition at line 45 of file MooseUtils.C.

Referenced by SetupRecoverFileBaseAction::act(), FileMesh::buildMesh(), and FEProblemBase::FEProblemBase().

46 {
47  auto slash_pos = orig.find_last_of("/");
48  auto path = orig.substr(0, slash_pos);
49  auto file = orig.substr(slash_pos + 1);
50  if (file != "LATEST")
51  return orig;
52 
54  if (!base_only)
56  else if (converted.empty())
57  mooseError("Unable to find suitable recovery file!");
58  return converted;
59 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:208
std::string getLatestAppCheckpointFileBase(const std::list< std::string > &checkpoint_files)
Definition: MooseUtils.C:550
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:542
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:505

◆ convertStringToInt()

template<typename T >
T MooseUtils::convertStringToInt ( const std::string &  str,
bool  throw_on_failure 
)

Definition at line 603 of file MooseUtils.C.

604 {
605  T val;
606 
607  // Let's try to read a double and see if we can cast it to an int
608  // This would be the case for scientific notation
609  long double double_val;
610  std::stringstream double_ss(str);
611 
612  if ((double_ss >> double_val).fail() || !double_ss.eof())
613  {
614  std::string msg =
615  std::string("Unable to convert '") + str + "' to type " + demangle(typeid(T).name());
616 
617  if (throw_on_failure)
618  throw std::invalid_argument(msg);
619  else
620  mooseError(msg);
621  }
622 
623  // Check to see if it's an integer (and within range of an integer
624  if (double_val == static_cast<T>(double_val))
625  val = double_val;
626  else // Still failure
627  {
628  std::string msg =
629  std::string("Unable to convert '") + str + "' to type " + demangle(typeid(T).name());
630 
631  if (throw_on_failure)
632  throw std::invalid_argument(msg);
633  else
634  mooseError(msg);
635  }
636 
637  return val;
638 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:208

◆ createSymlink()

void MooseUtils::createSymlink ( const std::string &  target,
const std::string &  link 
)

Create a symbolic link, if the link already exists it is replaced.

Definition at line 814 of file MooseUtils.C.

Referenced by CSV::output().

815 {
816  clearSymlink(link);
817  int err = symlink(target.c_str(), link.c_str());
818  if (err != 0)
819  mooseError("Failed to create symbolic link (via 'symlink') from ", target, " to ", link);
820 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:208
void clearSymlink(const std::string &link)
Remove a symbolic link, if the given filename is a link.
Definition: MooseUtils.C:823

◆ doesMapContainValue()

template<typename T1 , typename T2 >
bool MooseUtils::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 at line 208 of file MooseUtils.h.

Referenced by MooseMeshUtils::getBoundaryIDs(), and MooseMesh::getBoundaryIDs().

209 {
210  for (typename std::map<T1, T2>::const_iterator iter = the_map.begin(); iter != the_map.end();
211  ++iter)
212  if (iter->second == value)
213  return true;
214  return false;
215 }

◆ escape()

void MooseUtils::escape ( std::string &  str)

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

Definition at line 95 of file MooseUtils.C.

Referenced by YAMLFormatter::printBlockOpen(), InputFileFormatter::printParams(), YAMLFormatter::printParams(), and JsonSyntaxTree::setParams().

96 {
97  std::map<char, std::string> escapes;
98  escapes['\a'] = "\\a";
99  escapes['\b'] = "\\b";
100  escapes['\f'] = "\\f";
101  escapes['\n'] = "\\n";
102  escapes['\t'] = "\\t";
103  escapes['\v'] = "\\v";
104  escapes['\r'] = "\\r";
105 
106  for (const auto & it : escapes)
107  for (size_t pos = 0; (pos = str.find(it.first, pos)) != std::string::npos;
108  pos += it.second.size())
109  str.replace(pos, 1, it.second);
110 }

◆ fileSize()

std::size_t MooseUtils::fileSize ( const std::string &  filename)

Check the file size.

Definition at line 835 of file MooseUtils.C.

Referenced by Exodus::output().

836 {
837  struct stat buffer;
838  if (stat(filename.c_str(), &buffer))
839  return 0;
840 
841  return buffer.st_size;
842 }

◆ getDefaultExecFlagEnum()

ExecFlagEnum MooseUtils::getDefaultExecFlagEnum ( )

Return the default ExecFlagEnum for MOOSE.

Definition at line 713 of file MooseUtils.C.

Referenced by AddNodalNormalsAction::act(), AdvancedOutput::addValidParams(), Output::getDefaultExecFlagEnum(), Control::getExecuteOptions(), SetupInterface::getExecuteOptions(), OutputOnWarehouse::OutputOnWarehouse(), and validParams< SetupInterface >().

714 {
715  ExecFlagEnum exec_enum = ExecFlagEnum();
716  exec_enum.addAvailableFlags(EXEC_NONE,
717  EXEC_INITIAL,
718  EXEC_LINEAR,
722  EXEC_FINAL,
723  EXEC_CUSTOM);
724  return exec_enum;
725 }
A MultiMooseEnum object to hold "execute_on" flags.
Definition: ExecFlagEnum.h:25
const ExecFlagType EXEC_CUSTOM
const ExecFlagType EXEC_NONE
void addAvailableFlags(const ExecFlagType &flag, Args... flags)
Add additional execute_on flags to the list of possible flags.
Definition: ExecFlagEnum.h:85
const ExecFlagType EXEC_TIMESTEP_END
const ExecFlagType EXEC_TIMESTEP_BEGIN
const ExecFlagType EXEC_LINEAR
const ExecFlagType EXEC_NONLINEAR
const ExecFlagType EXEC_FINAL
const ExecFlagType EXEC_INITIAL

◆ getFilesInDirs()

std::list< std::string > MooseUtils::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 routine.

The names returned will be the paths to the files relative to the current directory.

Parameters
directory_listThe list of directories to retrieve files from.

Definition at line 531 of file MooseUtils.C.

Referenced by MooseApp::getCheckpointFiles().

532 {
533  std::list<std::string> files;
534 
535  for (const auto & dir_name : directory_list)
536  files.splice(files.end(), listDir(dir_name, true));
537 
538  return files;
539 }
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:505

◆ getLatestAppCheckpointFileBase()

std::string MooseUtils::getLatestAppCheckpointFileBase ( const std::list< std::string > &  checkpoint_files)

Definition at line 550 of file MooseUtils.C.

Referenced by convertLatestCheckpoint(), and MooseApp::setRecoverFileBase().

551 {
552  const static std::vector<std::string> extensions{"xda", "xdr"};
553 
554  return getLatestCheckpointFileHelper(checkpoint_files, extensions, false);
555 }
std::string getLatestCheckpointFileHelper(const std::list< std::string > &checkpoint_files, const std::vector< std::string > extensions, bool keep_extension)
Definition: MooseUtils.C:846

◆ getLatestMeshCheckpointFile()

std::string MooseUtils::getLatestMeshCheckpointFile ( const std::list< std::string > &  checkpoint_files)

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

Parameters
checkpoint_filesthe list of files to analyze

Definition at line 542 of file MooseUtils.C.

Referenced by convertLatestCheckpoint().

543 {
544  const static std::vector<std::string> extensions{"cpr"};
545 
546  return getLatestCheckpointFileHelper(checkpoint_files, extensions, true);
547 }
std::string getLatestCheckpointFileHelper(const std::list< std::string > &checkpoint_files, const std::vector< std::string > extensions, bool keep_extension)
Definition: MooseUtils.C:846

◆ hasExtension()

bool MooseUtils::hasExtension ( const std::string &  filename,
std::string  ext,
bool  strip_exodus_ext = false 
)

Function tests if the supplied filename as the desired extension.

Parameters
filenameThe filename to test the extension
extThe extension to test for (do not include the .)
strip_exodus_extWhen true, this function ignores -s* from the end of the extension
Returns
True if the filename has the supplied extension

Definition at line 254 of file MooseUtils.C.

Referenced by FileRangeBuilder::FileRangeBuilder(), getLatestCheckpointFileHelper(), and SolutionUserObject::initialSetup().

255 {
256  // Extract the extension, w/o the '.'
257  std::string file_ext;
258  if (strip_exodus_ext)
259  {
260  pcrecpp::RE re(
261  ".*\\.([^\\.]*?)(?:-s\\d+)?\\s*$"); // capture the complete extension, ignoring -s*
262  re.FullMatch(filename, &file_ext);
263  }
264  else
265  {
266  pcrecpp::RE re(".*\\.([^\\.]*?)\\s*$"); // capture the complete extension
267  re.FullMatch(filename, &file_ext);
268  }
269 
270  // Perform the comparision
271  if (file_ext == ext)
272  return true;
273  else
274  return false;
275 }

◆ hostname()

std::string MooseUtils::hostname ( )

Get the hostname the current process is running on.

Definition at line 373 of file MooseUtils.C.

Referenced by MooseApp::MooseApp().

374 {
375  // This is from: https://stackoverflow.com/a/505546
376  char hostname[1024];
377  hostname[1023] = '\0';
378 
379  auto failure = gethostname(hostname, 1023);
380 
381  if (failure)
382  mooseError("Failed to retrieve hostname!");
383 
384  return hostname;
385 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:208
std::string hostname()
Get the hostname the current process is running on.
Definition: MooseUtils.C:373

◆ indentMessage()

void MooseUtils::indentMessage ( const std::string &  prefix,
std::string &  message,
const char *  color = COLOR_CYAN 
)

Indents the supplied message given the prefix and color.

Parameters
prefixThe prefix to use for indenting
messageThe message that will be indented
colorThe 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

Definition at line 477 of file MooseUtils.C.

Referenced by FEProblemBase::checkNonlinearConvergence(), OutputWarehouse::mooseConsole(), moose::internal::mooseErrorRaw(), MooseApp::setupOptions(), and Console::write().

480 {
481  // First we need to see if the message we need to indent (with color) also contains color codes
482  // that span lines.
483  // The code matches all of the XTERM constants (see XTermConstants.h). If it does, then we'll work
484  // on formatting
485  // each colored multiline chunk one at a time with the right codes.
486  std::string colored_message;
487  std::string curr_color = COLOR_DEFAULT; // tracks last color code before newline
488  std::string line, color_code;
489 
490  std::istringstream iss(message);
491  for (std::string line; std::getline(iss, line);) // loop over each line
492  {
493  const static pcrecpp::RE match_color(".*(\\33\\[3\\dm)((?!\\33\\[3\\d)[^\n])*");
494  pcrecpp::StringPiece line_piece(line);
495  match_color.FindAndConsume(&line_piece, &color_code);
496  colored_message += color + prefix + ": " + curr_color + line + "\n";
497 
498  if (!color_code.empty())
499  curr_color = color_code; // remember last color of this line
500  }
501  message = colored_message;
502 }

◆ join()

template<typename T >
std::string MooseUtils::join ( const T &  strings,
const std::string &  delimiter 
)

Python like join function for strings.

Definition at line 797 of file MooseUtils.C.

Referenced by ControllableParameter::checkExecuteOnType().

798 {
799  std::ostringstream oss;
800  std::copy(
801  strings.begin(), strings.end(), infix_ostream_iterator<std::string>(oss, delimiter.c_str()));
802  return oss.str();
803 }

◆ join< std::set< MooseEnumItem > >()

template std::string MooseUtils::join< std::set< MooseEnumItem > > ( const std::set< MooseEnumItem > &  ,
const std::string &   
)

◆ join< std::set< std::string > >()

template std::string MooseUtils::join< std::set< std::string > > ( const std::set< std::string > &  ,
const std::string &   
)

◆ join< std::vector< MooseEnumItem > >()

template std::string MooseUtils::join< std::vector< MooseEnumItem > > ( const std::vector< MooseEnumItem > &  ,
const std::string &   
)

◆ join< std::vector< std::string > >()

template std::string MooseUtils::join< std::vector< std::string > > ( const std::vector< std::string > &  ,
const std::string &   
)

◆ levenshteinDist()

int MooseUtils::levenshteinDist ( const std::string &  s1,
const std::string &  s2 
)

Computes and returns the Levenshtein distance between strings s1 and s2.

Definition at line 64 of file MooseUtils.C.

Referenced by findSimilar().

65 {
66  // To change the type this function manipulates and returns, change
67  // the return type and the types of the two variables below.
68  auto s1len = s1.size();
69  auto s2len = s2.size();
70 
71  auto column_start = (decltype(s1len))1;
72 
73  auto column = new decltype(s1len)[s1len + 1];
74  std::iota(column + column_start, column + s1len + 1, column_start);
75 
76  for (auto x = column_start; x <= s2len; x++)
77  {
78  column[0] = x;
79  auto last_diagonal = x - column_start;
80  for (auto y = column_start; y <= s1len; y++)
81  {
82  auto old_diagonal = column[y];
83  auto possibilities = {
84  column[y] + 1, column[y - 1] + 1, last_diagonal + (s1[y - 1] == s2[x - 1] ? 0 : 1)};
85  column[y] = std::min(possibilities);
86  last_diagonal = old_diagonal;
87  }
88  }
89  auto result = column[s1len];
90  delete[] column;
91  return result;
92 }
static PetscErrorCode Vec x

◆ linearPartitionChunk()

processor_id_type MooseUtils::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.

Parameters
num_itemsGlobal number of items to partition
num_chunksTotal number of chunks to split into
item_idThe item to find the chunk_id for
Returns
The chunk_id of the chunk that contains item_id

Definition at line 761 of file MooseUtils.C.

762 {
763  auto global_num_local_items = num_items / num_chunks;
764 
765  auto leftovers = num_items % num_chunks;
766 
767  auto first_item_past_first_part = leftovers * (global_num_local_items + 1);
768 
769  // Is it in the first section (that gets an extra item)
770  if (item_id < first_item_past_first_part)
771  return item_id / (global_num_local_items + 1);
772  else
773  {
774  auto new_item_id = item_id - first_item_past_first_part;
775 
776  // First chunk after the first section + the number of chunks after that
777  return leftovers + (new_item_id / global_num_local_items);
778  }
779 }

◆ linearPartitionItems()

void MooseUtils::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.

Parameters
num_itemsThe number of items to partition
num_chunksThe number of chunks to partition into
chunk_idThe ID of the chunk you are trying to get information about (typically the current MPI rank)
num_local_itemsOutput: The number of items for this chunk_id
local_items_beginOutput: The first item for this chunk_id
local_items_endOutput: One past the final item for this chunk_id

Definition at line 735 of file MooseUtils.C.

741 {
742  auto global_num_local_items = num_items / num_chunks;
743 
744  num_local_items = global_num_local_items;
745 
746  auto leftovers = num_items % num_chunks;
747 
748  if (chunk_id < leftovers)
749  {
750  num_local_items++;
751  local_items_begin = num_local_items * chunk_id;
752  }
753  else
754  local_items_begin =
755  (global_num_local_items + 1) * leftovers + global_num_local_items * (chunk_id - leftovers);
756 
757  local_items_end = local_items_begin + num_local_items;
758 }

◆ listDir()

std::list< std::string > MooseUtils::listDir ( const std::string  path,
bool  files_only = false 
)

Definition at line 505 of file MooseUtils.C.

Referenced by convertLatestCheckpoint(), and getFilesInDirs().

506 {
507  std::list<std::string> files;
508 
509  tinydir_dir dir;
510  dir.has_next = 0; // Avoid a garbage value in has_next (clang StaticAnalysis)
511  tinydir_open(&dir, path.c_str());
512 
513  while (dir.has_next)
514  {
515  tinydir_file file;
516  file.is_dir = 0; // Avoid a garbage value in is_dir (clang StaticAnalysis)
517  tinydir_readfile(&dir, &file);
518 
519  if (!files_only || !file.is_dir)
520  files.push_back(path + "/" + file.name);
521 
522  tinydir_next(&dir);
523  }
524 
525  tinydir_close(&dir);
526 
527  return files;
528 }

◆ MaterialPropertyStorageDump()

void MooseUtils::MaterialPropertyStorageDump ( const HashMap< const libMesh::Elem *, HashMap< unsigned int, MaterialProperties >> &  props)

Function to dump the contents of MaterialPropertyStorage for debugging purposes.

Parameters
propsThe 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.

Definition at line 436 of file MooseUtils.C.

438 {
439  // Loop through the elements
440  for (const auto & elem_it : props)
441  {
442  Moose::out << "Element " << elem_it.first->id() << '\n';
443 
444  // Loop through the sides
445  for (const auto & side_it : elem_it.second)
446  {
447  Moose::out << " Side " << side_it.first << '\n';
448 
449  // Loop over properties
450  unsigned int cnt = 0;
451  for (const auto & mat_prop : side_it.second)
452  {
453  MaterialProperty<Real> * mp = dynamic_cast<MaterialProperty<Real> *>(mat_prop);
454  if (mp)
455  {
456  Moose::out << " Property " << cnt << '\n';
457  cnt++;
458 
459  // Loop over quadrature points
460  for (unsigned int qp = 0; qp < mp->size(); ++qp)
461  Moose::out << " prop[" << qp << "] = " << (*mp)[qp] << '\n';
462  }
463  }
464  }
465  }
466 }
virtual unsigned int size() const override

◆ numDigits()

template<typename T >
int MooseUtils::numDigits ( const T &  num)

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.

Definition at line 590 of file MooseUtils.h.

Referenced by MooseUtils::DelimitedFileReader::readColumnData(), and MooseUtils::DelimitedFileReader::readRowData().

591 {
592  return num > 9 ? static_cast<int>(std::log10(static_cast<double>(num))) + 1 : 1;
593 }

◆ parallelBarrierNotify() [1/2]

void MooseUtils::parallelBarrierNotify ( const libMesh::Parallel::Communicator &  comm,
bool  messaging = true 
)

This function implements a parallel barrier function but writes progress to stdout.

Referenced by FEProblemBase::backupMultiApps(), FEProblemBase::execMultiApps(), FEProblemBase::execMultiAppTransfers(), FEProblemBase::finishMultiAppStep(), and FEProblemBase::restoreMultiApps().

◆ parallelBarrierNotify() [2/2]

void MooseUtils::parallelBarrierNotify ( const Parallel::Communicator &  comm,
bool  messaging 
)

Definition at line 196 of file MooseUtils.C.

197 {
198  processor_id_type slave_processor_id;
199 
200  if (comm.rank() == 0)
201  {
202  // The master process is already through, so report it
203  if (messaging)
204  Moose::out << "Jobs complete: 1/" << comm.size() << (1 == comm.size() ? "\n" : "\r")
205  << std::flush;
206  for (unsigned int i = 2; i <= comm.size(); ++i)
207  {
208  comm.receive(MPI_ANY_SOURCE, slave_processor_id);
209  if (messaging)
210  Moose::out << "Jobs complete: " << i << "/" << comm.size()
211  << (i == comm.size() ? "\n" : "\r") << std::flush;
212  }
213  }
214  else
215  {
216  slave_processor_id = comm.rank();
217  comm.send(0, slave_processor_id);
218  }
219 
220  comm.barrier();
221 }
MPI_Comm comm

◆ pathContains()

bool MooseUtils::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 at line 123 of file MooseUtils.C.

126 {
127  std::vector<std::string> elements;
128  tokenize(expression, elements, 0, delims);
129 
130  std::vector<std::string>::iterator found_it =
131  std::find(elements.begin(), elements.end(), string_to_find);
132  if (found_it != elements.end())
133  return true;
134  else
135  return false;
136 }
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:429

◆ pathExists()

bool MooseUtils::pathExists ( const std::string &  path)

Definition at line 139 of file MooseUtils.C.

Referenced by FileMesh::buildMesh().

140 {
141  struct stat buffer;
142  return (stat(path.c_str(), &buffer) == 0);
143 }

◆ relativeFuzzyEqual()

template<typename T , typename T2 , typename std::enable_if< ScalarTraits< T >::value &&ScalarTraits< T2 >::value, int >::type = 0>
bool MooseUtils::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.

Parameters
var1The first variable to be checked
var2The second variable to be checked
tolThe relative tolerance to be used
Returns
true if var1 and var2 are equal within relative tol

Definition at line 296 of file MooseUtils.h.

Referenced by RankFourTensorTempl< Real >::isIsotropic().

299 {
300  return (absoluteFuzzyEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
301 }
MetaPhysicL::DualNumber< T, D > abs(const MetaPhysicL::DualNumber< T, D > &in)
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:231

◆ relativeFuzzyGreaterEqual() [1/2]

bool MooseUtils::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 tolerance.

Parameters
var1The first variable to be checked
var2The second variable to be checked
tolThe tolerance to be used
Returns
true if var1 > var2 or var1 == var2 within relative tol

Referenced by FunctionDT::computeDT().

◆ relativeFuzzyGreaterEqual() [2/2]

bool MooseUtils::relativeFuzzyGreaterEqual ( const Real &  var1,
const Real &  var2,
const Real &  tol 
)

Definition at line 412 of file MooseUtils.C.

413 {
414  return (absoluteFuzzyGreaterEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
415 }
MetaPhysicL::DualNumber< T, D > abs(const MetaPhysicL::DualNumber< T, D > &in)
bool absoluteFuzzyGreaterEqual(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:388

◆ relativeFuzzyGreaterThan() [1/2]

bool MooseUtils::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.

Parameters
var1The first variable to be checked
var2The second variable to be checked
tolThe tolerance to be used
Returns
true if var1 > var2 and var1 != var2 within relative tol

◆ relativeFuzzyGreaterThan() [2/2]

bool MooseUtils::relativeFuzzyGreaterThan ( const Real &  var1,
const Real &  var2,
const Real &  tol 
)

Definition at line 418 of file MooseUtils.C.

419 {
420  return (absoluteFuzzyGreaterThan(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
421 }
MetaPhysicL::DualNumber< T, D > abs(const MetaPhysicL::DualNumber< T, D > &in)
bool absoluteFuzzyGreaterThan(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:394

◆ relativeFuzzyLessEqual() [1/2]

bool MooseUtils::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 tolerance.

Parameters
var1The first variable to be checked
var2The second variable to be checked
tolThe tolerance to be used
Returns
true if var1 < var2 or var1 == var2 within relative tol

◆ relativeFuzzyLessEqual() [2/2]

bool MooseUtils::relativeFuzzyLessEqual ( const Real &  var1,
const Real &  var2,
const Real &  tol 
)

Definition at line 424 of file MooseUtils.C.

425 {
426  return (absoluteFuzzyLessEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
427 }
MetaPhysicL::DualNumber< T, D > abs(const MetaPhysicL::DualNumber< T, D > &in)
bool absoluteFuzzyLessEqual(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:400

◆ relativeFuzzyLessThan() [1/2]

bool MooseUtils::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.

Parameters
var1The first variable to be checked
var2The second variable to be checked
tolThe tolerance to be used
Returns
true if var1 < var2 and var1 != var2 within relative tol

Referenced by PenetrationThread::competeInteractionsBothOnFace(), and FunctionDT::computeDT().

◆ relativeFuzzyLessThan() [2/2]

bool MooseUtils::relativeFuzzyLessThan ( const Real &  var1,
const Real &  var2,
const Real &  tol 
)

Definition at line 430 of file MooseUtils.C.

431 {
432  return (absoluteFuzzyLessThan(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
433 }
MetaPhysicL::DualNumber< T, D > abs(const MetaPhysicL::DualNumber< T, D > &in)
bool absoluteFuzzyLessThan(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:406

◆ removeColor()

std::string & MooseUtils::removeColor ( std::string &  msg)

remove ANSI escape sequences for teminal color from msg

Definition at line 469 of file MooseUtils.C.

Referenced by Console::writeStreamToFile().

470 {
471  pcrecpp::RE re("(\\33\\[3[0-7]m))", pcrecpp::DOTALL());
472  re.GlobalReplace(std::string(""), &msg);
473  return msg;
474 }

◆ reset() [1/2]

template<class T , typename... Args>
auto MooseUtils::reset ( int  ,
T &  obj,
Args...  args 
) -> decltype(obj.reset(args...), void())

Definition at line 22 of file SharedPool.h.

Referenced by MooseUtils::SharedPool< T >::acquire(), FEProblemBase::reinitMaterials(), and FEProblemBase::reinitMaterialsBoundary().

23 {
24  obj.reset(std::forward<Args>(args)...);
25 }

◆ reset() [2/2]

template<class T , typename... Args>
void MooseUtils::reset ( double  ,
T &  ,
Args...   
)

Definition at line 29 of file SharedPool.h.

30 {
31 }

◆ serialBegin()

void MooseUtils::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.

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).

Parameters
commThe communicator to use
warnWhether or not to warn that something is being serialized

Definition at line 224 of file MooseUtils.C.

Referenced by SerializerGuard::SerializerGuard().

225 {
226  // unless we are the first processor...
227  if (comm.rank() > 0)
228  {
229  // ...wait for the previous processor to finish
230  int dummy = 0;
231  comm.receive(comm.rank() - 1, dummy);
232  }
233  else if (warn)
234  mooseWarning("Entering serial execution block (use only for debugging)");
235 }
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:220
MPI_Comm comm

◆ serialEnd()

void MooseUtils::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 serialBegin.

No MPI communication can happen in this block.

Parameters
commThe communicator to use
warnWhether or not to warn that something is being serialized

Definition at line 238 of file MooseUtils.C.

Referenced by SerializerGuard::~SerializerGuard().

239 {
240  // unless we are the last processor...
241  if (comm.rank() + 1 < comm.size())
242  {
243  // ...notify the next processor of its turn
244  int dummy = 0;
245  comm.send(comm.rank() + 1, dummy);
246  }
247 
248  comm.barrier();
249  if (comm.rank() == 0 && warn)
250  mooseWarning("Leaving serial execution block (use only for debugging)");
251 }
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:220
MPI_Comm comm

◆ shortName()

std::string MooseUtils::shortName ( const std::string &  name)

Function for stripping name after the file / in parser block.

Definition at line 361 of file MooseUtils.C.

Referenced by MooseApp::addMeshGenerator(), MooseApp::addMeshModifier(), MooseApp::getMeshGenerator(), MooseApp::getMeshModifier(), Action::getShortName(), CSV::getVectorPostprocessorFileName(), CSV::getVectorPostprocessorFilePrefix(), CSV::initialSetup(), and Parser::walkRaw().

362 {
363  return name.substr(name.find_last_of('/') != std::string::npos ? name.find_last_of('/') + 1 : 0);
364 }

◆ split()

std::vector< std::string > MooseUtils::split ( const std::string &  str,
const std::string &  delimiter 
)

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", "", ""}.

Definition at line 782 of file MooseUtils.C.

Referenced by NonlinearSystemBase::addSplit(), MultiApp::createApp(), DMMooseReset(), and Split::setup().

783 {
784  std::vector<std::string> output;
785  size_t prev = 0, pos = 0;
786  do
787  {
788  pos = str.find(delimiter, prev);
789  output.push_back(str.substr(prev, pos - prev));
790  prev = pos + delimiter.length();
791  } while (pos != string::npos);
792  return output;
793 }

◆ splitFileName()

std::pair< std::string, std::string > MooseUtils::splitFileName ( std::string  full_file)

Function for splitting path and filename.

Parameters
full_fileA complete filename and path
Returns
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

Definition at line 287 of file MooseUtils.C.

Referenced by FileRangeBuilder::FileRangeBuilder(), and MooseApp::loadLibraryAndDependencies().

288 {
289  // Error if path ends with /
290  if (full_file.empty() || *full_file.rbegin() == '/')
291  mooseError("Invalid full file name: ", full_file);
292 
293  // Define the variables to output
294  std::string path;
295  std::string file;
296 
297  // Locate the / sepearting the file from path
298  std::size_t found = full_file.find_last_of("/");
299 
300  // If no / is found used "." for the path, otherwise seperate the two
301  if (found == std::string::npos)
302  {
303  path = ".";
304  file = full_file;
305  }
306  else
307  {
308  path = full_file.substr(0, found);
309  file = full_file.substr(found + 1);
310  }
311 
312  // Return the path and file as a pair
313  return std::pair<std::string, std::string>(path, file);
314 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:208

◆ stringToInteger()

int MooseUtils::stringToInteger ( const std::string &  input,
bool  throw_on_failure = false 
)

Robust string to integer conversion that fails for cases such at "1foo".

Parameters
inputThe string to convert.
throw_on_failureThrow an invalid_argument exception instead of mooseError.

Definition at line 728 of file MooseUtils.C.

Referenced by FormattedTable::printTable().

729 {
730  return convert<int>(input, throw_on_failure);
731 }
int convert< int >(const std::string &str, bool throw_on_failure)
Definition: MooseUtils.C:656

◆ stripExtension()

std::string MooseUtils::stripExtension ( const std::string &  s)

Removes any file extension from the fiven string s (i.e.

any ".[extension]" suffix of s) and returns the result.

Definition at line 278 of file MooseUtils.C.

Referenced by SetupMeshAction::act(), and SplitMeshAction::act().

279 {
280  auto pos = s.rfind(".");
281  if (pos != std::string::npos)
282  return s.substr(0, pos);
283  return s;
284 }

◆ tokenize()

template<typename T >
void MooseUtils::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 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.

Definition at line 429 of file MooseUtils.h.

Referenced by CommandLine::addArgument(), InputParameters::addCommandLineParam(), Syntax::addDependencySets(), MooseEnumBase::addEnumerationName(), MooseEnumBase::addEnumerationNames(), JsonInputFileFormatter::addLine(), InputParameters::addParamNamesToGroup(), InputParameters::addRequiredCommandLineParam(), MooseApp::dynamicRegistration(), MultiMooseEnum::erase(), FileOutput::FileOutput(), Syntax::isAssociated(), MultiMooseEnum::operator=(), FunctionMaterialPropertyDescriptor::parseDependentVariables(), FunctionMaterialPropertyDescriptor::parseDerivative(), pathContains(), InputFileFormatter::printParams(), MultiMooseEnum::push_back(), MooseUtils::DelimitedFileReader::readColumnData(), InputParameters::registerBuildableTypes(), InputParameters::registerRelationshipManagers(), Parser::setDoubleIndexParameter(), tokenizeAndConvert(), and wildCardMatch().

433 {
434  elements.clear();
435 
436  std::string::size_type last_pos = str.find_first_not_of(delims, 0);
437  std::string::size_type pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
438 
439  while (last_pos != std::string::npos)
440  {
441  elements.push_back(str.substr(last_pos, pos - last_pos));
442  // skip delims between tokens
443  last_pos = str.find_first_not_of(delims, pos);
444  if (last_pos == std::string::npos)
445  break;
446  pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
447  }
448 }

◆ tokenizeAndConvert()

template<typename T >
bool MooseUtils::tokenizeAndConvert ( const std::string &  str,
std::vector< T > &  tokenized_vector,
const std::string &  delimiter = " \t\n\v\f\r" 
)

tokenizeAndConvert splits a string using delimiter and then converts to type T.

If the conversion fails tokenizeAndConvert returns false, otherwise true.

Definition at line 456 of file MooseUtils.h.

Referenced by SplitMeshAction::act().

459 {
460  std::vector<std::string> tokens;
461  MooseUtils::tokenize(str, tokens, 1, delimiter);
462  tokenized_vector.resize(tokens.size());
463  for (unsigned int j = 0; j < tokens.size(); ++j)
464  {
465  std::stringstream ss(trim(tokens[j]));
466  // we have to make sure that the conversion succeeded _and_ that the string
467  // was fully read to avoid situations like [conversion to Real] 3.0abc to work
468  if ((ss >> tokenized_vector[j]).fail() || !ss.eof())
469  return false;
470  }
471  return true;
472 }
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:429
std::string trim(const std::string &str, const std::string &white_space=" \\\)
Standard scripting language trim function.
Definition: MooseUtils.C:113

◆ toLower()

std::string MooseUtils::toLower ( const std::string &  name)

Convert supplied string to lower case.

name The string to convert upper case.

Definition at line 705 of file MooseUtils.C.

Referenced by ConsoleUtils::outputRelationshipManagerInformation().

706 {
707  std::string lower(name);
708  std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
709  return lower;
710 }

◆ toUpper()

std::string MooseUtils::toUpper ( const std::string &  name)

Convert supplied string to upper case.

name The string to convert upper case.

Definition at line 697 of file MooseUtils.C.

Referenced by SubProblem::addMatrixTag(), SubProblem::addVectorTag(), MooseEnumBase::find(), SubProblem::getMatrixTagID(), SubProblem::getVectorTagID(), SubProblem::matrixTagExists(), MooseEnumItem::operator!=(), MooseEnumItem::operator==(), MooseEnum::operator==(), and SubProblem::vectorTagExists().

698 {
699  std::string upper(name);
700  std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
701  return upper;
702 }

◆ trim()

std::string MooseUtils::trim ( const std::string &  str,
const std::string &  white_space = " \t\n\v\f\r" 
)

Standard scripting language trim function.

Definition at line 113 of file MooseUtils.C.

Referenced by CommandLine::addArgument(), MooseEnumBase::addEnumerationName(), JsonInputFileFormatter::addLine(), JsonInputFileFormatter::addParameters(), SONDefinitionFormatter::addParameters(), MooseUtils::DelimitedFileReader::preprocessLine(), InputFileFormatter::printParams(), MooseUtils::DelimitedFileReader::readColumnData(), and tokenizeAndConvert().

114 {
115  const auto begin = str.find_first_not_of(white_space);
116  if (begin == std::string::npos)
117  return ""; // no content
118  const auto end = str.find_last_not_of(white_space);
119  return str.substr(begin, end - begin + 1);
120 }

◆ underscoreToCamelCase()

std::string MooseUtils::underscoreToCamelCase ( const std::string &  underscore_name,
bool  leading_upper_case 
)

Function for converting an underscore name to a camel case name.

Parameters
underscore_nameA string containing underscores
Returns
a string containing camel casing

Definition at line 329 of file MooseUtils.C.

Referenced by MooseApp::libNameToAppName(), and ConsoleUtils::outputRelationshipManagerInformation().

330 {
331  pcrecpp::StringPiece input(underscore_name);
332  pcrecpp::RE re("([^_]*)(_|$)");
333 
334  std::string result;
335  std::string us, not_us;
336  bool make_upper = leading_upper_case;
337  while (re.Consume(&input, &not_us, &us))
338  {
339  if (not_us.length() > 0)
340  {
341  if (make_upper)
342  {
343  result += std::toupper(not_us[0]);
344  if (not_us.length() > 1)
345  result += not_us.substr(1);
346  }
347  else
348  result += not_us;
349  }
350  if (us == "")
351  break;
352 
353  // Toggle flag so next match is upper cased
354  make_upper = true;
355  }
356 
357  return result;
358 }

◆ wildCardMatch()

bool MooseUtils::wildCardMatch ( std::string  name,
std::string  search_string 
)

Definition at line 558 of file MooseUtils.C.

Referenced by JsonSyntaxTree::addParameters(), JsonSyntaxTree::addSyntaxType(), SyntaxTree::TreeNode::print(), InputFileFormatter::printParams(), and JsonSyntaxTree::setParams().

559 {
560  // Assume that an empty string matches anything
561  if (search_string == "")
562  return true;
563 
564  // transform to lower for case insenstive matching
565  std::transform(name.begin(), name.end(), name.begin(), (int (*)(int))std::toupper);
566  std::transform(search_string.begin(),
567  search_string.end(),
568  search_string.begin(),
569  (int (*)(int))std::toupper);
570 
571  // exact match!
572  if (search_string.find("*") == std::string::npos)
573  return search_string == name;
574 
575  // wildcard
576  std::vector<std::string> tokens;
577  MooseUtils::tokenize(search_string, tokens, 1, "*");
578 
579  size_t pos = 0;
580  for (unsigned int i = 0; i < tokens.size() && pos != std::string::npos; ++i)
581  {
582  pos = name.find(tokens[i], pos);
583  // See if we have a leading wildcard
584  if (search_string[0] != '*' && i == 0 && pos != 0)
585  return false;
586  }
587 
588  if (pos != std::string::npos && tokens.size() > 0)
589  {
590  // Now see if we have a trailing wildcard
591  size_t last_token_length = tokens.back().length();
592  if (*search_string.rbegin() == '*' || pos == name.size() - last_token_length)
593  return true;
594  else
595  return false;
596  }
597  else
598  return false;
599 }
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:429