https://mooseframework.inl.gov
Loading...
Searching...
No Matches
Classes | Typedefs | Functions
MooseUtils Namespace Reference

Classes

class  Buffer
 Base class for a buffer. More...
 
class  CircularBuffer
 An optimized circular buffer. More...
 
class  DelimitedFileReaderTempl
 Utility class for reading delimited data (e.g., CSV data). More...
 
class  LIFOBuffer
 An optimized LIFO (Last In First Out) buffer. More...
 
class  SharedPool
 Originally From https://stackoverflow.com/a/27837534/2042320. More...
 
class  StaticallyAllocatedSet
 Optimized set with static allocation. More...
 

Typedefs

typedef DelimitedFileReaderTempl< double > DelimitedFileReader
 
typedef DelimitedFileReaderTempl< std::string > DelimitedFileOfStringReader
 

Functions

std::string trim (const std::string &str, const std::string &white_space=" \t\n\v\f\r")
 Standard scripting language trim function.
 
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.
 
template<class T >
bool convert (const std::string &str, T &value, const bool throw_on_failure)
 Takes the string representation of a value and converts it to the value.
 
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.
 
std::string toUpper (std::string name)
 Convert supplied string to upper case.
 
std::string toLower (std::string name)
 Convert supplied string to lower case.
 
std::string stringJoin (const std::vector< std::string > &values, const std::string &separator=" ")
 Concatenates value into a single string separated by separator.
 
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...)
 
bool isFinitePoint (const Point &point)
 
libMesh::FEType variableFEType (const InputParameters &params)
 
std::filesystem::path pathjoin (const std::filesystem::path &p)
 
std::string runTestsExecutable ()
 
std::string findTestRoot ()
 
bool parsesToReal (const std::string &input, Real *parsed_real)
 
std::string installedInputsDir (const std::string &app_name, const std::string &dir_name, const std::string &extra_error_msg)
 
std::string docsDir (const std::string &app_name)
 
std::string mooseDocsURL (const std::string &path)
 
std::string replaceAll (std::string str, const std::string &from, const std::string &to)
 
std::string convertLatestCheckpoint (std::string orig)
 
int levenshteinDist (const std::string &s1, const std::string &s2)
 
void escape (std::string &str)
 
std::string removeExtraWhitespace (const std::string &input)
 
bool pathContains (const std::string &expression, const std::string &string_to_find, const std::string &delims)
 
bool pathExists (const std::string &path)
 
bool checkFileReadable (const std::string &filename, bool check_line_endings, bool throw_on_unreadable, bool check_for_git_lfs_pointer)
 
bool checkForGitLFSPointer (std::ifstream &file)
 
bool checkFileWriteable (const std::string &filename, bool throw_on_unwritable)
 
void parallelBarrierNotify (const Parallel::Communicator &comm, bool messaging)
 
void serialBegin (const libMesh::Parallel::Communicator &comm, bool warn)
 
void serialEnd (const libMesh::Parallel::Communicator &comm, bool warn)
 
bool hasExtension (const std::string &filename, std::string ext, bool strip_exodus_ext)
 
std::string getExtension (const std::string &filename, const bool rfind)
 
std::string stripExtension (const std::string &s, const bool rfind)
 
std::string getCurrentWorkingDir ()
 
void makedirs (const std::string &dir_name, bool throw_on_failure)
 
void removedirs (const std::string &dir_name, bool throw_on_failure)
 
std::string camelCaseToUnderscore (const std::string &camel_case_name)
 
std::string underscoreToCamelCase (const std::string &underscore_name, bool leading_upper_case)
 
std::string shortName (const std::string &name)
 
std::string baseName (const std::string &name)
 
std::string hostname ()
 
unsigned short getTermWidth (bool use_environment)
 
void MaterialPropertyStorageDump (const HashMap< const libMesh::Elem *, HashMap< unsigned int, MaterialProperties > > &props)
 
std::string & removeColor (std::string &msg)
 
void addLineBreaks (std::string &message, unsigned int line_width)
 
void indentMessage (const std::string &prefix, std::string &message, const char *color, bool indent_first_line, const std::string &post_prefix)
 
std::list< std::string > listDir (const std::string path, bool files_only)
 
std::list< std::string > getFilesInDirs (const std::list< std::string > &directory_list, const bool files_only)
 
std::string getLatestCheckpointFilePrefix (const std::list< std::string > &checkpoint_files)
 
bool wildCardMatch (std::string name, std::string search_string)
 
bool globCompare (const std::string &candidate, const std::string &pattern, std::size_t c, std::size_t p)
 
bool beginsWith (const std::string &value, const std::string &begin_value)
 
ExecFlagEnum getDefaultExecFlagEnum ()
 
int stringToInteger (const std::string &input, bool throw_on_failure)
 
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)
 
processor_id_type linearPartitionChunk (dof_id_type num_items, dof_id_type num_chunks, dof_id_type item_id)
 
std::vector< std::string > split (const std::string &str, const std::string &delimiter, std::size_t max_count)
 
std::vector< std::string > rsplit (const std::string &str, const std::string &delimiter, std::size_t max_count)
 
void createSymlink (const std::string &target, const std::string &link)
 
void clearSymlink (const std::string &link)
 
std::size_t fileSize (const std::string &filename)
 
std::string realpath (const std::string &path)
 
BoundingBox buildBoundingBox (const Point &p1, const Point &p2)
 
std::string prettyCppType (const std::string &cpp_type)
 
std::string canonicalPath (const std::string &path)
 
bool startsWith (const std::string &string1, const std::string &string2)
 
void replaceStart (std::string &string1, const std::string &string2, const std::string &string3)
 
bool isAllLowercase (const std::string &str)
 
template<typename T >
void swap (std::vector< T > &data, const std::size_t idx0, const std::size_t idx1, const libMesh::Parallel::Communicator &comm)
 Swap function for serial or distributed vector of data.
 
template<typename T >
void swap (std::vector< T > &data, const std::size_t idx0, const std::size_t idx1, const libMesh::Parallel::Communicator *comm_ptr=nullptr)
 
template<typename T >
void shuffle (std::vector< T > &data, MooseRandom &generator, const std::size_t seed_index=0)
 Shuffle function for serial or distributed vector of data that shuffles in place.
 
template<typename T >
void shuffle (std::vector< T > &data, MooseRandom &generator, const libMesh::Parallel::Communicator &comm)
 
template<typename T >
void shuffle (std::vector< T > &data, MooseRandom &generator, const std::size_t seed_index, const libMesh::Parallel::Communicator &comm)
 
template<typename T >
void shuffle (std::vector< T > &data, MooseRandom &generator, const std::size_t seed_index, const libMesh::Parallel::Communicator *comm_ptr)
 
template<typename T >
std::vector< T > resample (const std::vector< T > &data, MooseRandom &generator, const std::size_t seed_index=0)
 Randomly resample a vector of data, allowing a value to be repeated.
 
template<typename T >
std::vector< T > resample (const std::vector< T > &data, MooseRandom &generator, const libMesh::Parallel::Communicator &comm)
 
template<typename T >
std::vector< T > resample (const std::vector< T > &data, MooseRandom &generator, const std::size_t seed_index, const libMesh::Parallel::Communicator &comm)
 
template<typename T >
std::vector< T > resample (const std::vector< T > &data, MooseRandom &generator, const std::size_t seed_index, const libMesh::Parallel::Communicator *comm_ptr)
 
template<typename T , typename ActionFunctor >
void resampleWithFunctor (const std::vector< T > &data, const ActionFunctor &functor, MooseRandom &generator, const std::size_t seed_index=0)
 Randomly resample a vector of data and apply a functor, allowing a value to be repeated.
 
template<typename T , typename ActionFunctor >
void resampleWithFunctor (const std::vector< T > &data, const ActionFunctor &functor, MooseRandom &generator, const libMesh::Parallel::Communicator &comm)
 
template<typename T , typename ActionFunctor >
void resampleWithFunctor (const std::vector< T > &data, const ActionFunctor &functor, MooseRandom &generator, const std::size_t seed_index, const libMesh::Parallel::Communicator &comm)
 
template<typename T , typename ActionFunctor >
void resampleWithFunctor (const std::vector< T > &data, const ActionFunctor &functor, MooseRandom &generator, const std::size_t seed_index, const libMesh::Parallel::Communicator *comm_ptr)
 

Typedef Documentation

◆ DelimitedFileOfStringReader

Definition at line 201 of file DelimitedFileReader.h.

◆ DelimitedFileReader

Definition at line 200 of file DelimitedFileReader.h.

Function Documentation

◆ addLineBreaks()

void MooseUtils::addLineBreaks ( std::string &  message,
unsigned int  line_width 
)

Definition at line 793 of file MooseUtils.C.

795{
796 for (auto i : make_range(int(message.length() / line_width)))
797 message.insert((i + 1) * (line_width + 2) - 2, "\n");
798}
void ErrorVector unsigned int

◆ baseName()

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

Definition at line 681 of file MooseUtils.C.

682{
683 return name.substr(0, name.find_last_of('/') != std::string::npos ? name.find_last_of('/') : 0);
684}

Referenced by Moose::Builder::walkRaw().

◆ beginsWith()

bool MooseUtils::beginsWith ( const std::string &  value,
const std::string &  begin_value 
)

Definition at line 1018 of file MooseUtils.C.

1019{
1020 return value.rfind(begin_value, 0) == 0;
1021}

Referenced by CommandLine::initSubAppCommandLine(), CommandLine::parse(), and CommandLine::setCommandLineParam().

◆ buildBoundingBox()

BoundingBox MooseUtils::buildBoundingBox ( const Point &  p1,
const Point &  p2 
)

Definition at line 1194 of file MooseUtils.C.

1195{
1196 BoundingBox bb;
1197 bb.union_with(p1);
1198 bb.union_with(p2);
1199 return bb;
1200}

Referenced by PropertyReadFile::PropertyReadFile().

◆ camelCaseToUnderscore()

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

Definition at line 631 of file MooseUtils.C.

632{
633 std::string replaced = camel_case_name;
634 // Put underscores in front of each contiguous set of capital letters
635 pcrecpp::RE("(?!^)(?<![A-Z_])([A-Z]+)").GlobalReplace("_\\1", &replaced);
636
637 // Convert all capital letters to lower case
638 std::transform(replaced.begin(), replaced.end(), replaced.begin(), ::tolower);
639 return replaced;
640}

Referenced by MooseApp::appNameToLibName().

◆ canonicalPath()

std::string MooseUtils::canonicalPath ( const std::string &  path)

Definition at line 1236 of file MooseUtils.C.

1237{
1238 return std::filesystem::weakly_canonical(path).c_str();
1239}

