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 390 of file MooseUtils.C.

391 {
392  return (var1 >= (var2 - tol));
393 }

◆ 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 396 of file MooseUtils.C.

397 {
398  return (var1 > (var2 + tol));
399 }

◆ 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 402 of file MooseUtils.C.

403 {
404  return (var1 <= (var2 + tol));
405 }

◆ 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 408 of file MooseUtils.C.

409 {
410  return (var1 < (var2 - tol));
411 }

◆ baseName()

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

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

Definition at line 369 of file MooseUtils.C.

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

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

◆ 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 319 of file MooseUtils.C.

Referenced by MooseApp::appNameToLibName().

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

◆ 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 825 of file MooseUtils.C.

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

826 {
827  struct stat sbuf;
828  if (lstat(link.c_str(), &sbuf) == 0)
829  {
830  int err = unlink(link.c_str());
831  if (err != 0)
832  mooseError("Failed to remove symbolic link (via 'unlink') to ", link);
833  }
834 }
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 658 of file MooseUtils.C.

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

659 {
660  return convertStringToInt<int>(str, throw_on_failure);
661 }

◆ convert< long int >()

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

Definition at line 672 of file MooseUtils.C.

673 {
674  return convertStringToInt<long int>(str, throw_on_failure);
675 }

◆ convert< long long int >()

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

Definition at line 686 of file MooseUtils.C.

687 {
688  return convertStringToInt<long long int>(str, throw_on_failure);
689 }

◆ convert< short int >()

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

Definition at line 644 of file MooseUtils.C.

645 {
646  return convertStringToInt<short int>(str, throw_on_failure);
647 }

◆ convert< unsigned int >()

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

Definition at line 665 of file MooseUtils.C.

666 {
667  return convertStringToInt<unsigned int>(str, throw_on_failure);
668 }

◆ convert< unsigned long int >()

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

Definition at line 679 of file MooseUtils.C.

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

◆ 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 693 of file MooseUtils.C.

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

◆ convert< unsigned short int >()

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

Definition at line 651 of file MooseUtils.C.

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

◆ 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:552
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
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:507

◆ convertStringToInt()

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

Definition at line 605 of file MooseUtils.C.

606 {
607  T val;
608 
609  // Let's try to read a double and see if we can cast it to an int
610  // This would be the case for scientific notation
611  long double double_val;
612  std::stringstream double_ss(str);
613 
614  if ((double_ss >> double_val).fail() || !double_ss.eof())
615  {
616  std::string msg =
617  std::string("Unable to convert '") + str + "' to type " + demangle(typeid(T).name());
618 
619  if (throw_on_failure)
620  throw std::invalid_argument(msg);
621  else
622  mooseError(msg);
623  }
624 
625  // Check to see if it's an integer (and within range of an integer
626  if (double_val == static_cast<T>(double_val))
627  val = double_val;
628  else // Still failure
629  {
630  std::string msg =
631  std::string("Unable to convert '") + str + "' to type " + demangle(typeid(T).name());
632 
633  if (throw_on_failure)
634  throw std::invalid_argument(msg);
635  else
636  mooseError(msg);
637  }
638 
639  return val;
640 }
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 816 of file MooseUtils.C.

Referenced by CSV::output().

817 {
818  clearSymlink(link);
819  int err = symlink(target.c_str(), link.c_str());
820  if (err != 0)
821  mooseError("Failed to create symbolic link (via 'symlink') from ", target, " to ", link);
822 }
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:825

◆ 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 837 of file MooseUtils.C.

Referenced by Exodus::output().

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

◆ getDefaultExecFlagEnum()

ExecFlagEnum MooseUtils::getDefaultExecFlagEnum ( )

Return the default ExecFlagEnum for MOOSE.

Definition at line 715 of file MooseUtils.C.

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

716 {
717  ExecFlagEnum exec_enum = ExecFlagEnum();
718  exec_enum.addAvailableFlags(EXEC_NONE,
719  EXEC_INITIAL,
720  EXEC_LINEAR,
724  EXEC_FINAL,
725  EXEC_CUSTOM);
726  return exec_enum;
727 }
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 533 of file MooseUtils.C.

Referenced by MooseApp::getCheckpointFiles().

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

◆ getLatestAppCheckpointFileBase()

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

Definition at line 552 of file MooseUtils.C.

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

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

◆ 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 544 of file MooseUtils.C.

Referenced by convertLatestCheckpoint().

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

◆ 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 256 of file MooseUtils.C.

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

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

◆ hostname()

std::string MooseUtils::hostname ( )

Get the hostname the current process is running on.

Definition at line 375 of file MooseUtils.C.

Referenced by MooseApp::MooseApp().

376 {
377  // This is from: https://stackoverflow.com/a/505546
378  char hostname[1024];
379  hostname[1023] = '\0';
380 
381  auto failure = gethostname(hostname, 1023);
382 
383  if (failure)
384  mooseError("Failed to retrieve hostname!");
385 
386  return hostname;
387 }
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:375

◆ 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 479 of file MooseUtils.C.

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

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

◆ join()

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

Python like join function for strings.

Definition at line 799 of file MooseUtils.C.

