www.mooseframework.org
Classes | Functions
MooseUtils Namespace Reference

Classes

class  DelimitedFileReader
 Utility class for reading delimited data (e.g., CSV data). More...
 

Functions

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=" \t\n\v\f\r")
 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)
 This function implements a parallel barrier function but writes progress to stdout. More...
 
void serialBegin (const libMesh::Parallel::Communicator &comm)
 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)
 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::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...
 
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 > 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=" \t\n\v\f\r")
 tokenizeAndConvert splits a string using delimiter and then converts to type T. More...
 
std::string toUpper (const std::string &name)
 Convert supplied string to upper 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 teh 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...
 
void parallelBarrierNotify (const Parallel::Communicator &comm)
 
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)
 

Function Documentation

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

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

Referenced by FormattedTable::addData(), doesMapContainValue(), PointValue::execute(), FindValueOnLine::execute(), RelativeDifferencePostprocessor::getValue(), EigenExecutionerBase::normalizeSolution(), RankTwoTensor::operator==(), EigenExecutionerBase::postExecute(), relativeFuzzyEqual(), TimeSequenceStepperBase::setupSequence(), Predictor::shouldApply(), and Axisymmetric2D3DSolutionFunction::value().

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

Definition at line 337 of file MooseUtils.C.

338 {
339  return (std::abs(var1 - var2) <= tol);
340 }
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 doesMapContainValue(), TimePeriod::execute(), and relativeFuzzyGreaterEqual().

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

Definition at line 343 of file MooseUtils.C.

344 {
345  return (var1 >= (var2 - tol));
346 }
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 doesMapContainValue(), relativeFuzzyGreaterThan(), and Axisymmetric2D3DSolutionFunction::value().

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

Definition at line 349 of file MooseUtils.C.

350 {
351  return (var1 > (var2 + tol));
352 }
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 doesMapContainValue(), and relativeFuzzyLessEqual().

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

Definition at line 355 of file MooseUtils.C.

356 {
357  return (var1 <= (var2 + tol));
358 }
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(), doesMapContainValue(), TimePeriod::execute(), and relativeFuzzyLessThan().

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

Definition at line 361 of file MooseUtils.C.

362 {
363  return (var1 < (var2 - tol));
364 }
std::string MooseUtils::baseName ( const std::string &  name)

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

Definition at line 331 of file MooseUtils.C.

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

332 {
333  return name.substr(0, name.find_last_of('/') != std::string::npos ? name.find_last_of('/') : 0);
334 }
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 281 of file MooseUtils.C.

Referenced by MooseApp::appNameToLibName().

282 {
283  string replaced = camel_case_name;
284  // Put underscores in front of each contiguous set of capital letters
285  pcrecpp::RE("(?!^)(?<![A-Z])([A-Z]+)").GlobalReplace("_\\1", &replaced);
286 
287  // Convert all capital letters to lower case
288  std::transform(replaced.begin(), replaced.end(), replaced.begin(), ::tolower);
289  return replaced;
290 }
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 121 of file MooseUtils.C.

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