Referenced by Registry::determineDataFilePath(), and Moose::DataFileUtils::getPath().

◆ checkFileReadable()

bool MooseUtils::checkFileReadable ( const std::string &  filename,
bool  check_line_endings,
bool  throw_on_unreadable,
bool  check_for_git_lfs_pointer 
)

Definition at line 317 of file MooseUtils.C.

321{
322 std::ifstream in(filename.c_str(), std::ifstream::in);
323 if (in.fail())
324 {
325 if (throw_on_unreadable)
327 (std::string("Unable to open file \"") + filename +
328 std::string("\". Check to make sure that it exists and that you have read permission."))
329 .c_str());
330 else
331 return false;
332 }
333
334 if (check_line_endings)
335 {
336 std::istream_iterator<char> iter(in);
337 std::istream_iterator<char> eos;
338 in >> std::noskipws;
339 while (iter != eos)
340 if (*iter++ == '\r')
341 mooseError(filename + " contains Windows(DOS) line endings which are not supported.");
342 }
343
344 if (check_for_git_lfs_pointer && checkForGitLFSPointer(in))
345 mooseError(filename + " appears to be a Git-LFS pointer. Make sure you have \"git-lfs\" "
346 "installed so that you may pull this file.");
347 in.close();
348
349 return true;
350}
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application.
Definition MooseError.h:311
bool checkForGitLFSPointer(std::ifstream &file)
Definition MooseUtils.C:353

Referenced by MooseServer::addResourcesForDocument(), FileMesh::buildMesh(), Registry::determineDataFilePath(), docsDir(), MooseApp::dynamicRegistration(), ExodusFileTimes::ExodusFileTimes(), findTestRoot(), MooseServer::gatherDocumentDefinitionLocations(), FileMeshGenerator::generate(), Moose::DataFileUtils::getPath(), ExodusTimeSequenceStepper::init(), installedInputsDir(), RestartableDataReader::isAvailable(), ADFParser::JITCompile(), MooseApp::loadLibraryAndDependencies(), Exodus::output(), Parser::parse(), MooseUtils::DelimitedFileReaderTempl< T >::read(), JSONFileReader::read(), MultiApp::readCommandLineArguments(), SolutionUserObjectBase::readXda(), MooseApp::run(), runTestsExecutable(), and ValueCache< T >::ValueCache().

◆ checkFileWriteable()

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

Definition at line 370 of file MooseUtils.C.

371{
372 std::ofstream out(filename.c_str(), std::ios_base::app);
373 if (out.fail())
374 {
375 if (throw_on_unwritable)
377 (std::string("Unable to open file \"") + filename +
378 std::string("\". Check to make sure that it exists and that you have write permission."))
379 .c_str());
380 else
381 return false;
382 }
383
384 out.close();
385
386 return true;
387}

Referenced by PNGOutput::makePNG().

◆ checkForGitLFSPointer()

bool MooseUtils::checkForGitLFSPointer ( std::ifstream &  file)

Definition at line 353 of file MooseUtils.C.

354{
355 mooseAssert(file.is_open(), "Passed in file handle is not open");
356
357 std::string line;
358
359 // git-lfs pointer files contain several name value pairs. The specification states that the
360 // first name/value pair must be "version {url}". We'll do a simplified check for that.
361 file.seekg(0);
362 std::getline(file, line);
363 if (line.find("version https://") != std::string::npos)
364 return true;
365 else
366 return false;
367}

Referenced by checkFileReadable().

◆ clearSymlink()

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

Definition at line 1136 of file MooseUtils.C.

1137{
1138#ifndef __WIN32__
1139 struct stat sbuf;
1140 if (lstat(link.c_str(), &sbuf) == 0)
1141 {
1142 auto err = unlink(link.c_str());
1143 if (err != 0)
1144 mooseError("Failed to remove symbolic link (via 'unlink') to ", link);
1145 }
1146#else
1147 auto attr = GetFileAttributesA(link.c_str());
1148 if (attr != INVALID_FILE_ATTRIBUTES)
1149 {
1150 auto err = _unlink(link.c_str());
1151 if (err != 0)
1152 mooseError("Failed to remove link/file (via '_unlink') to ", link);
1153 }
1154#endif
1155}

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

◆ convert()

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

Takes the string representation of a value and converts it to the value.

For standard numeric types, this gets around the deficiencies in the STL stoi and stod methods where they might successfully convert part of a string to a number when we'd instead prefer to get a failure.

For string and string-derived types, this does a direct copy and does not utilize a stream.

For all other types, this uses the stringstream >> operator to fill the value.

Parameters
strThe string to convert from
valueThe typed value to fill
throw_on_failureIf true, throw a std::invalid_argument on failure
Returns
Whether or not the conversion succeeded

Definition at line 96 of file MooseStringUtils.h.

97{
98 // Special case for numeric values, also handling range checking
99 if constexpr (std::is_same_v<short int, T> || std::is_same_v<unsigned short int, T> ||
100 std::is_same_v<int, T> || std::is_same_v<unsigned int, T> ||
101 std::is_same_v<long int, T> || std::is_same_v<unsigned long int, T> ||
102 std::is_same_v<long long int, T> || std::is_same_v<unsigned long long int, T>)
103 {
104 // Try read a double and try to cast it to an int
105 long double double_val;
106 std::stringstream double_ss(str);
107 double_ss >> double_val;
108
109 if (!double_ss.fail() && double_ss.eof())
110 {
111 // on arm64 the long double does not have sufficient precision
112 std::stringstream int_ss(str);
113 const bool use_int = !(int_ss >> value).fail() && int_ss.eof();
114
115 // Check to see if it's an integer and thus within range of an integer
116 if (double_val == static_cast<long double>(static_cast<T>(double_val)))
117 {
118 if (!use_int)
119 value = static_cast<T>(double_val);
120 return true;
121 }
122 }
123 }
124 // Non numeric values
125 else
126 {
127 // string or derived string: direct copy
128 if constexpr (std::is_base_of_v<std::string, T>)
129 {
130 value = str;
131 return true;
132 }
133 // non-string or numeric, use stringstream >>
134 else
135 {
136 std::stringstream ss(trim(str));
137 if (!(ss >> value).fail() && ss.eof())
138 return true;
139 }
140 }
141
142 if (throw_on_failure)
143 {
144 std::string error = "Unable to convert '" + str + "' to type ";
145#ifdef MOOSESTRINGUTILS_NO_LIBMESH
146 error += typeid(T).name();
147#else
148 error += libMesh::demangle(typeid(T).name());
149#endif
150 throw std::invalid_argument(error);
151 }
152
153 return false;
154}
std::string trim(const std::string &str, const std::string &white_space=" \t\n\v\f\r")
Standard scripting language trim function.
Real value(unsigned n, unsigned alpha, unsigned beta, Real x)
std::string name(const ElemQuality q)
std::string demangle(const char *name)

Referenced by RangeEvaler::eval().

◆ convertLatestCheckpoint()

std::string MooseUtils::convertLatestCheckpoint ( std::string  orig)

Definition at line 220 of file MooseUtils.C.

221{
222 auto slash_pos = orig.find_last_of("/");
223 auto path = orig.substr(0, slash_pos);
224 auto file = orig.substr(slash_pos + 1);
225 if (file != "LATEST")
226 return orig;
227
229
230 if (converted.empty())
231 mooseError("Unable to find suitable recovery file!");
232
233 return converted;
234}
std::list< std::string > listDir(const std::string path, bool files_only)
Definition MooseUtils.C:845
std::string getLatestCheckpointFilePrefix(const std::list< std::string > &checkpoint_files)
Definition MooseUtils.C:882

Referenced by SetupRecoverFileBaseAction::act(), FileMeshGenerator::deduceCheckpointPath(), and FEProblemBase::FEProblemBase().

◆ createSymlink()

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

Definition at line 1123 of file MooseUtils.C.

1124{
1125 clearSymlink(link);
1126#ifndef __WIN32__
1127 auto err = symlink(target.c_str(), link.c_str());
1128#else
1129 auto err = CreateSymbolicLink(target.c_str(), link.c_str(), 0);
1130#endif
1131 if (err)
1132 mooseError("Failed to create symbolic link (via 'symlink') from ", target, " to ", link);
1133}
void clearSymlink(const std::string &link)

Referenced by CSV::output().

◆ docsDir()

std::string MooseUtils::docsDir ( const std::string &  app_name)

Definition at line 188 of file MooseUtils.C.

189{
190 // See moose.mk for a detailed explanation of the assumed installed application
191 // layout. Installed docs are expected to be installed in "share/<app_name>/doc".
192 // The binary, which has a defined location will be in "bin", a peer directory to "share".
193 std::string installed_path = pathjoin(Moose::getExecutablePath(), "..", "share", app_name, "doc");
194
195 auto docfile = pathjoin(installed_path, "css", "moose.css");
196 if (pathExists(docfile) && checkFileReadable(docfile))
197 return installed_path;
198 return "";
199}
std::filesystem::path pathjoin(const std::filesystem::path &p)
Definition MooseUtils.C:122
bool pathExists(const std::string &path)
Definition MooseUtils.C:310
bool checkFileReadable(const std::string &filename, bool check_line_endings, bool throw_on_unreadable, bool check_for_git_lfs_pointer)
Definition MooseUtils.C:317
std::string getExecutablePath()
Gets the directory the running executable is on Mac OS X and linux.

Referenced by MooseApp::run().

◆ escape()

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

Definition at line 270 of file MooseUtils.C.

271{
272 std::map<char, std::string> escapes;
273 escapes['\a'] = "\\a";
274 escapes['\b'] = "\\b";
275 escapes['\f'] = "\\f";
276 escapes['\n'] = "\\n";
277 escapes['\t'] = "\\t";
278 escapes['\v'] = "\\v";
279 escapes['\r'] = "\\r";
280
281 for (const auto & it : escapes)
282 for (size_t pos = 0; (pos = str.find(it.first, pos)) != std::string::npos;
283 pos += it.second.size())
284 str.replace(pos, 1, it.second);
285}
for(PetscInt i=0;i< nvars;++i)

Referenced by MooseServer::addParametersToList(), MooseServer::addValuesToList(), MooseServer::getHoverDisplayText(), YAMLFormatter::printBlockOpen(), InputFileFormatter::printParams(), YAMLFormatter::printParams(), and JsonSyntaxTree::setParams().

◆ fileSize()

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

Definition at line 1158 of file MooseUtils.C.

