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...
 
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...
 
bool absoluteFuzzyEqual (const libMesh::Real &var1, const libMesh::Real &var2, const libMesh::Real &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether two variables are equal within 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...
 
bool relativeFuzzyEqual (const libMesh::Real &var1, const libMesh::Real &var2, const libMesh::Real &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether two variables are equal within a relative tolerance. 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)
 
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 absoluteFuzzyEqual (const Real &var1, const Real &var2, const Real &tol)
 
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 relativeFuzzyEqual (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)
 

Function Documentation

◆ absoluteFuzzyEqual() [1/2]

bool MooseUtils::absoluteFuzzyEqual ( const libMesh::Real &  var1,
const libMesh::Real &  var2,
const libMesh::Real &  tol = libMesh::TOLERANCE *libMesh::TOLERANCE 
)

◆ absoluteFuzzyEqual() [2/2]

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

Definition at line 387 of file MooseUtils.C.

388 {
389  return (std::abs(var1 - var2) <= tol);
390 }

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

394 {
395  return (var1 >= (var2 - tol));
396 }

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

400 {
401  return (var1 > (var2 + tol));
402 }

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

406 {
407  return (var1 <= (var2 + tol));
408 }

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

412 {
413  return (var1 < (var2 - tol));
414 }

◆ baseName()

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

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

Definition at line 366 of file MooseUtils.C.

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

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

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

Referenced by MooseApp::appNameToLibName().

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

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

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

146 {
147  std::ifstream in(filename.c_str(), std::ifstream::in);
148  if (in.fail())
149  {
150  if (throw_on_unreadable)
151  mooseError(
152  (std::string("Unable to open file \"") + filename +
153  std::string("\". Check to make sure that it exists and that you have read permission."))
154  .c_str());
155  else
156  return false;
157  }
158 
159  if (check_line_endings)
160  {
161  std::istream_iterator<char> iter(in);
162  std::istream_iterator<char> eos;
163  in >> std::noskipws;
164  while (iter != eos)
165  if (*iter++ == '\r')
166  mooseError(filename + " contains Windows(DOS) line endings which are not supported.");
167  }
168 
169  in.close();
170 
171  return true;
172 }
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 175 of file MooseUtils.C.

176 {
177  std::ofstream out(filename.c_str(), std::ofstream::out);
178  if (out.fail())
179  {
180  if (throw_on_unwritable)
181  mooseError(
182  (std::string("Unable to open file \"") + filename +
183  std::string("\". Check to make sure that it exists and that you have write permission."))
184  .c_str());
185  else
186  return false;
187  }
188 
189  out.close();
190 
191  return true;
192 }
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 490 of file MooseUtils.h.

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

491 {
492  c1.insert(c2.begin(), c2.end());
493  return c1;
494 }

◆ 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 501 of file MooseUtils.h.

502 {
503  c1.insert(c1.end(), c2.begin(), c2.end());
504  return c1;
505 }

◆ 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 512 of file MooseUtils.h.

513 {
514  c1.push_back(item);
515  return c1;
516 }

◆ 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 429 of file MooseUtils.h.

430 {
431  std::stringstream ss(str);
432  T val;
433  if ((ss >> val).fail() || !ss.eof())
434  {
435  std::string msg =
436  std::string("Unable to convert '") + str + "' to type " + demangle(typeid(T).name());
437 
438  if (throw_on_failure)
439  throw std::invalid_argument(msg);
440  else
441  mooseError(msg);
442  }
443 
444  return val;
445 }
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 667 of file MooseUtils.C.

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

668 {
669  return convertStringToInt<int>(str, throw_on_failure);
670 }

◆ convert< long int >()

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

Definition at line 681 of file MooseUtils.C.

682 {
683  return convertStringToInt<long int>(str, throw_on_failure);
684 }

◆ convert< long long int >()

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

Definition at line 695 of file MooseUtils.C.

696 {
697  return convertStringToInt<long long int>(str, throw_on_failure);
698 }

◆ convert< short int >()

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

Definition at line 653 of file MooseUtils.C.

654 {
655  return convertStringToInt<short int>(str, throw_on_failure);
656 }

◆ convert< unsigned int >()

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

Definition at line 674 of file MooseUtils.C.

675 {
676  return convertStringToInt<unsigned int>(str, throw_on_failure);
677 }

◆ convert< unsigned long int >()

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

Definition at line 688 of file MooseUtils.C.

689 {
690  return convertStringToInt<unsigned long int>(str, throw_on_failure);
691 }

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

703 {
704  return convertStringToInt<unsigned long long int>(str, throw_on_failure);
705 }

◆ convert< unsigned short int >()

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

Definition at line 660 of file MooseUtils.C.

661 {
662  return convertStringToInt<unsigned short int>(str, throw_on_failure);
663 }

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

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

45 {
46  auto slash_pos = orig.find_last_of("/");
47  auto path = orig.substr(0, slash_pos);
48  auto file = orig.substr(slash_pos + 1);
49  if (file != "LATEST")
50  return orig;
51 
53  if (!base_only)
55  else if (converted.empty())
56  mooseError("Unable to find suitable recovery file!");
57  return converted;
58 }
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:561
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:553
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:516

◆ convertStringToInt()

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

Definition at line 614 of file MooseUtils.C.

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

◆ 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 173 of file MooseUtils.h.

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

174 {
175  for (typename std::map<T1, T2>::const_iterator iter = the_map.begin(); iter != the_map.end();
176  ++iter)
177  if (iter->second == value)
178  return true;
179  return false;
180 }

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

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

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

◆ getDefaultExecFlagEnum()

ExecFlagEnum MooseUtils::getDefaultExecFlagEnum ( )

Return the default ExecFlagEnum for MOOSE.

Definition at line 724 of file MooseUtils.C.

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

725 {
726  ExecFlagEnum exec_enum = ExecFlagEnum();
727  exec_enum.addAvailableFlags(EXEC_NONE,
728  EXEC_INITIAL,
729  EXEC_LINEAR,
733  EXEC_FINAL,
734  EXEC_CUSTOM);
735  return exec_enum;
736 }
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 542 of file MooseUtils.C.

Referenced by MooseApp::getCheckpointFiles().

543 {
544  std::list<std::string> files;
545 
546  for (const auto & dir_name : directory_list)
547  files.splice(files.end(), listDir(dir_name, true));
548 
549  return files;
550 }
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:516

◆ getLatestAppCheckpointFileBase()

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

Definition at line 561 of file MooseUtils.C.

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

562 {
563  const static std::vector<std::string> extensions{"xda", "xdr"};
564 
565  return getLatestCheckpointFileHelper(checkpoint_files, extensions, false);
566 }
std::string getLatestCheckpointFileHelper(const std::list< std::string > &checkpoint_files, const std::vector< std::string > extensions, bool keep_extension)
Definition: MooseUtils.C:794

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

Referenced by convertLatestCheckpoint().

554 {
555  const static std::vector<std::string> extensions{"cpr"};
556 
557  return getLatestCheckpointFileHelper(checkpoint_files, extensions, true);
558 }
std::string getLatestCheckpointFileHelper(const std::list< std::string > &checkpoint_files, const std::vector< std::string > extensions, bool keep_extension)
Definition: MooseUtils.C:794

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

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

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

◆ hostname()

std::string MooseUtils::hostname ( )

Get the hostname the current process is running on.

Definition at line 372 of file MooseUtils.C.

Referenced by MooseApp::MooseApp().

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

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

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

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

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

Referenced by findSimilar().

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

772 {
773  auto global_num_local_items = num_items / num_chunks;
774 
775  auto leftovers = num_items % num_chunks;
776 
777  auto first_item_past_first_part = leftovers * (global_num_local_items + 1);
778 
779  // Is it in the first section (that gets an extra item)
780  if (item_id < first_item_past_first_part)
781  return item_id / (global_num_local_items + 1);
782  else
783  {
784  auto new_item_id = item_id - first_item_past_first_part;
785 
786  // First chunk after the first section + the number of chunks after that
787  return leftovers + (new_item_id / global_num_local_items);
788  }
789 }

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

751 {
752  auto global_num_local_items = num_items / num_chunks;
753 
754  num_local_items = global_num_local_items;
755 
756  auto leftovers = num_items % num_chunks;
757 
758  if (chunk_id < leftovers)
759  {
760  num_local_items++;
761  local_items_begin = num_local_items * chunk_id;
762  }
763  else
764  local_items_begin =
765  (global_num_local_items + 1) * leftovers + global_num_local_items * (chunk_id - leftovers);
766 
767  local_items_end = local_items_begin + num_local_items;
768 }

◆ listDir()

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

Definition at line 516 of file MooseUtils.C.

Referenced by convertLatestCheckpoint(), and getFilesInDirs().

517 {
518  std::list<std::string> files;
519 
520  tinydir_dir dir;
521  dir.has_next = 0; // Avoid a garbage value in has_next (clang StaticAnalysis)
522  tinydir_open(&dir, path.c_str());
523 
524  while (dir.has_next)
525  {
526  tinydir_file file;
527  file.is_dir = 0; // Avoid a garbage value in is_dir (clang StaticAnalysis)
528  tinydir_readfile(&dir, &file);
529 
530  if (!files_only || !file.is_dir)
531  files.push_back(path + "/" + file.name);
532 
533  tinydir_next(&dir);
534  }
535 
536  tinydir_close(&dir);
537 
538  return files;
539 }

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

449 {
450  // Loop through the elements
451  for (const auto & elem_it : props)
452  {
453  Moose::out << "Element " << elem_it.first->id() << '\n';
454 
455  // Loop through the sides
456  for (const auto & side_it : elem_it.second)
457  {
458  Moose::out << " Side " << side_it.first << '\n';
459 
460  // Loop over properties
461  unsigned int cnt = 0;
462  for (const auto & mat_prop : side_it.second)
463  {
464  MaterialProperty<Real> * mp = dynamic_cast<MaterialProperty<Real> *>(mat_prop);
465  if (mp)
466  {
467  Moose::out << " Property " << cnt << '\n';
468  cnt++;
469 
470  // Loop over quadrature points
471  for (unsigned int qp = 0; qp < mp->size(); ++qp)
472  Moose::out << " prop[" << qp << "] = " << (*mp)[qp] << '\n';
473  }
474  }
475  }
476  }
477 }
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 528 of file MooseUtils.h.

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

529 {
530  return num > 9 ? static_cast<int>(std::log10(static_cast<double>(num))) + 1 : 1;
531 }

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

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

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

◆ pathExists()

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

Definition at line 138 of file MooseUtils.C.

Referenced by FileMesh::buildMesh().

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

◆ relativeFuzzyEqual() [1/2]

bool MooseUtils::relativeFuzzyEqual ( const libMesh::Real &  var1,
const libMesh::Real &  var2,
const libMesh::Real &  tol = libMesh::TOLERANCE *libMesh::TOLERANCE 
)

Function to check whether two variables are equal within a relative tolerance.

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

Referenced by RankFourTensor::isIsotropic().

◆ relativeFuzzyEqual() [2/2]

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

Definition at line 417 of file MooseUtils.C.

418 {
419  return (absoluteFuzzyEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
420 }
bool absoluteFuzzyEqual(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:387

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

424 {
425  return (absoluteFuzzyGreaterEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
426 }
bool absoluteFuzzyGreaterEqual(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:393

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

430 {
431  return (absoluteFuzzyGreaterThan(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
432 }
bool absoluteFuzzyGreaterThan(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:399

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

436 {
437  return (absoluteFuzzyLessEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
438 }
bool absoluteFuzzyLessEqual(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:405

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

442 {
443  return (absoluteFuzzyLessThan(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
444 }
bool absoluteFuzzyLessThan(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:411

◆ removeColor()

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

remove ANSI escape sequences for teminal color from msg

Definition at line 480 of file MooseUtils.C.

Referenced by Console::writeStreamToFile().

481 {
482  pcrecpp::RE re("(\\33\\[3[0-7]m))", pcrecpp::DOTALL());
483  re.GlobalReplace(std::string(""), &msg);
484  return msg;
485 }

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

Referenced by SerializerGuard::SerializerGuard().

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

Referenced by SerializerGuard::~SerializerGuard().

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

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

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

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

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

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

Referenced by FormattedTable::printTable().

740 {
741  return convert<int>(input, throw_on_failure);
742 }
int convert< int >(const std::string &str, bool throw_on_failure)
Definition: MooseUtils.C:667

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

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

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

◆ 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 377 of file MooseUtils.h.

Referenced by InputParameters::addCommandLineParam(), Syntax::addDependencySets(), MooseEnumBase::addEnumerationName(), MooseEnumBase::addEnumerationNames(), JsonInputFileFormatter::addLine(), InputParameters::addParamNamesToGroup(), InputParameters::addRequiredCommandLineParam(), CommandLine::CommandLine(), 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().

381 {
382  elements.clear();
383 
384  std::string::size_type last_pos = str.find_first_not_of(delims, 0);
385  std::string::size_type pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
386 
387  while (last_pos != std::string::npos)
388  {
389  elements.push_back(str.substr(last_pos, pos - last_pos));
390  // skip delims between tokens
391  last_pos = str.find_first_not_of(delims, pos);
392  if (last_pos == std::string::npos)
393  break;
394  pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
395  }
396 }

◆ 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 404 of file MooseUtils.h.

Referenced by SplitMeshAction::act().

407 {
408  std::vector<std::string> tokens;
409  MooseUtils::tokenize(str, tokens, 1, delimiter);
410  tokenized_vector.resize(tokens.size());
411  for (unsigned int j = 0; j < tokens.size(); ++j)
412  {
413  std::stringstream ss(trim(tokens[j]));
414  // we have to make sure that the conversion succeeded _and_ that the string
415  // was fully read to avoid situations like [conversion to Real] 3.0abc to work
416  if ((ss >> tokenized_vector[j]).fail() || !ss.eof())
417  return false;
418  }
419  return true;
420 }
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:377
std::string trim(const std::string &str, const std::string &white_space=" \\\)
Standard scripting language trim function.
Definition: MooseUtils.C:112

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

Referenced by ConsoleUtils::outputRelationshipManagerInformation().

717 {
718  std::string lower(name);
719  std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
720  return lower;
721 }

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

709 {
710  std::string upper(name);
711  std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
712  return upper;
713 }

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

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

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

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

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

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

◆ wildCardMatch()

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

Definition at line 569 of file MooseUtils.C.

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

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