122 {
123  std::ifstream in(filename.c_str(), std::ifstream::in);
124  if (in.fail())
125  {
126  if (throw_on_unreadable)
127  mooseError(
128  (std::string("Unable to open file \"") + filename +
129  std::string("\". Check to make sure that it exists and that you have read permission."))
130  .c_str());
131  else
132  return false;
133  }
134 
135  if (check_line_endings)
136  {
137  std::istream_iterator<char> iter(in);
138  std::istream_iterator<char> eos;
139  in >> std::noskipws;
140  while (iter != eos)
141  if (*iter++ == '\r')
142  mooseError(filename + " contains Windows(DOS) line endings which are not supported.");
143  }
144 
145  in.close();
146 
147  return true;
148 }
void mooseError(Args &&...args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:182
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 151 of file MooseUtils.C.

152 {
153  std::ofstream out(filename.c_str(), std::ofstream::out);
154  if (out.fail())
155  {
156  if (throw_on_unwritable)
157  mooseError(
158  (std::string("Unable to open file \"") + filename +
159  std::string("\". Check to make sure that it exists and that you have write permission."))
160  .c_str());
161  else
162  return false;
163  }
164 
165  out.close();
166 
167  return true;
168 }
void mooseError(Args &&...args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:182
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 407 of file MooseUtils.h.

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

408 {
409  c1.insert(c2.begin(), c2.end());
410  return c1;
411 }
template<typename T >
std::vector<T> MooseUtils::concatenate ( std::vector< T >  c1,
const std::vector< T > &  c2 
)

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

Definition at line 418 of file MooseUtils.h.

419 {
420  c1.insert(c1.end(), c2.begin(), c2.end());
421  return c1;
422 }
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 429 of file MooseUtils.h.

430 {
431  c1.push_back(item);
432  return c1;
433 }
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 150 of file MooseUtils.h.

Referenced by MooseMesh::getBoundaryIDs().

151 {
152  for (typename std::map<T1, T2>::const_iterator iter = the_map.begin(); iter != the_map.end();
153  ++iter)
154  if (iter->second == value)
155  return true;
156  return false;
157 }
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 77 of file MooseUtils.C.

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

78 {
79  std::map<char, std::string> escapes;
80  escapes['\a'] = "\\a";
81  escapes['\b'] = "\\b";
82  escapes['\f'] = "\\f";
83  escapes['\n'] = "\\n";
84  escapes['\t'] = "\\t";
85  escapes['\v'] = "\\v";
86  escapes['\r'] = "\\r";
87 
88  for (const auto & it : escapes)
89  for (size_t pos = 0; (pos = str.find(it.first, pos)) != std::string::npos;
90  pos += it.second.size())
91  str.replace(pos, 1, it.second);
92 }
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 466 of file MooseUtils.C.

Referenced by CreateProblemAction::act(), FileMesh::buildMesh(), doesMapContainValue(), and MooseApp::getCheckpointFiles().

467 {
468  std::list<std::string> files;
469 
470  for (const auto & dir_name : directory_list)
471  {
472  tinydir_dir dir;
473  dir.has_next = 0; // Avoid a garbage value in has_next (clang StaticAnalysis)
474  tinydir_open(&dir, dir_name.c_str());
475 
476  while (dir.has_next)
477  {
478  tinydir_file file;
479  file.is_dir = 0; // Avoid a garbage value in is_dir (clang StaticAnalysis)
480  tinydir_readfile(&dir, &file);
481 
482  if (!file.is_dir)
483  files.push_back(dir_name + "/" + file.name);
484 
485  tinydir_next(&dir);
486  }
487 
488  tinydir_close(&dir);
489  }
490 
491  return files;
492 }
std::string MooseUtils::getLatestAppCheckpointFileBase ( const std::list< std::string > &  checkpoint_files)

Definition at line 503 of file MooseUtils.C.

Referenced by CreateProblemAction::act(), SetupRecoverFileBaseAction::act(), and doesMapContainValue().

504 {
505  const static std::vector<std::string> extensions{"xda", "xdr"};
506 
507  return getLatestCheckpointFileHelper(checkpoint_files, extensions, false);
508 }
std::string getLatestCheckpointFileHelper(const std::list< std::string > &checkpoint_files, const std::vector< std::string > extensions, bool keep_extension)
Definition: MooseUtils.C:565
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 495 of file MooseUtils.C.

Referenced by FileMesh::buildMesh(), and doesMapContainValue().

496 {
497  const static std::vector<std::string> extensions{"cpr"};
498 
499  return getLatestCheckpointFileHelper(checkpoint_files, extensions, true);
500 }
std::string getLatestCheckpointFileHelper(const std::list< std::string > &checkpoint_files, const std::vector< std::string > extensions, bool keep_extension)
Definition: MooseUtils.C:565
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 227 of file MooseUtils.C.

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

228 {
229  // Extract the extension, w/o the '.'
230  std::string file_ext;
231  if (strip_exodus_ext)
232  {
233  pcrecpp::RE re(
234  ".*\\.([^\\.]*?)(?:-s\\d+)?\\s*$"); // capture the complete extension, ignoring -s*
235  re.FullMatch(filename, &file_ext);
236  }
237  else
238  {
239  pcrecpp::RE re(".*\\.([^\\.]*?)\\s*$"); // capture the complete extension
240  re.FullMatch(filename, &file_ext);
241  }
242 
243  // Perform the comparision
244  if (file_ext == ext)
245  return true;
246  else
247  return false;
248 }
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 438 of file MooseUtils.C.

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

441 {
442  // First we need to see if the message we need to indent (with color) also contains color codes
443  // that span lines.
444  // The code matches all of the XTERM constants (see XTermConstants.h). If it does, then we'll work
445  // on formatting
446  // each colored multiline chunk one at a time with the right codes.
447  std::string colored_message;
448  std::string curr_color = COLOR_DEFAULT; // tracks last color code before newline
449  std::string line, color_code;
450 
451  std::istringstream iss(message);
452  for (std::string line; std::getline(iss, line);) // loop over each line
453  {
454  const static pcrecpp::RE match_color(".*(\\33\\[3\\dm)((?!\\33\\[3\\d)[^\n])*");
455  pcrecpp::StringPiece line_piece(line);
456  match_color.FindAndConsume(&line_piece, &color_code);
457  colored_message += color + prefix + ": " + curr_color + line + "\n";
458 
459  if (!color_code.empty())
460  curr_color = color_code; // remember last color of this line
461  }
462  message = colored_message;
463 }
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 46 of file MooseUtils.C.

Referenced by findSimilar().

47 {
48  // To change the type this function manipulates and returns, change
49  // the return type and the types of the two variables below.
50  auto s1len = s1.size();
51  auto s2len = s2.size();
52 
53  auto column_start = (decltype(s1len))1;
54 
55  auto column = new decltype(s1len)[s1len + 1];
56  std::iota(column + column_start, column + s1len + 1, column_start);
57 
58  for (auto x = column_start; x <= s2len; x++)
59  {
60  column[0] = x;
61  auto last_diagonal = x - column_start;
62  for (auto y = column_start; y <= s1len; y++)
63  {
64  auto old_diagonal = column[y];
65  auto possibilities = {
66  column[y] + 1, column[y - 1] + 1, last_diagonal + (s1[y - 1] == s2[x - 1] ? 0 : 1)};
67  column[y] = std::min(possibilities);
68  last_diagonal = old_diagonal;
69  }
70  }
71  auto result = column[s1len];
72  delete[] column;
73  return result;
74 }
static PetscErrorCode Vec x
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 397 of file MooseUtils.C.

Referenced by doesMapContainValue().

399 {
400  // Loop through the elements
401  for (const auto & elem_it : props)
402  {
403  Moose::out << "Element " << elem_it.first->id() << '\n';
404 
405  // Loop through the sides
406  for (const auto & side_it : elem_it.second)
407  {
408  Moose::out << " Side " << side_it.first << '\n';
409 
410  // Loop over properties
411  unsigned int cnt = 0;
412  for (const auto & mat_prop : side_it.second)
413  {
414  MaterialProperty<Real> * mp = dynamic_cast<MaterialProperty<Real> *>(mat_prop);
415  if (mp)
416  {
417  Moose::out << " Property " << cnt << '\n';
418  cnt++;
419 
420  // Loop over quadrature points
421  for (unsigned int qp = 0; qp < mp->size(); ++qp)
422  Moose::out << " prop[" << qp << "] = " << (*mp)[qp] << '\n';
423  }
424  }
425  }
426  }
427 }
unsigned int size() const
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 445 of file MooseUtils.h.

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

446 {
447  return num > 9 ? static_cast<int>(std::log10(static_cast<double>(num))) + 1 : 1;
448 }
void MooseUtils::parallelBarrierNotify ( const libMesh::Parallel::Communicator &  comm)

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

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

void MooseUtils::parallelBarrierNotify ( const Parallel::Communicator &  comm)

Definition at line 171 of file MooseUtils.C.

172 {
173  processor_id_type slave_processor_id;
174 
175  if (comm.rank() == 0)
176  {
177  // The master process is already through, so report it
178  Moose::out << "Jobs complete: 1/" << comm.size() << (1 == comm.size() ? "\n" : "\r")
179  << std::flush;
180  for (unsigned int i = 2; i <= comm.size(); ++i)
181  {
182  comm.receive(MPI_ANY_SOURCE, slave_processor_id);
183  Moose::out << "Jobs complete: " << i << "/" << comm.size() << (i == comm.size() ? "\n" : "\r")
184  << std::flush;
185  }
186  }
187  else
188  {
189  slave_processor_id = comm.rank();
190  comm.send(0, slave_processor_id);
191  }
192 
193  comm.barrier();
194 }
MPI_Comm comm
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 105 of file MooseUtils.C.

108 {
109  std::vector<std::string> elements;
110  tokenize(expression, elements, 0, delims);
111 
112  std::vector<std::string>::iterator found_it =
113  std::find(elements.begin(), elements.end(), string_to_find);
114  if (found_it != elements.end())
115  return true;
116  else
117  return false;
118 }
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:350
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 doesMapContainValue(), and RankFourTensor::isIsotropic().

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

Definition at line 367 of file MooseUtils.C.

368 {
369  return (absoluteFuzzyEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
370 }
bool absoluteFuzzyEqual(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:337
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(), and doesMapContainValue().

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

Definition at line 373 of file MooseUtils.C.

374 {
375  return (absoluteFuzzyGreaterEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
376 }
bool absoluteFuzzyGreaterEqual(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:343
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

Referenced by doesMapContainValue().

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

Definition at line 379 of file MooseUtils.C.

380 {
381  return (absoluteFuzzyGreaterThan(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
382 }
bool absoluteFuzzyGreaterThan(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:349
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

Referenced by doesMapContainValue().

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

Definition at line 385 of file MooseUtils.C.

386 {
387  return (absoluteFuzzyLessEqual(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
388 }
bool absoluteFuzzyLessEqual(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:355
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 FunctionDT::computeDT(), and doesMapContainValue().

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

Definition at line 391 of file MooseUtils.C.

392 {
393  return (absoluteFuzzyLessThan(var1, var2, tol * (std::abs(var1) + std::abs(var2))));
394 }
bool absoluteFuzzyLessThan(const Real &var1, const Real &var2, const Real &tol)
Definition: MooseUtils.C:361
std::string & MooseUtils::removeColor ( std::string &  msg)

remove ANSI escape sequences for teminal color from msg

Definition at line 430 of file MooseUtils.C.

Referenced by doesMapContainValue(), and Console::writeStreamToFile().

431 {
432  pcrecpp::RE re("(\\33\\[3[0-7]m))", pcrecpp::DOTALL());
433  re.GlobalReplace(std::string(""), &msg);
434  return msg;
435 }
void MooseUtils::serialBegin ( const libMesh::Parallel::Communicator &  comm)

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

Definition at line 197 of file MooseUtils.C.

198 {
199  // unless we are the first processor...
200  if (comm.rank() > 0)
201  {
202  // ...wait for the previous processor to finish
203  int dummy = 0;
204  comm.receive(comm.rank() - 1, dummy);
205  }
206  else
207  mooseWarning("Entering serial execution block (use only for debugging)");
208 }
MPI_Comm comm
void mooseWarning(Args &&...args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:194
void MooseUtils::serialEnd ( const libMesh::Parallel::Communicator &  comm)

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.

Definition at line 211 of file MooseUtils.C.

212 {
213  // unless we are the last processor...
214  if (comm.rank() + 1 < comm.size())
215  {
216  // ...notify the next processor of its turn
217  int dummy = 0;
218  comm.send(comm.rank() + 1, dummy);
219  }
220 
221  comm.barrier();
222  if (comm.rank() == 0)
223  mooseWarning("Leaving serial execution block (use only for debugging)");
224 }
MPI_Comm comm
void mooseWarning(Args &&...args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:194
std::string MooseUtils::shortName ( const std::string &  name)

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

Definition at line 325 of file MooseUtils.C.

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

326 {
327  return name.substr(name.find_last_of('/') != std::string::npos ? name.find_last_of('/') + 1 : 0);
328 }
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 251 of file MooseUtils.C.

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

252 {
253  // Error if path ends with /
254  if (full_file.empty() || *full_file.rbegin() == '/')
255  mooseError("Invalid full file name: ", full_file);
256 
257  // Define the variables to output
258  std::string path;
259  std::string file;
260 
261  // Locate the / sepearting the file from path
262  std::size_t found = full_file.find_last_of("/");
263 
264  // If no / is found used "." for the path, otherwise seperate the two
265  if (found == std::string::npos)
266  {
267  path = ".";
268  file = full_file;
269  }
270  else
271  {
272  path = full_file.substr(0, found);
273  file = full_file.substr(found + 1);
274  }
275 
276  // Return the path and file as a pair
277  return std::pair<std::string, std::string>(path, file);
278 }
void mooseError(Args &&...args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:182
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 350 of file MooseUtils.h.

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

354 {
355  elements.clear();
356 
357  std::string::size_type last_pos = str.find_first_not_of(delims, 0);
358  std::string::size_type pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
359 
360  while (last_pos != std::string::npos)
361  {
362  elements.push_back(str.substr(last_pos, pos - last_pos));
363  // skip delims between tokens
364  last_pos = str.find_first_not_of(delims, pos);
365  if (last_pos == std::string::npos)
366  break;
367  pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
368  }
369 }
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 377 of file MooseUtils.h.

380 {
381  std::vector<std::string> tokens;
382  MooseUtils::tokenize(str, tokens, 1, delimiter);
383  tokenized_vector.resize(tokens.size());
384  for (unsigned int j = 0; j < tokens.size(); ++j)
385  {
386  std::stringstream ss(trim(tokens[j]));
387  // we have to make sure that the conversion succeeded _and_ that the string
388  // was fully read to avoid situations like [conversion to Real] 3.0abc to work
389  if ((ss >> tokenized_vector[j]).fail() || !ss.eof())
390  return false;
391  }
392  return true;
393 }
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:350
std::string trim(const std::string &str, const std::string &white_space=" \t\n\v\f\r")
Standard scripting language trim function.
Definition: MooseUtils.C:95
std::string MooseUtils::toUpper ( const std::string &  name)

Convert supplied string to upper case.

name The string to convert upper case.

Definition at line 555 of file MooseUtils.C.

Referenced by MultiMooseEnum::assign(), MultiMooseEnum::contains(), MooseEnumBase::deprecate(), MooseEnumItem::operator!=(), MooseEnum::operator=(), MooseEnumItem::operator==(), MooseEnum::operator==(), MultiMooseEnum::remove(), and tokenizeAndConvert().

556 {
557  std::string upper(name);
558  std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
559  return upper;
560 }
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 95 of file MooseUtils.C.

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

96 {
97  const auto begin = str.find_first_not_of(white_space);
98  if (begin == std::string::npos)
99  return ""; // no content
100  const auto end = str.find_last_not_of(white_space);
101  return str.substr(begin, end - begin + 1);
102 }
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 293 of file MooseUtils.C.

Referenced by MooseApp::libNameToAppName().

294 {
295  pcrecpp::StringPiece input(underscore_name);
296  pcrecpp::RE re("([^_]*)(_|$)");
297 
298  std::string result;
299  std::string us, not_us;
300  bool make_upper = leading_upper_case;
301  while (re.Consume(&input, &not_us, &us))
302  {
303  if (not_us.length() > 0)
304  {
305  if (make_upper)
306  {
307  result += std::toupper(not_us[0]);
308  if (not_us.length() > 1)
309  result += not_us.substr(1);
310  }
311  else
312  result += not_us;
313  }
314  if (us == "")
315  break;
316 
317  // Toggle flag so next match is upper cased
318  make_upper = true;
319  }
320 
321  return result;
322 }
bool MooseUtils::wildCardMatch ( std::string  name,
std::string  search_string 
)

Definition at line 511 of file MooseUtils.C.

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

512 {
513  // Assume that an empty string matches anything
514  if (search_string == "")
515  return true;
516 
517  // transform to lower for case insenstive matching
518  std::transform(name.begin(), name.end(), name.begin(), (int (*)(int))std::toupper);
519  std::transform(search_string.begin(),
520  search_string.end(),
521  search_string.begin(),
522  (int (*)(int))std::toupper);
523 
524  // exact match!
525  if (search_string.find("*") == std::string::npos)
526  return search_string == name;
527 
528  // wildcard
529  std::vector<std::string> tokens;
530  MooseUtils::tokenize(search_string, tokens, 1, "*");
531 
532  size_t pos = 0;
533  for (unsigned int i = 0; i < tokens.size() && pos != std::string::npos; ++i)
534  {
535  pos = name.find(tokens[i], pos);
536  // See if we have a leading wildcard
537  if (search_string[0] != '*' && i == 0 && pos != 0)
538  return false;
539  }
540 
541  if (pos != std::string::npos && tokens.size() > 0)
542  {
543  // Now see if we have a trailing wildcard
544  size_t last_token_length = tokens.back().length();
545  if (*search_string.rbegin() == '*' || pos == name.size() - last_token_length)
546  return true;
547  else
548  return false;
549  }
550  else
551  return false;
552 }
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:350