1159{
1160#ifndef __WIN32__
1161 struct stat buffer;
1162 if (!stat(filename.c_str(), &buffer))
1163 return buffer.st_size;
1164#else
1165 HANDLE hFile = CreateFile(filename.c_str(),
1166 GENERIC_READ,
1167 FILE_SHARE_READ | FILE_SHARE_WRITE,
1168 NULL,
1169 OPEN_EXISTING,
1170 FILE_ATTRIBUTE_NORMAL,
1171 NULL);
1172 if (hFile == INVALID_HANDLE_VALUE)
1173 return 0;
1174
1175 LARGE_INTEGER size;
1176 if (GetFileSizeEx(hFile, &size))
1177 {
1178 CloseHandle(hFile);
1179 return size.QuadPart;
1180 }
1181
1182 CloseHandle(hFile);
1183#endif
1184 return 0;
1185}

Referenced by Exodus::output().

◆ findTestRoot()

std::string MooseUtils::findTestRoot ( )

Definition at line 138 of file MooseUtils.C.

139{
140 std::string path = ".";
141 for (int i = 0; i < 5; i++)
142 {
143 auto testroot = pathjoin(path, "testroot");
144 if (pathExists(testroot) && checkFileReadable(testroot))
145 return testroot;
146 path += "/..";
147 }
148 return "";
149}

Referenced by MooseApp::runInputs().

◆ getCurrentWorkingDir()

std::string MooseUtils::getCurrentWorkingDir ( )

Definition at line 499 of file MooseUtils.C.

500{
501 // Note: At the time of creating this method, our minimum compiler still
502 // does not support <filesystem>. Additionally, the inclusion of that header
503 // requires an additional library to be linked so for now, we'll just
504 // use the Unix standard library to get us the cwd().
505 constexpr unsigned int BUF_SIZE = 1024;
506 char buffer[BUF_SIZE];
507
508 return getcwd(buffer, BUF_SIZE) != nullptr ? buffer : "";
509}

Referenced by MooseApp::runInputs().

◆ getDefaultExecFlagEnum()

ExecFlagEnum MooseUtils::getDefaultExecFlagEnum ( )

◆ getExtension()

std::string MooseUtils::getExtension ( const std::string &  filename,
const bool  rfind 
)

Definition at line 474 of file MooseUtils.C.

475{
476 std::string file_ext = "";
477 if (filename != "")
478 {
479 // The next line splits filename at the last "/" and gives the file name after "/"
480 const std::string stripped_filename = splitFileName<std::string>(filename).second;
481 auto pos = rfind ? stripped_filename.rfind(".") : stripped_filename.find(".");
482 if (pos != std::string::npos)
483 file_ext += stripped_filename.substr(pos + 1, std::string::npos);
484 }
485
486 return file_ext;
487}

Referenced by CommonOutputAction::act(), SplitMeshAction::act(), SetupMeshAction::modifyParamsForUseSplit(), and stripExtension().

◆ getFilesInDirs()

std::list< std::string > MooseUtils::getFilesInDirs ( const std::list< std::string > &  directory_list,
const bool  files_only 
)

Definition at line 871 of file MooseUtils.C.

872{
873 std::list<std::string> files;
874
875 for (const auto & dir_name : directory_list)
876 files.splice(files.end(), listDir(dir_name, files_only));
877
878 return files;
879}

Referenced by MooseApp::getCheckpointFiles().

◆ getLatestCheckpointFilePrefix()

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

Definition at line 882 of file MooseUtils.C.

883{
884 // Create storage for newest restart files
885 // Note that these might have the same modification time if the simulation was fast.
886 // In that case we're going to save all of the "newest" files and sort it out momentarily
887 std::time_t newest_time = 0;
888 std::list<std::string> newest_restart_files;
889
890 // Loop through all possible files and store the newest
891 for (const auto & cp_file : checkpoint_files)
892 {
893 if (MooseUtils::hasExtension(cp_file, "rd"))
894 {
895 struct stat stats;
896 stat(cp_file.c_str(), &stats);
897
898 std::time_t mod_time = stats.st_mtime;
899 if (mod_time > newest_time)
900 {
901 newest_restart_files.clear(); // If the modification time is greater, clear the list
902 newest_time = mod_time;
903 }
904
905 if (mod_time == newest_time)
906 newest_restart_files.push_back(cp_file);
907 }
908 }
909
910 // Loop through all of the newest files according the number in the file name
911 int max_file_num = -1;
912 std::string max_file;
913 std::string max_prefix;
914
915 // Pull out the path including the number and the number itself
916 // This takes something_blah_out_cp/0024-restart-1.rd
917 // and returns "something_blah_out_cp/0024" as the "prefix"
918 // and then "24" as the number itself
919 pcrecpp::RE re_file_num("(.*?(\\d+))-restart-\\d+.rd$");
920
921 // Now, out of the newest files find the one with the largest number in it
922 for (const auto & res_file : newest_restart_files)
923 {
924 int file_num = 0;
925
926 // All of the file up to and including the digits
927 std::string file_prefix;
928
929 re_file_num.FullMatch(res_file, &file_prefix, &file_num);
930
931 if (file_num > max_file_num)
932 {
933 // Need both the header and the data
935 continue;
936
937 max_file_num = file_num;
938 max_file = res_file;
939 max_prefix = file_prefix;
940 }
941 }
942
943 // Error if nothing was located
944 if (max_file_num == -1)
945 mooseError("No checkpoint file found!");
946
947 return max_prefix;
948}
static bool isAvailable(const std::filesystem::path &folder_base)
bool hasExtension(const std::string &filename, std::string ext, bool strip_exodus_ext)
Definition MooseUtils.C:450

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

◆ getTermWidth()

unsigned short MooseUtils::getTermWidth ( bool  use_environment)

Initialize the value we intend to populate just in case the system call fails

Definition at line 703 of file MooseUtils.C.

704{
705#ifndef __WIN32__
706 struct winsize w;
707#else
708 struct
709 {
710 unsigned short ws_col;
711 } w;
712#endif
717 w.ws_col = std::numeric_limits<unsigned short>::max();
718
719 if (use_environment)
720 {
721 char * pps_width = std::getenv("MOOSE_PPS_WIDTH");
722 if (pps_width != NULL)
723 {
724 std::stringstream ss(pps_width);
725 ss >> w.ws_col;
726 }
727 }
728 // Default to AUTO if no environment variable was set
729 if (w.ws_col == std::numeric_limits<unsigned short>::max())
730 {
731#ifndef __WIN32__
732 try
733 {
734 ioctl(0, TIOCGWINSZ, &w);
735 }
736 catch (...)
737#endif
738 {
739 }
740 }
741
742 // Something bad happened, make sure we have a sane value
743 // 132 seems good for medium sized screens, and is available as a GNOME preset
744 if (w.ws_col == std::numeric_limits<unsigned short>::max())
745 w.ws_col = 132;
746
747 return w.ws_col;
748}

Referenced by FormattedTable::printTable().

◆ globCompare()

bool MooseUtils::globCompare ( const std::string &  candidate,
const std::string &  pattern,
std::size_t  c,
std::size_t  p 
)

Definition at line 995 of file MooseUtils.C.

999{
1000 if (p == pattern.size())
1001 return c == candidate.size();
1002
1003 if (pattern[p] == '*')
1004 {
1005 for (; c < candidate.size(); ++c)
1006 if (globCompare(candidate, pattern, c, p + 1))
1007 return true;
1008 return globCompare(candidate, pattern, c, p + 1);
1009 }
1010
1011 if (pattern[p] != '?' && pattern[p] != candidate[c])
1012 return false;
1013
1014 return globCompare(candidate, pattern, c + 1, p + 1);
1015}
bool globCompare(const std::string &candidate, const std::string &pattern, std::size_t c, std::size_t p)
Definition MooseUtils.C:995

Referenced by RestartableDataReporter::execute(), globCompare(), and ReferenceResidualConvergence::initialSetup().

◆ hasExtension()

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

Definition at line 450 of file MooseUtils.C.

451{
452 // Extract the extension, w/o the '.'
453 std::string file_ext;
454 if (strip_exodus_ext)
455 {
456 pcrecpp::RE re(
457 ".*\\.([^\\.]*?)(?:-s\\d+)?\\s*$"); // capture the complete extension, ignoring -s*
458 re.FullMatch(filename, &file_ext);
459 }
460 else
461 {
462 pcrecpp::RE re(".*\\.([^\\.]*?)\\s*$"); // capture the complete extension
463 re.FullMatch(filename, &file_ext);
464 }
465
466 // Perform the comparision
467 if (file_ext == ext)
468 return true;
469 else
470 return false;
471}

Referenced by FileMesh::FileMesh(), FileRangeBuilder::FileRangeBuilder(), getLatestCheckpointFilePrefix(), and SolutionUserObjectBase::initialSetup().

◆ hostname()

std::string MooseUtils::hostname ( )

Definition at line 687 of file MooseUtils.C.

688{
689 char hostname[1024];
690 hostname[1023] = '\0';
691#ifndef __WIN32__
692 if (gethostname(hostname, 1023))
693 mooseError("Failed to retrieve hostname!");
694#else
695 DWORD dwSize = sizeof(hostname);
696 if (!GetComputerNameEx(ComputerNamePhysicalDnsHostname, hostname, &dwSize))
697 mooseError("Failed to retrieve hostname!");
698#endif
699 return hostname;
700}
std::string hostname()
Definition MooseUtils.C:687

Referenced by hostname().

◆ indentMessage()

void MooseUtils::indentMessage ( const std::string &  prefix,
std::string &  message,
const char *  color,
bool  indent_first_line,
const std::string &  post_prefix 
)

Definition at line 801 of file MooseUtils.C.

806{
807 // First we need to see if the message we need to indent (with color) also contains color codes
808 // that span lines.
809 // The code matches all of the XTERM constants (see XTermConstants.h). If it does, then we'll work
810 // on formatting
811 // each colored multiline chunk one at a time with the right codes.
812 std::string colored_message;
813 std::string curr_color = COLOR_DEFAULT; // tracks last color code before newline
814 std::string line, color_code;
815
816 bool ends_in_newline = message.empty() ? true : message.back() == '\n';
817
818 bool first = true;
819
820 std::istringstream iss(message);
821 for (std::string line; std::getline(iss, line);) // loop over each line
822 {
823 const static pcrecpp::RE match_color(".*(\\33\\[3\\dm)((?!\\33\\[3\\d)[^\n])*");
824 pcrecpp::StringPiece line_piece(line);
825 match_color.FindAndConsume(&line_piece, &color_code);
826
827 if (!first || indent_first_line)
828 colored_message += color + prefix + post_prefix + curr_color;
829
830 colored_message += line;
831
832 // Only add a newline to the last line if it had one to begin with!
833 if (!iss.eof() || ends_in_newline)
834 colored_message += "\n";
835
836 if (!color_code.empty())
837 curr_color = color_code; // remember last color of this line
838
839 first = false;
840 }
841 message = colored_message;
842}