Referenced by ControllableParameter::checkExecuteOnType().

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

◆ 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 763 of file MooseUtils.C.

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

◆ 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 737 of file MooseUtils.C.

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

◆ listDir()

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

Definition at line 507 of file MooseUtils.C.

Referenced by convertLatestCheckpoint(), and getFilesInDirs().

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

◆ 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 438 of file MooseUtils.C.

440 {
441  // Loop through the elements
442  for (const auto & elem_it : props)
443  {
444  Moose::out << "Element " << elem_it.first->id() << '\n';
445 
446  // Loop through the sides
447  for (const auto & side_it : elem_it.second)
448  {
449  Moose::out << " Side " << side_it.first << '\n';
450 
451  // Loop over properties
452  unsigned int cnt = 0;
453  for (const auto & mat_prop : side_it.second)
454  {
455  MaterialProperty<Real> * mp = dynamic_cast<MaterialProperty<Real> *>(mat_prop);
456  if (mp)
457  {
458  Moose::out << " Property " << cnt << '\n';
459  cnt++;
460 
461  // Loop over quadrature points
462  for (unsigned int qp = 0; qp < mp->size(); ++qp)
463  Moose::out << " prop[" << qp << "] = " << (*mp)[qp] << '\n';
464  }
465  }
466  }
467  }
468 }
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 (messaging)
201  Moose::out << "Waiting For Other Processors To Finish" << std::endl;
202  if (comm.rank() == 0)
203  {
204  // The master process is already through, so report it
205  if (messaging)
206  Moose::out << "Jobs complete: 1/" << comm.size() << (1 == comm.size() ? "\n" : "\r")
207  << std::flush;
208  for (unsigned int i = 2; i <= comm.size(); ++i)
209  {
210  comm.receive(MPI_ANY_SOURCE, slave_processor_id);
211  if (messaging)
212  Moose::out << "Jobs complete: " << i << "/" << comm.size()
213  << (i == comm.size() ? "\n" : "\r") << std::flush;
214  }
215  }
216  else
217  {
218  slave_processor_id = comm.rank();
219  comm.send(0, slave_processor_id);
220  }
221 
222  comm.barrier();
223 }
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 414 of file MooseUtils.C.

415 {
416  return (absoluteFuzzyGreaterEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
417 }
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:390

◆ 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 420 of file MooseUtils.C.

421 {
422  return (absoluteFuzzyGreaterThan(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
423 }
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:396

◆ 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 426 of file MooseUtils.C.

427 {
428  return (absoluteFuzzyLessEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
429 }
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:402

◆ 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 432 of file MooseUtils.C.

433 {
434  return (absoluteFuzzyLessThan(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
435 }
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:408

◆ removeColor()

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

remove ANSI escape sequences for teminal color from msg

Definition at line 471 of file MooseUtils.C.

Referenced by Console::writeStreamToFile().

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

◆ 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 226 of file MooseUtils.C.

Referenced by SerializerGuard::SerializerGuard().

227 {
228  // unless we are the first processor...
229  if (comm.rank() > 0)
230  {
231  // ...wait for the previous processor to finish
232  int dummy = 0;
233  comm.receive(comm.rank() - 1, dummy);
234  }
235  else if (warn)
236  mooseWarning("Entering serial execution block (use only for debugging)");
237 }
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 240 of file MooseUtils.C.

Referenced by SerializerGuard::~SerializerGuard().

241 {
242  // unless we are the last processor...
243  if (comm.rank() + 1 < comm.size())
244  {
245  // ...notify the next processor of its turn
246  int dummy = 0;
247  comm.send(comm.rank() + 1, dummy);
248  }
249 
250  comm.barrier();
251  if (comm.rank() == 0 && warn)
252  mooseWarning("Leaving serial execution block (use only for debugging)");
253 }
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 363 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().

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

◆ 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 784 of file MooseUtils.C.

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

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

◆ 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 289 of file MooseUtils.C.

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

290 {
291  // Error if path ends with /
292  if (full_file.empty() || *full_file.rbegin() == '/')
293  mooseError("Invalid full file name: ", full_file);
294 
295  // Define the variables to output
296  std::string path;
297  std::string file;
298 
299  // Locate the / sepearting the file from path
300  std::size_t found = full_file.find_last_of("/");
301 
302  // If no / is found used "." for the path, otherwise seperate the two
303  if (found == std::string::npos)
304  {
305  path = ".";
306  file = full_file;
307  }
308  else
309  {
310  path = full_file.substr(0, found);
311  file = full_file.substr(found + 1);
312  }
313 
314  // Return the path and file as a pair
315  return std::pair<std::string, std::string>(path, file);
316 }
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 730 of file MooseUtils.C.

Referenced by FormattedTable::printTable().

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

◆ 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 280 of file MooseUtils.C.

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

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

◆ 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(), 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 707 of file MooseUtils.C.

Referenced by ConsoleUtils::outputRelationshipManagerInformation().

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

◆ 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 699 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().

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

◆ 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 331 of file MooseUtils.C.

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

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

◆ wildCardMatch()

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

Definition at line 560 of file MooseUtils.C.

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

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