Referenced by DefaultNonlinearConvergence::checkConvergence(), ConsoleUtils::formatString(), OutputWarehouse::mooseConsole(), moose::internal::mooseErrorRaw(), and Console::write().

◆ installedInputsDir()

std::string MooseUtils::installedInputsDir ( const std::string &  app_name,
const std::string &  dir_name,
const std::string &  extra_error_msg 
)

Definition at line 166 of file MooseUtils.C.

169{
170 // See moose.mk for a detailed explanation of the assumed installed application
171 // layout. Installed inputs are expected to be installed in "share/<app_name>/<folder>".
172 // The binary, which has a defined location will be in "bin", a peer directory to "share".
173 std::string installed_path =
174 pathjoin(Moose::getExecutablePath(), "..", "share", app_name, dir_name);
175
176 auto test_root = pathjoin(installed_path, "testroot");
177 if (!pathExists(installed_path))
178 mooseError("Couldn't locate any installed inputs to copy in path: ",
179 installed_path,
180 '\n',
181 extra_error_msg);
182
183 checkFileReadable(test_root);
184 return installed_path;
185}

Referenced by MooseApp::copyInputs().

◆ isAllLowercase()

bool MooseUtils::isAllLowercase ( const std::string &  str)

Definition at line 1258 of file MooseUtils.C.

1259{
1260 return std::all_of(
1261 str.begin(), str.end(), [](unsigned char c) { return !std::isalpha(c) || std::islower(c); });
1262}

◆ isFinitePoint()

bool MooseUtils::isFinitePoint ( const Point &  point)

Definition at line 63 of file MooseUtils.C.

64{
65 for (const auto component : make_range(Moose::dim))
66 if (!std::isfinite(point(component)))
67 return false;
68
69 return true;
70}
if(!dmm->_nl) SETERRQ(PETSC_COMM_WORLD
unsigned int dim
MOOSE now contains C++17 code, so give a reasonable error message stating what the user can do to add...

Referenced by Moose::Mortar::projectQPoints3d(), and MortarSegmentHelper::referencePoint().

◆ levenshteinDist()

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

Definition at line 239 of file MooseUtils.C.

240{
241 // To change the type this function manipulates and returns, change
242 // the return type and the types of the two variables below.
243 auto s1len = s1.size();
244 auto s2len = s2.size();
245
246 auto column_start = (decltype(s1len))1;
247
248 auto column = new decltype(s1len)[s1len + 1];
249 std::iota(column + column_start, column + s1len + 1, column_start);
250
251 for (auto x = column_start; x <= s2len; x++)
252 {
253 column[0] = x;
254 auto last_diagonal = x - column_start;
255 for (auto y = column_start; y <= s1len; y++)
256 {
257 auto old_diagonal = column[y];
258 auto possibilities = {
259 column[y] + 1, column[y - 1] + 1, last_diagonal + (s1[y - 1] == s2[x - 1] ? 0 : 1)};
260 column[y] = std::min(possibilities);
261 last_diagonal = old_diagonal;
262 }
263 }
264 auto result = column[s1len];
265 delete[] column;
266 return result;
267}

Referenced by Moose::findSimilar().

◆ linearPartitionChunk()

processor_id_type MooseUtils::linearPartitionChunk ( dof_id_type  num_items,
dof_id_type  num_chunks,
dof_id_type  item_id 
)

Definition at line 1062 of file MooseUtils.C.

1063{
1064 auto global_num_local_items = num_items / num_chunks;
1065
1066 auto leftovers = num_items % num_chunks;
1067
1068 auto first_item_past_first_part = leftovers * (global_num_local_items + 1);
1069
1070 // Is it in the first section (that gets an extra item)
1071 if (item_id < first_item_past_first_part)
1072 return item_id / (global_num_local_items + 1);
1073 else
1074 {
1075 auto new_item_id = item_id - first_item_past_first_part;
1076
1077 // First chunk after the first section + the number of chunks after that
1078 return leftovers + (new_item_id / global_num_local_items);
1079 }
1080}

Referenced by DistributedRectilinearMeshGenerator::buildCube().

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

Definition at line 1036 of file MooseUtils.C.

1042{
1043 auto global_num_local_items = num_items / num_chunks;
1044
1045 num_local_items = global_num_local_items;
1046
1047 auto leftovers = num_items % num_chunks;
1048
1049 if (chunk_id < leftovers)
1050 {
1051 num_local_items++;
1052 local_items_begin = num_local_items * chunk_id;
1053 }
1054 else
1055 local_items_begin =
1056 (global_num_local_items + 1) * leftovers + global_num_local_items * (chunk_id - leftovers);
1057
1058 local_items_end = local_items_begin + num_local_items;
1059}

Referenced by DistributedRectilinearMeshGenerator::buildCube().

◆ listDir()

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

Definition at line 845 of file MooseUtils.C.

846{
847 std::list<std::string> files;
848
849 tinydir_dir dir;
850 dir.has_next = 0; // Avoid a garbage value in has_next (clang StaticAnalysis)
851 tinydir_open(&dir, path.c_str());
852
853 while (dir.has_next)
854 {
855 tinydir_file file;
856 file.is_dir = 0; // Avoid a garbage value in is_dir (clang StaticAnalysis)
857 tinydir_readfile(&dir, &file);
858
859 if (!files_only || !file.is_dir)
860 files.push_back(path + "/" + file.name);
861
862 tinydir_next(&dir);
863 }
864
865 tinydir_close(&dir);
866
867 return files;
868}

Referenced by convertLatestCheckpoint(), getFilesInDirs(), and removedirs().

◆ makedirs()

void MooseUtils::makedirs ( const std::string &  dir_name,
bool  throw_on_failure 
)

Definition at line 512 of file MooseUtils.C.

513{
514 // split path into directories with delimiter '/'
515 std::vector<std::string> split_dir_names;
516 MooseUtils::tokenize(dir_name, split_dir_names);
517
518 auto n = split_dir_names.size();
519
520 // remove '.' and '..' when possible
521 auto i = n;
522 i = 0;
523 while (i != n)
524 {
525 if (split_dir_names[i] == ".")
526 {
527 for (auto j = i + 1; j < n; ++j)
528 split_dir_names[j - 1] = split_dir_names[j];
529 --n;
530 }
531 else if (i > 0 && split_dir_names[i] == ".." && split_dir_names[i - 1] != "..")
532 {
533 for (auto j = i + 1; j < n; ++j)
534 split_dir_names[j - 2] = split_dir_names[j];
535 n -= 2;
536 --i;
537 }
538 else
539 ++i;
540 }
541 if (n == 0)
542 return;
543
544 split_dir_names.resize(n);
545
546 // start creating directories recursively
547 std::string cur_dir = dir_name[0] == '/' ? "" : ".";
548 for (auto & dir : split_dir_names)
549 {
550 cur_dir += "/" + dir;
551
552 if (!pathExists(cur_dir))
553 {
554 auto code = Utility::mkdir(cur_dir.c_str());
555 if (code != 0)
556 {
557 std::string msg = "Failed creating directory " + dir_name;
558 if (throw_on_failure)
559 throw std::invalid_argument(msg);
560 else
561 mooseError(msg);
562 }
563 }
564 }
565}
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 ...
int mkdir(const char *pathname)

◆ MaterialPropertyStorageDump()

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

Definition at line 751 of file MooseUtils.C.

753{
754 // Loop through the elements
755 for (const auto & elem_it : props)
756 {
757 Moose::out << "Element " << elem_it.first->id() << '\n';
758
759 // Loop through the sides
760 for (const auto & side_it : elem_it.second)
761 {
762 Moose::out << " Side " << side_it.first << '\n';
763
764 // Loop over properties
765 unsigned int cnt = 0;
766 for (const auto & mat_prop : side_it.second)
767 {
768 if (auto mp = dynamic_cast<const MaterialProperty<Real> *>(&mat_prop))
769 {
770 Moose::out << " Property " << cnt << '\n';
771 cnt++;
772
773 // Loop over quadrature points
774 for (unsigned int qp = 0; qp < mp->size(); ++qp)
775 Moose::out << " prop[" << qp << "] = " << (*mp)[qp] << '\n';
776 }
777 }
778 }
779 }
780
781 Moose::out << std::flush;
782}

◆ mooseDocsURL()

std::string MooseUtils::mooseDocsURL ( const std::string &  path)

Definition at line 202 of file MooseUtils.C.

203{
204 return "https://mooseframework.inl.gov/" + path;
205}

Referenced by ExecFlagEnum::getDocString().

◆ parallelBarrierNotify()

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

Definition at line 390 of file MooseUtils.C.

391{
392 processor_id_type secondary_processor_id;
393
394 if (messaging)
395 Moose::out << "Waiting For Other Processors To Finish" << std::endl;
396 if (comm.rank() == 0)
397 {
398 // The primary process is already through, so report it
399 if (messaging)
400 Moose::out << "Jobs complete: 1/" << comm.size() << (1 == comm.size() ? "\n" : "\r")
401 << std::flush;
402 for (unsigned int i = 2; i <= comm.size(); ++i)
403 {
404 comm.receive(MPI_ANY_SOURCE, secondary_processor_id);
405 if (messaging)
406 Moose::out << "Jobs complete: " << i << "/" << comm.size()
407 << (i == comm.size() ? "\n" : "\r") << std::flush;
408 }
409 }
410 else
411 {
412 secondary_processor_id = comm.rank();
413 comm.send(0, secondary_processor_id);
414 }
415
416 comm.barrier();
417}
processor_id_type size() const
processor_id_type rank() const
Status receive(const unsigned int dest_processor_id, T &buf, const MessageTag &tag=any_tag) const
void send(const unsigned int dest_processor_id, const T &buf, const MessageTag &tag=no_tag) const

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

◆ parsesToReal()

bool MooseUtils::parsesToReal ( const std::string &  input,
Real *  parsed_real 
)

Definition at line 152 of file MooseUtils.C.

153{
154 std::istringstream ss(input);
155 Real real_value;
156 if (ss >> real_value && ss.eof())
157 {
158 if (parsed_real)
159 (*parsed_real) = real_value;
160 return true;
161 }
162 return false;
163}

Referenced by DiffusionCG::addFEBCs(), DiffusionCG::addFEKernels(), DiffusionFV::addFVBCs(), DiffusionFV::addFVKernels(), FunctorExtremaPositions::FunctorExtremaPositions(), FunctorIC::FunctorIC(), and RankTwoTensorFromComponentProperties::RankTwoTensorFromComponentProperties().

◆ pathContains()

bool MooseUtils::pathContains ( const std::string &  expression,
const std::string &  string_to_find,
const std::string &  delims 
)

Definition at line 294 of file MooseUtils.C.

297{
298 std::vector<std::string> elements;
299 tokenize(expression, elements, 0, delims);
300
301 std::vector<std::string>::iterator found_it =
302 std::find(elements.begin(), elements.end(), string_to_find);
303 if (found_it != elements.end())
304 return true;
305 else
306 return false;
307}

◆ pathExists()

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

Definition at line 310 of file MooseUtils.C.

311{
312 struct stat buffer;
313 return (stat(path.c_str(), &buffer) == 0);
314}

Referenced by MooseApp::copyInputs(), FileMeshGenerator::deduceCheckpointPath(), docsDir(), findTestRoot(), installedInputsDir(), RestartableDataReader::isAvailable(), makedirs(), removedirs(), MooseApp::run(), and runTestsExecutable().

◆ pathjoin()

std::filesystem::path MooseUtils::pathjoin ( const std::filesystem::path &  p)

◆ prettyCppType()

std::string MooseUtils::prettyCppType ( const std::string &  cpp_type)

Definition at line 1203 of file MooseUtils.C.

1204{
1205 // On mac many of the std:: classes are inline namespaced with __1
1206 // On linux std::string can be inline namespaced with __cxx11
1207 std::string s = cpp_type;
1208 // Remove all spaces surrounding a >
1209 pcrecpp::RE("\\s(?=>)").GlobalReplace("", &s);
1210 pcrecpp::RE("std::__\\w+::").GlobalReplace("std::", &s);
1211 // It would be nice if std::string actually looked normal
1212 pcrecpp::RE("\\s*std::basic_string<char, std::char_traits<char>, std::allocator<char>>\\s*")
1213 .GlobalReplace("std::string", &s);
1214 // It would be nice if std::vector looked normal
1215 pcrecpp::RE r("std::vector<([[:print:]]+),\\s?std::allocator<\\s?\\1\\s?>\\s?>");
1216 r.GlobalReplace("std::vector<\\1>", &s);
1217 // Do it again for nested vectors
1218 r.GlobalReplace("std::vector<\\1>", &s);
1219 // It would be nice if std::map and unordered map looked normal
1220 pcrecpp::RE r_map(
1221 "std::map<\\s*((?:[^,<]|<[^>]*>)+)\\s*,\\s*((?:[^,<]|<[^>]*>)+)\\s*,\\s*"
1222 "std::less<\\s*\\1\\s*>\\s*,\\s*"
1223 "std::allocator<\\s*std::pair<\\s*(?:const\\s*\\1|\\1\\s*const)\\s*,\\s*\\2\\s*>\\s*>\\s*>");
1224 r_map.GlobalReplace("std::map<\\1, \\2>", &s);
1225 pcrecpp::RE r_umap(
1226 "std::unordered_map<\\s*([^,]+)\\s*,\\s*([^,]+)\\s*,\\s*"
1227 "std::hash<\\s*\\1\\s*>\\s*,\\s*"
1228 "std::equal_to<\\s*\\1\\s*>\\s*,\\s*"
1229 "std::allocator<\\s*std::pair<\\s*(?:const\\s*\\1|\\1\\s*const)\\s*,\\s*\\2\\s*>\\s*>\\s*>");
1230 r_umap.GlobalReplace("std::unordered_map<\\1, \\2>", &s);
1231
1232 return s;
1233}

Referenced by MooseServer::addParametersToList(), MooseServer::addValuesToList(), InputParametersChecksUtils< C >::assertParamDefined(), ReporterGeneralContext< T >::contextType(), ReporterBroadcastContext< T >::contextType(), ReporterScatterContext< T >::contextType(), ReporterGatherContext< T >::contextType(), ReporterVectorContext< T >::contextType(), Moose::Kokkos::dataLoad(), FunctorSmootherTempl< T >::FunctorSmootherTempl(), MooseServer::gatherDocumentDefinitionLocations(), MooseServer::getFileNameTypeValues(), MooseServer::getNodesByValueAndTypes(), CSG::CSGSurface::getSurfaceType(), CSG::CSGLattice::getType(), CSG::CSGEngUnit::getUnitType(), ThreadedElementLoop< RangeType >::printExecutionOrdering(), Moose::ParameterRegistry::set(), JsonSyntaxTree::setParams(), and MFEMProblem::solverTypeString().

◆ realpath()

std::string MooseUtils::realpath ( const std::string &  path)

Definition at line 1188 of file MooseUtils.C.

1189{
1190 return std::filesystem::absolute(path);
1191}

Referenced by Parser::parse(), and MooseApp::run().

◆ removeColor()

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

Definition at line 785 of file MooseUtils.C.

786{
787 pcrecpp::RE re("(\\33\\[3[0-7]m))", pcrecpp::DOTALL());
788 re.GlobalReplace(std::string(""), &msg);
789 return msg;
790}

Referenced by Console::writeStreamToFile().

◆ removedirs()

void MooseUtils::removedirs ( const std::string &  dir_name,
bool  throw_on_failure 
)

Definition at line 568 of file MooseUtils.C.

569{
570 // split path into directories with delimiter '/'
571 std::vector<std::string> split_dir_names;
572 MooseUtils::tokenize(dir_name, split_dir_names);
573
574 auto n = split_dir_names.size();
575
576 // remove '.' and '..' when possible
577 auto i = n;
578 i = 0;
579 while (i != n)
580 {
581 if (split_dir_names[i] == ".")
582 {
583 for (auto j = i + 1; j < n; ++j)
584 split_dir_names[j - 1] = split_dir_names[j];
585 --n;
586 }
587 else if (i > 0 && split_dir_names[i] == ".." && split_dir_names[i - 1] != "..")
588 {
589 for (auto j = i + 1; j < n; ++j)
590 split_dir_names[j - 2] = split_dir_names[j];
591 n -= 2;
592 --i;
593 }
594 else
595 ++i;
596 }
597 if (n == 0)
598 return;
599
600 split_dir_names.resize(n);
601
602 // start removing directories recursively
603 std::string base_dir = dir_name[0] == '/' ? "" : ".";
604 for (i = n; i > 0; --i)
605 {
606 std::string cur_dir = base_dir;
607 auto j = i;
608 for (j = 0; j < i; ++j)
609 cur_dir += "/" + split_dir_names[j];
610
611 // listDir should return at least '.' and '..'
612 if (pathExists(cur_dir) && listDir(cur_dir).size() == 2)
613 {
614 auto code = rmdir(cur_dir.c_str());
615 if (code != 0)
616 {
617 std::string msg = "Failed removing directory " + dir_name;
618 if (throw_on_failure)
619 throw std::invalid_argument(msg);
620 else
621 mooseError(msg);
622 }
623 }
624 else
625 // stop removing
626 break;
627 }
628}

◆ removeExtraWhitespace()

std::string MooseUtils::removeExtraWhitespace ( const std::string &  input)

Definition at line 288 of file MooseUtils.C.

289{
290 return std::regex_replace(input, std::regex("^\\s+|\\s+$|\\s+(?=\\s)"), "");
291}

Referenced by CommandLine::initSubAppCommandLine(), and CommandLine::parse().

◆ replaceAll()

std::string MooseUtils::replaceAll ( std::string  str,
const std::string &  from,
const std::string &  to 
)

Definition at line 208 of file MooseUtils.C.

209{
210 size_t start_pos = 0;
211 while ((start_pos = str.find(from, start_pos)) != std::string::npos)
212 {
213 str.replace(start_pos, from.length(), to);
214 start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
215 }
216 return str;
217}

Referenced by ReporterDebugOutput::output(), and MooseUtils::DelimitedFileReaderTempl< T >::processLine().

◆ replaceStart()

void MooseUtils::replaceStart ( std::string &  string1,
const std::string &  string2,
const std::string &  string3 
)

Definition at line 1250 of file MooseUtils.C.

1251{
1252 mooseAssert(startsWith(string1, string2),
1253 "Cannot replace the start because it doesn't match the start string");
1254 string1.replace(0, string2.size(), string3);
1255}
bool startsWith(const std::string &string1, const std::string &string2)

◆ resample() [1/4]

template<typename T >
std::vector< T > MooseUtils::resample ( const std::vector< T > &  data,
MooseRandom &  generator,
const libMesh::Parallel::Communicator &  comm 
)

Definition at line 540 of file Shuffle.h.

543{
544 return MooseUtils::resample(data, generator, 0, &comm);
545}
std::vector< T > resample(const std::vector< T > &data, MooseRandom &generator, const std::size_t seed_index=0)
Randomly resample a vector of data, allowing a value to be repeated.
Definition Shuffle.h:531

◆ resample() [2/4]

template<typename T >
std::vector< T > MooseUtils::resample ( const std::vector< T > &  data,
MooseRandom &  generator,
const std::size_t  seed_index,
const libMesh::Parallel::Communicator &  comm 
)

Definition at line 549 of file Shuffle.h.

553{
554 return MooseUtils::resample(data, generator, seed_index, &comm);
555}

◆ resample() [3/4]

template<typename T >
std::vector< T > MooseUtils::resample ( const std::vector< T > &  data,
MooseRandom &  generator,
const std::size_t  seed_index,
const libMesh::Parallel::Communicator *  comm_ptr 
)

Definition at line 335 of file Shuffle.h.

339{
340 // Size of the local input data
341 const std::size_t n_local = data.size();
342
343 // Re-sampled data vector to be returned
344 std::vector<T> replicate(n_local);
345
346 // REPLICATED data
347 if (!comm_ptr || comm_ptr->size() == 1)
348 {
349 replicate.resize(n_local);
350 for (std::size_t j = 0; j < n_local; ++j)
351 {
352 auto index = generator.randl(seed_index, 0, n_local);
353 replicate[j] = data[index];
354 }
355 }
356
357 // DISTRIBUTED data
358 else
359 {
360 // Compute the global size of the vector
361 std::size_t n_global = n_local;
362 comm_ptr->sum(n_global);
363
364 // Compute the vector data offsets, the scope cleans up the "n_local" vector
365 std::vector<std::size_t> offsets(comm_ptr->size());
366 {
367 std::vector<std::size_t> local_sizes;
368 comm_ptr->allgather(n_local, local_sizes);
369 for (std::size_t i = 0; i < local_sizes.size() - 1; ++i)
370 offsets[i + 1] = offsets[i] + local_sizes[i];
371 }
372
373 // Advance the random number generator to the current offset
374 const auto rank = comm_ptr->rank();
375 for (std::size_t i = 0; i < offsets[rank]; ++i)
376 generator.randl(seed_index, 0, n_global);
377
378 // Compute the needs for this processor
379 std::unordered_map<processor_id_type, std::vector<std::pair<std::size_t, std::size_t>>> needs;
380 for (std::size_t i = 0; i < n_local; ++i)
381 {
382 const auto idx = generator.randl(seed_index, 0, n_global); // random global index
383
384 // Locate the rank and local index of the data desired
385 const auto idx_offset_iter = std::prev(std::upper_bound(offsets.begin(), offsets.end(), idx));
386 const auto idx_rank = std::distance(offsets.begin(), idx_offset_iter);
387 const auto idx_local_idx = idx - *idx_offset_iter;
388
389 // Local available data can be inserted into the re-sample, non-local data is add the the
390 // needs from other ranks
391 if (idx_rank == rank)
392 replicate[i] = data[idx_local_idx];
393 else
394 needs[idx_rank].emplace_back(idx_local_idx, i);
395 }
396
397 // Advance the random number generator to the end of the global vector
398 for (std::size_t i = offsets[rank] + n_local; i < n_global; ++i)
399 generator.randl(seed_index, 0, n_global);
400
401 // Collect the values to be returned to the various processors
402 std::unordered_map<processor_id_type, std::vector<std::pair<T, std::size_t>>> returns;
403 auto return_functor =
404 [&data, &returns](processor_id_type pid,
405 const std::vector<std::pair<std::size_t, std::size_t>> & indices)
406 {
407 auto & returns_pid = returns[pid];
408 for (const auto & idx : indices)
409 returns_pid.emplace_back(data[idx.first], idx.second);
410 };
411 Parallel::push_parallel_vector_data(*comm_ptr, needs, return_functor);
412
413 // Receive resampled values from the various processors
414 auto recv_functor =
415 [&replicate](processor_id_type, const std::vector<std::pair<T, std::size_t>> & values)
416 {
417 for (const auto & value : values)
418 replicate[value.second] = value.first;
419 };
420 Parallel::push_parallel_vector_data(*comm_ptr, returns, recv_functor);
421 }
422 return replicate;
423}
std::array< Real, 2 > values
Definition MortarUtils.C:52
static uint32_t randl()
This method returns the next random number (long format) from the generator.
Definition MooseRandom.h:71
void allgather(const T &send_data, std::vector< T, A > &recv_data) const
uint8_t processor_id_type
unsigned int idx(const ElemType type, const unsigned int nx, const unsigned int i, const unsigned int j)

◆ resample() [4/4]

template<typename T >
std::vector< T > MooseUtils::resample ( const std::vector< T > &  data,
MooseRandom &  generator,
const std::size_t  seed_index = 0 
)

Randomly resample a vector of data, allowing a value to be repeated.

Parameters
dataThe vector on which the values are to be swapped
generatorRandom number generator to use for shuffle
seed_index(default: 0) The seed index to use for calls to randl
comm_ptrOptional Communicator, if provided and running with multiple processors the vector is assumed to be distributed

Definition at line 531 of file Shuffle.h.

534{
535 return MooseUtils::resample(data, generator, seed_index, nullptr);
536}

Referenced by resample(), resample(), and resample().

◆ resampleWithFunctor() [1/4]

template<typename T , typename ActionFunctor >
void MooseUtils::resampleWithFunctor ( const std::vector< T > &  data,
const ActionFunctor &  functor,
MooseRandom &  generator,
const libMesh::Parallel::Communicator &  comm 
)

Definition at line 569 of file Shuffle.h.

573{
574 return MooseUtils::resampleWithFunctor(data, functor, generator, 0, &comm);
575}
void resampleWithFunctor(const std::vector< T > &data, const ActionFunctor &functor, MooseRandom &generator, const std::size_t seed_index=0)
Randomly resample a vector of data and apply a functor, allowing a value to be repeated.
Definition Shuffle.h:559

◆ resampleWithFunctor() [2/4]

template<typename T , typename ActionFunctor >
void MooseUtils::resampleWithFunctor ( const std::vector< T > &  data,
const ActionFunctor &  functor,
MooseRandom &  generator,
const std::size_t  seed_index,
const libMesh::Parallel::Communicator &  comm 
)

Definition at line 579 of file Shuffle.h.

584{
585 return MooseUtils::resampleWithFunctor(data, functor, generator, seed_index, &comm);
586}

◆ resampleWithFunctor() [3/4]

template<typename T , typename ActionFunctor >
void MooseUtils::resampleWithFunctor ( const std::vector< T > &  data,
const ActionFunctor &  functor,
MooseRandom &  generator,
const std::size_t  seed_index,
const libMesh::Parallel::Communicator *  comm_ptr 
)

Definition at line 427 of file Shuffle.h.

432{
433 const std::size_t n_local = data.size();
434
435 if (!comm_ptr || comm_ptr->size() == 1)
436 {
437 for (std::size_t j = 0; j < n_local; ++j)
438 {
439 auto index = generator.randl(seed_index, 0, n_local);
440 functor(data[index]);
441 }
442 }
443 else
444 {
445 // Compute the global size of the vector
446 std::size_t n_global = n_local;
447 comm_ptr->sum(n_global);
448
449 // Compute the vector data offsets, the scope cleans up the "n_local" vector
450 std::vector<std::size_t> offsets(comm_ptr->size());
451 {
452 std::vector<std::size_t> local_sizes;
453 comm_ptr->allgather(n_local, local_sizes);
454 for (std::size_t i = 0; i < local_sizes.size() - 1; ++i)
455 offsets[i + 1] = offsets[i] + local_sizes[i];
456 }
457
458 // Advance the random number generator to the current offset
459 const auto rank = comm_ptr->rank();
460 for (std::size_t i = 0; i < offsets[rank]; ++i)
461 generator.randl(seed_index, 0, n_global);
462
463 // Compute the needs for this processor
464 std::unordered_map<processor_id_type, std::vector<std::size_t>> indices;
465 for (std::size_t i = 0; i < n_local; ++i)
466 {
467 const auto idx = generator.randl(seed_index, 0, n_global); // random global index
468
469 // Locate the rank and local index of the data desired
470 const auto idx_offset_iter = std::prev(std::upper_bound(offsets.begin(), offsets.end(), idx));
471 const auto idx_rank = std::distance(offsets.begin(), idx_offset_iter);
472 const auto idx_local_idx = idx - *idx_offset_iter;
473
474 // Push back the index to appropriate rank
475 indices[idx_rank].push_back(idx_local_idx);
476 }
477
478 // Advance the random number generator to the end of the global vector
479 for (std::size_t i = offsets[rank] + n_local; i < n_global; ++i)
480 generator.randl(seed_index, 0, n_global);
481
482 // Send the indices to the appropriate rank and have the calculator do its work
483 auto act_functor =
484 [&functor, &data](processor_id_type /*pid*/, const std::vector<std::size_t> & indices)
485 {
486 for (const auto & idx : indices)
487 functor(data[idx]);
488 };
489 Parallel::push_parallel_vector_data(*comm_ptr, indices, act_functor);
490 }
491}

◆ resampleWithFunctor() [4/4]

template<typename T , typename ActionFunctor >
void MooseUtils::resampleWithFunctor ( const std::vector< T > &  data,
const ActionFunctor &  functor,
MooseRandom &  generator,
const std::size_t  seed_index = 0 
)

Randomly resample a vector of data and apply a functor, allowing a value to be repeated.

Parameters
dataThe vector on which the values are to be swapped
functorFunctor to apply to each entry of the resampled vector
generatorRandom number generator to use for shuffle
seed_index(default: 0) The seed index to use for calls to randl
comm_ptrOptional Communicator, if provided and running with multiple processors the vector is assumed to be distributed

Definition at line 559 of file Shuffle.h.

563{
564 return MooseUtils::resampleWithFunctor(data, functor, generator, seed_index, nullptr);
565}

Referenced by resampleWithFunctor(), resampleWithFunctor(), and resampleWithFunctor().

◆ reset() [1/2]

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

Definition at line 28 of file SharedPool.h.

29{
30}

◆ reset() [2/2]

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

Definition at line 21 of file SharedPool.h.

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

Referenced by MooseUtils::SharedPool< T >::acquire().

◆ rsplit()

std::vector< std::string > MooseUtils::rsplit ( const std::string &  str,
const std::string &  delimiter,
std::size_t  max_count 
)

Definition at line 1103 of file MooseUtils.C.

1104{
1105 std::vector<std::string> output;
1106 std::size_t count = 0;
1107 size_t prev = str.length(), pos = str.length();
1108 do
1109 {
1110 pos = str.rfind(delimiter, prev);
1111 output.insert(output.begin(), str.substr(pos + delimiter.length(), prev - pos));
1112 prev = pos - delimiter.length();
1113 count += 1;
1114 } while (pos != std::string::npos && pos > 0 && count < max_count);
1115
1116 if (pos != std::string::npos)
1117 output.insert(output.begin(), str.substr(0, pos));
1118
1119 return output;
1120}
unsigned int count
Definition MortarUtils.C:53

◆ runTestsExecutable()

std::string MooseUtils::runTestsExecutable ( )

Definition at line 128 of file MooseUtils.C.

129{
130 auto build_loc = pathjoin(Moose::getExecutablePath(), "run_tests");
131 if (pathExists(build_loc) && checkFileReadable(build_loc))
132 return build_loc;
133 // TODO: maybe no path prefix - just moose_test_runner here?
134 return pathjoin(Moose::getExecutablePath(), "moose_test_runner");
135}

Referenced by MooseApp::runInputs().

◆ serialBegin()

void MooseUtils::serialBegin ( const libMesh::Parallel::Communicator &  comm,
bool  warn 
)

Definition at line 420 of file MooseUtils.C.

421{
422 // unless we are the first processor...
423 if (comm.rank() > 0)
424 {
425 // ...wait for the previous processor to finish
426 int dummy = 0;
427 comm.receive(comm.rank() - 1, dummy);
428 }
429 else if (warn)
430 mooseWarning("Entering serial execution block (use only for debugging)");
431}
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition MooseError.h:345

Referenced by SerializerGuard::SerializerGuard().

◆ serialEnd()

void MooseUtils::serialEnd ( const libMesh::Parallel::Communicator &  comm,
bool  warn 
)

Definition at line 434 of file MooseUtils.C.

435{
436 // unless we are the last processor...
437 if (comm.rank() + 1 < comm.size())
438 {
439 // ...notify the next processor of its turn
440 int dummy = 0;
441 comm.send(comm.rank() + 1, dummy);
442 }
443
444 comm.barrier();
445 if (comm.rank() == 0 && warn)
446 mooseWarning("Leaving serial execution block (use only for debugging)");
447}

Referenced by SerializerGuard::~SerializerGuard().

◆ shortName()

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

Definition at line 675 of file MooseUtils.C.

676{
677 return name.substr(name.find_last_of('/') != std::string::npos ? name.find_last_of('/') + 1 : 0);
678}

Referenced by InputParameterWarehouse::addInputParameters(), ActionFactory::create(), CSV::getVectorPostprocessorFileName(), CSV::getVectorPostprocessorFilePrefix(), and CSV::initialSetup().

◆ shuffle() [1/4]

template<typename T >
void MooseUtils::shuffle ( std::vector< T > &  data,
MooseRandom &  generator,
const libMesh::Parallel::Communicator &  comm 
)

Definition at line 512 of file Shuffle.h.

515{
516 return MooseUtils::shuffle(data, generator, 0, &comm);
517}
void shuffle(std::vector< T > &data, MooseRandom &generator, const std::size_t seed_index=0)
Shuffle function for serial or distributed vector of data that shuffles in place.
Definition Shuffle.h:505

◆ shuffle() [2/4]

template<typename T >
void MooseUtils::shuffle ( std::vector< T > &  data,
MooseRandom &  generator,
const std::size_t  seed_index,
const libMesh::Parallel::Communicator &  comm 
)

Definition at line 521 of file Shuffle.h.

525{
526 return MooseUtils::shuffle(data, generator, seed_index, &comm);
527}

◆ shuffle() [3/4]

template<typename T >
void MooseUtils::shuffle ( std::vector< T > &  data,
MooseRandom &  generator,
const std::size_t  seed_index,
const libMesh::Parallel::Communicator *  comm_ptr 
)

Definition at line 244 of file Shuffle.h.

248{
249 // REPLICATED data
250 if (!comm_ptr || comm_ptr->size() == 1)
251 {
252 std::size_t n_global = data.size();
253 for (std::size_t i = n_global - 1; i > 0; --i)
254 {
255 auto j = generator.randl(seed_index, 0, i);
256 MooseUtils::swap(data, i, j, nullptr);
257 }
258 }
259
260 // DISTRIBUTED data
261 else
262 {
263 // Local/global size
264 std::size_t n_local = data.size();
265 std::size_t n_global = n_local;
266 comm_ptr->sum(n_global);
267
268 // Compute the vector data offsets, the scope cleans up the "n_local" vector
269 std::vector<std::size_t> offsets(comm_ptr->size());
270 {
271 std::vector<std::size_t> local_sizes;
272 comm_ptr->allgather(n_local, local_sizes);
273 for (std::size_t i = 0; i < local_sizes.size() - 1; ++i)
274 offsets[i + 1] = offsets[i] + local_sizes[i];
275 }
276
277 // Perform swaps
278 auto rank = comm_ptr->rank();
279 for (std::size_t idx0 = n_global - 1; idx0 > 0; --idx0)
280 {
281 auto idx1 = generator.randl(seed_index, 0, idx0);
282
283 // Locate the rank and local index of the data to swap
284 auto idx0_offset_iter = std::prev(std::upper_bound(offsets.begin(), offsets.end(), idx0));
285 auto idx0_rank = std::distance(offsets.begin(), idx0_offset_iter);
286 auto idx0_local_idx = idx0 - *idx0_offset_iter;
287
288 auto idx1_offset_iter = std::prev(std::upper_bound(offsets.begin(), offsets.end(), idx1));
289 auto idx1_rank = std::distance(offsets.begin(), idx1_offset_iter);
290 auto idx1_local_idx = idx1 - *idx1_offset_iter;
291
292 // The values, if any, needed from other rank
293 std::unordered_map<processor_id_type, std::vector<std::size_t>> needs;
294 if (idx0_rank != rank && idx1_rank == rank)
295 needs[idx0_rank].push_back(idx0_local_idx);
296 if (idx0_rank == rank && idx1_rank != rank)
297 needs[idx1_rank].push_back(idx1_local_idx);
298
299 // Collect the values needed by this processor
300 std::unordered_map<processor_id_type, std::vector<T>> returns;
301 auto return_functor =
302 [&data, &returns](processor_id_type pid, const std::vector<std::size_t> & indices)
303 {
304 auto & returns_pid = returns[pid];
305 for (auto idx : indices)
306 returns_pid.push_back(data[idx]);
307 };
308 Parallel::push_parallel_vector_data(*comm_ptr, needs, return_functor);
309
310 // Receive needed values from the others processors
311 std::vector<T> incoming;
312 auto recv_functor = [&incoming](processor_id_type /*pid*/, const std::vector<T> & values)
313 { incoming = values; };
314 Parallel::push_parallel_vector_data(*comm_ptr, returns, recv_functor);
315
316 if (idx0_rank == rank && idx1_rank == rank)
317 MooseUtils::swap(data, idx0_local_idx, idx1_local_idx);
318
319 else if (idx0_rank == rank)
320 {
321 mooseAssert(incoming.size() == 1, "Only one value should be received");
322 data[idx0_local_idx] = incoming[0];
323 }
324 else if (idx1_rank == rank)
325 {
326 mooseAssert(incoming.size() == 1, "Only one value should be received");
327 data[idx1_local_idx] = incoming[0];
328 }
329 }
330 }
331}
void swap(std::vector< T > &data, const std::size_t idx0, const std::size_t idx1, const libMesh::Parallel::Communicator &comm)
Swap function for serial or distributed vector of data.
Definition Shuffle.h:495

◆ shuffle() [4/4]

template<typename T >
void MooseUtils::shuffle ( std::vector< T > &  data,
MooseRandom &  generator,
const std::size_t  seed_index = 0 
)

Shuffle function for serial or distributed vector of data that shuffles in place.

Parameters
dataThe vector on which the values are to be swapped
generatorRandom number generator to use for shuffle
seed_index(default: 0) The seed index to use for calls to randl
comm_ptrOptional Communicator, if provided and running with multiple processors the vector is assumed to be distributed

Both the serial and distributed version implement a Fisher-Yates shuffle https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

NOTE: This distributed shuffle I have here does a parallel communication with each swap pair generated. I am certain that there are more efficient ways to shuffle a distributed vector, but there doesn't seem to be an algorithm in the literature (my search was not extensive).

The reason I came to this conclusion was because of a 2019 paper, which states the following (https://iopscience.iop.org/article/10.1088/1742-6596/1196/1/012035):

The study also says that the Fisher-Yates Shuffle can be developed in two ways,
namely the algorithm's initial assumptions that allow for discrete uniform variables,
and also with the avent of large core clusters and GPUs, there is an interest in making
parallel versions of this algorithm.

This paper discusses the MergeShuffle (https://arxiv.org/abs/1508.03167), but that is a shared memory parallel algorithm.

Hence, if you want to become famous create a parallel Fisher-Yates algorithm for MPI.

Definition at line 505 of file Shuffle.h.

506{
507 return MooseUtils::shuffle(data, generator, seed_index, nullptr);
508}

Referenced by shuffle(), shuffle(), and shuffle().

◆ split()

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

Definition at line 1083 of file MooseUtils.C.

1084{
1085 std::vector<std::string> output;
1086 std::size_t count = 0;
1087 size_t prev = 0, pos = 0;
1088 do
1089 {
1090 pos = str.find(delimiter, prev);
1091 output.push_back(str.substr(prev, pos - prev));
1092 prev = pos + delimiter.length();
1093 count += 1;
1094 } while (pos != std::string::npos && count < max_count);
1095
1096 if (pos != std::string::npos)
1097 output.push_back(str.substr(prev));
1098
1099 return output;
1100}

Referenced by BatchMeshGeneratorAction::convertStringToCompoundRealScalar(), MeshGenerator::generateInternal(), MultiApp::getCommandLineArgs(), Moose::ParameterRegistration::setDoubleVectorValue(), and MooseApp::setMFEMDevice().

◆ startsWith()

bool MooseUtils::startsWith ( const std::string &  string1,
const std::string &  string2 
)

Definition at line 1242 of file MooseUtils.C.

1243{
1244 if (string2.size() > string1.size())
1245 return false;
1246 return string1.compare(0, string2.size(), string2) == 0;
1247}

Referenced by replaceStart().

◆ stringJoin()

std::string MooseUtils::stringJoin ( const std::vector< std::string > &  values,
const std::string &  separator = " " 
)
inline

Concatenates value into a single string separated by separator.

Definition at line 201 of file MooseStringUtils.h.

202{
203 std::string combined;
204 for (const auto & value : values)
205 combined += value + separator;
206 if (values.size())
207 combined = combined.substr(0, combined.size() - separator.size());
208 return combined;
209}

Referenced by InputParameters::addCommandLineParamHelper(), Moose::Builder::build(), InputParameters::checkParams(), Moose::Capability::enumerationToString(), EnumerateEvaler::eval(), RangeEvaler::eval(), RepeatEvaler::eval(), Parser::joinErrorMessages(), Parser::parse(), ParsedPostprocessor::ParsedPostprocessor(), MFEMProblem::solverTypeString(), and MeshInfo::validParams().

◆ stringToInteger()

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

Definition at line 1030 of file MooseUtils.C.

1031{
1032 return convert<int>(input, throw_on_failure);
1033}

Referenced by FormattedTable::printTable().

◆ stripExtension()

std::string MooseUtils::stripExtension ( const std::string &  s,
const bool  rfind 
)

Definition at line 490 of file MooseUtils.C.

491{
492 const std::string ext = getExtension(s, rfind);
493 const bool offset = (ext.size() != 0);
494 // -1 offset accounts for the extension's leading dot ("."), if there is an extension
495 return s.substr(0, s.size() - ext.size() - offset);
496}
std::string getExtension(const std::string &filename, const bool rfind)
Definition MooseUtils.C:474

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

◆ swap() [1/2]

template<typename T >
void MooseUtils::swap ( std::vector< T > &  data,
const std::size_t  idx0,
const std::size_t  idx1,
const libMesh::Parallel::Communicator &  comm 
)

Swap function for serial or distributed vector of data.

Parameters
dataThe vector on which the values are to be swapped
idx0,idx1The global indices to be swapped
comm_ptrOptional Communicator, if provided and running with multiple processors the vector is assumed to be distributed

Definition at line 495 of file Shuffle.h.

499{
500 MooseUtils::swap<T>(data, idx0, idx1, &comm);
501}

Referenced by shuffle(), and swap().

◆ swap() [2/2]

template<typename T >
void MooseUtils::swap ( std::vector< T > &  data,
const std::size_t  idx0,
const std::size_t  idx1,
const libMesh::Parallel::Communicator *  comm_ptr = nullptr 
)

Definition at line 156 of file Shuffle.h.

160{
161 if (!comm_ptr || comm_ptr->size() == 1)
162 {
163 mooseAssert(idx0 < data.size(),
164 "idx0 (" << idx0 << ") out of range, data.size() is " << data.size());
165 mooseAssert(idx1 < data.size(),
166 "idx1 (" << idx1 << ") out of range, data.size() is " << data.size());
167 std::swap(data[idx0], data[idx1]);
168 }
169
170 else
171 {
172 // Size of the local input data
173 const auto n_local = data.size();
174 const auto rank = comm_ptr->rank();
175
176 // Compute the global size of the vector
177 std::size_t n_global = n_local;
178 comm_ptr->sum(n_global);
179 mooseAssert(idx0 < n_global,
180 "idx0 (" << idx0 << ") out of range, the global data size is " << n_global);
181 mooseAssert(idx1 < n_global,
182 "idx1 (" << idx1 << ") out of range, the global data size is " << n_global);
183
184 // Compute the vector data offsets, the scope cleans up the "n_local" vector
185 std::vector<std::size_t> offsets(comm_ptr->size());
186 {
187 std::vector<std::size_t> local_sizes;
188 comm_ptr->allgather(n_local, local_sizes);
189 for (std::size_t i = 0; i < local_sizes.size() - 1; ++i)
190 offsets[i + 1] = offsets[i] + local_sizes[i];
191 }
192
193 // Locate the rank and local index of the data to swap
194 auto idx0_offset_iter = std::prev(std::upper_bound(offsets.begin(), offsets.end(), idx0));
195 auto idx0_rank = std::distance(offsets.begin(), idx0_offset_iter);
196 auto idx0_local_idx = idx0 - *idx0_offset_iter;
197
198 auto idx1_offset_iter = std::prev(std::upper_bound(offsets.begin(), offsets.end(), idx1));
199 auto idx1_rank = std::distance(offsets.begin(), idx1_offset_iter);
200 auto idx1_local_idx = idx1 - *idx1_offset_iter;
201
202 // The values, if any, needed from other rank
203 std::unordered_map<processor_id_type, std::vector<std::size_t>> needs;
204 if (idx0_rank != rank && idx1_rank == rank)
205 needs[idx0_rank].push_back(idx0_local_idx);
206 if (idx0_rank == rank && idx1_rank != rank)
207 needs[idx1_rank].push_back(idx1_local_idx);
208
209 // Collect the values needed by this processor
210 std::unordered_map<processor_id_type, std::vector<T>> returns;
211 auto return_functor =
212 [&data, &returns](processor_id_type pid, const std::vector<std::size_t> & indices)
213 {
214 auto & returns_pid = returns[pid];
215 for (auto idx : indices)
216 returns_pid.push_back(data[idx]);
217 };
218 Parallel::push_parallel_vector_data(*comm_ptr, needs, return_functor);
219
220 // Receive needed values from the others processors
221 std::vector<T> incoming;
222 auto recv_functor = [&incoming](processor_id_type /*pid*/, const std::vector<T> & values)
223 { incoming = values; };
224 Parallel::push_parallel_vector_data(*comm_ptr, returns, recv_functor);
225
226 if (idx0_rank == rank && idx1_rank == rank)
227 MooseUtils::swap(data, idx0_local_idx, idx1_local_idx);
228
229 else if (idx0_rank == rank)
230 {
231 mooseAssert(incoming.size() == 1, "Only one value should be received");
232 data[idx0_local_idx] = incoming[0];
233 }
234 else if (idx1_rank == rank)
235 {
236 mooseAssert(incoming.size() == 1, "Only one value should be received");
237 data[idx1_local_idx] = incoming[0];
238 }
239 }
240}

◆ 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 >= than the supplied value. T should be std::string or a MOOSE derived string class.

Definition at line 55 of file MooseStringUtils.h.

59{
60 elements.clear();
61
62 std::string::size_type last_pos = str.find_first_not_of(delims, 0);
63 std::string::size_type pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
64
65 while (last_pos != std::string::npos)
66 {
67 elements.push_back(str.substr(last_pos, pos - last_pos));
68 // skip delims between tokens
69 last_pos = str.find_first_not_of(delims, pos);
70 if (last_pos == std::string::npos)
71 break;
72 pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
73 }
74}

Referenced by InputParameters::addCommandLineParamHelper(), Syntax::addDependencySets(), MooseEnumBase::addEnumerationName(), MooseEnumBase::addEnumerationNames(), JsonInputFileFormatter::addLine(), JsonInputFileFormatter::addParameters(), InputParameters::addParamNamesToGroup(), MultiMooseEnum::eraseSetValue(), TransfiniteMeshGenerator::getDiscreteEdge(), MooseApp::getLibrarySearchPaths(), Moose::MFEM::CoefficientManager::getMatrixCoefficientPtr(), TransfiniteMeshGenerator::getParsedEdge(), Syntax::isAssociated(), makedirs(), MultiMooseEnum::operator=(), FunctionMaterialPropertyDescriptor< is_ad >::parseDependentSymbols(), FunctionMaterialPropertyDescriptor< is_ad >::parseDerivative(), pathContains(), InputFileFormatter::printParams(), MooseUtils::DelimitedFileReaderTempl< T >::readColumnData(), InputParameters::registerBuildableTypes(), removedirs(), MultiMooseEnum::setAdditionalValue(), CommandLine::setCommandLineParam(), Moose::ParameterRegistration::setTripleVectorValue(), MooseApp::showInputs(), SingleMatrixPreconditioner::SingleMatrixPreconditioner(), tokenizeAndConvert(), and wildCardMatch().

◆ 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 162 of file MooseStringUtils.h.

165{
166 std::vector<std::string> tokens;
167 MooseUtils::tokenize(str, tokens, 1, delimiter);
168 tokenized_vector.resize(tokens.size());
169 for (std::size_t i = 0; i < tokens.size(); ++i)
170 if (!convert<T>(tokens[i], tokenized_vector[i], false))
171 return false;
172 return true;
173}

Referenced by SplitMeshAction::act(), Moose::internal::CapabilityRegistry::check(), TransfiniteMeshGenerator::getCircarcEdge(), TransfiniteMeshGenerator::getDiscreteEdge(), Moose::MFEM::CoefficientManager::getMatrixCoefficientPtr(), and Moose::MFEM::CoefficientManager::getVectorCoefficientPtr().

◆ toLower()

std::string MooseUtils::toLower ( std::string  name)
inline

◆ toUpper()

std::string MooseUtils::toUpper ( std::string  name)
inline

◆ trim()

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

◆ underscoreToCamelCase()

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

Definition at line 643 of file MooseUtils.C.

644{
645 pcrecpp::StringPiece input(underscore_name);
646 pcrecpp::RE re("([^_]*)(_|$)");
647
648 std::string result;
649 std::string us, not_us;
650 bool make_upper = leading_upper_case;
651 while (re.Consume(&input, &not_us, &us))
652 {
653 if (not_us.length() > 0)
654 {
655 if (make_upper)
656 {
657 result += std::toupper(not_us[0]);
658 if (not_us.length() > 1)
659 result += not_us.substr(1);
660 }
661 else
662 result += not_us;
663 }
664 if (us == "")
665 break;
666
667 // Toggle flag so next match is upper cased
668 make_upper = true;
669 }
670
671 return result;
672}

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

◆ variableFEType()

libMesh::FEType MooseUtils::variableFEType ( const InputParameters &  params)

Definition at line 98 of file MooseUtils.C.

99{
100 const auto order =
101 libMesh::Utility::string_to_enum<libMesh::Order>(params.get<MooseEnum>("order"));
102 const auto family =
103 libMesh::Utility::string_to_enum<libMesh::FEFamily>(params.get<MooseEnum>("family"));
104
105 bool p_refinement = defaultPRefinement(order, family);
106 if (params.isParamValid("p_refinement"))
107 p_refinement = params.get<bool>("p_refinement");
108
109 if (params.isParamValid("disable_p_refinement"))
110 {
111 if (params.isParamSetByUser("p_refinement"))
112 params.paramError("disable_p_refinement",
113 "Cannot be supplied together with 'p_refinement'. Use "
114 "'p_refinement = false' instead.");
115 p_refinement = !params.get<bool>("disable_p_refinement");
116 }
117
118 return libMesh::FEType(order, family).set_p_refinement(p_refinement);
119}
bool isParamSetByUser(const std::string &name) const
Method returns true if the parameter was set by the user.
std::vector< std::pair< R1, R2 > > get(const std::string &param1, const std::string &param2) const
Combine two vector parameters into a single vector of pairs.
void paramError(const std::string &param, Args... args) const
Emits a parameter error prefixed with the parameter location and object information if available.
bool isParamValid(const std::string &name) const
This method returns parameters that have been initialized in one fashion or another,...
This is a "smart" enum class intended to replace many of the shortcomings in the C++ enum type It sho...
Definition MooseEnum.h:55
FEType set_p_refinement(bool p) &

Referenced by FEProblemBase::addAuxVariable(), AuxiliarySystem::addVariable(), SystemBase::addVariable(), FEProblemBase::addVariable(), and AddVariableAction::feType().

◆ wildCardMatch()

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

Definition at line 951 of file MooseUtils.C.

952{
953 // Assume that an empty string matches anything
954 if (search_string == "")
955 return true;
956
957 // transform to lower for case insenstive matching
958 std::transform(name.begin(), name.end(), name.begin(), (int (*)(int))std::toupper);
959 std::transform(search_string.begin(),
960 search_string.end(),
961 search_string.begin(),
962 (int (*)(int))std::toupper);
963
964 // exact match!
965 if (search_string.find("*") == std::string::npos)
966 return search_string == name;
967
968 // wildcard
969 std::vector<std::string> tokens;
970 MooseUtils::tokenize(search_string, tokens, 1, "*");
971
972 size_t pos = 0;
973 for (unsigned int i = 0; i < tokens.size() && pos != std::string::npos; ++i)
974 {
975 pos = name.find(tokens[i], pos);
976 // See if we have a leading wildcard
977 if (search_string[0] != '*' && i == 0 && pos != 0)
978 return false;
979 }
980
981 if (pos != std::string::npos && tokens.size() > 0)
982 {
983 // Now see if we have a trailing wildcard
984 size_t last_token_length = tokens.back().length();
985 if (*search_string.rbegin() == '*' || pos == name.size() - last_token_length)
986 return true;
987 else
988 return false;
989 }
990 else
991 return false;
992}

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