https://mooseframework.inl.gov
Classes | Typedefs | Functions
MooseUtils Namespace Reference

Classes

struct  AnyType
 Comparison helpers that support the MooseUtils::Any wildcard which will match any value. More...
 
class  Buffer
 Base class for a buffer. More...
 
struct  canBroadcast
 Custom type trait that has a value of true for types that can be broadcasted. More...
 
class  CircularBuffer
 An optimized circular buffer. More...
 
class  DelimitedFileReaderTempl
 Utility class for reading delimited data (e.g., CSV data). More...
 
class  Has_size
 Taken from https://stackoverflow.com/a/257382 Evaluating constexpr (Has_size<T>::value) in a templated method over class T will return whether T is a standard container or a singleton. More...
 
struct  IsLikeReal
 Custom type trait that has a value of true for types that cam be use interchangeably with Real. More...
 
struct  IsLikeReal< ADReal >
 
struct  IsLikeReal< Real >
 
class  LIFOBuffer
 An optimized LIFO (Last In First Out) buffer. More...
 
class  SemidynamicVector
 Utility class template for a semidynamic vector with a maximum size N and a chosen dynamic size. 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=" \\\)
 Standard scripting language trim function. More...
 
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<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. More...
 
template<typename T >
bool tokenizeAndConvert (const std::string &str, std::vector< T > &tokenized_vector, const std::string &delimiter=" \\\)
 tokenizeAndConvert splits a string using delimiter and then converts to type T. More...
 
std::string toUpper (std::string name)
 Convert supplied string to upper case. More...
 
std::string toLower (std::string name)
 Convert supplied string to lower case. More...
 
std::filesystem::path pathjoin (const std::filesystem::path &p)
 
template<typename... Args>
std::filesystem::path pathjoin (const std::filesystem::path &p, Args... args)
 
bool parsesToReal (const std::string &input, Real *parsed_real=nullptr)
 Check if the input string can be parsed into a Real. More...
 
std::string runTestsExecutable ()
 Returns the location of either a local repo run_tests script - or an installed test executor script if run_tests isn't found. More...
 
std::string findTestRoot ()
 Searches in the current working directory and then recursively up in each parent directory looking for a "testroot" file. More...
 
std::string installedInputsDir (const std::string &app_name, const std::string &dir_name, const std::string &extra_error_msg="")
 Returns the directory of any installed inputs or the empty string if none are found. More...
 
std::string docsDir (const std::string &app_name)
 Returns the directory of any installed docs/site. More...
 
std::string mooseDocsURL (const std::string &path)
 Returns the URL of a page located on the MOOSE documentation site. More...
 
std::string replaceAll (std::string str, const std::string &from, const std::string &to)
 Replaces all occurrences of from in str with to and returns the result. More...
 
std::string convertLatestCheckpoint (std::string orig)
 Replaces "LATEST" placeholders with the latest checkpoint file name. More...
 
int levenshteinDist (const std::string &s1, const std::string &s2)
 Computes and returns the Levenshtein distance between strings s1 and s2. More...
 
void escape (std::string &str)
 This function will escape all of the standard C++ escape characters so that they can be printed. More...
 
std::string removeExtraWhitespace (const std::string &str)
 Removes additional whitespace from a string. More...
 
std::vector< std::string > split (const std::string &str, const std::string &delimiter, std::size_t max_count=std::numeric_limits< std::size_t >::max())
 Python like split functions for strings. More...
 
std::vector< std::string > rsplit (const std::string &str, const std::string &delimiter, std::size_t max_count=std::numeric_limits< std::size_t >::max())
 
template<typename Iterator >
std::string join (Iterator begin, Iterator end, const std::string &delimiter)
 Python-like join function for strings over an iterator range. More...
 
template<typename T >
std::string join (const T &strings, const std::string &delimiter)
 Python-like join function for strings over a container. More...
 
std::size_t fileSize (const std::string &filename)
 Check the file size. More...
 
bool pathContains (const std::string &expression, const std::string &string_to_find, const std::string &delims="/")
 This function tokenizes a path and checks to see if it contains the string to look for. More...
 
bool checkFileReadable (const std::string &filename, bool check_line_endings=false, bool throw_on_unreadable=true, bool check_for_git_lfs_pointer=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...
 
bool checkForGitLFSPointer (std::ifstream &file)
 Check if the file is a Git-LFS pointer. More...
 
void parallelBarrierNotify (const libMesh::Parallel::Communicator &comm, bool messaging=true)
 This function implements a parallel barrier function but writes progress to stdout. More...
 
void serialBegin (const libMesh::Parallel::Communicator &comm, bool warn=true)
 This function marks the begin of a section of code that is executed in serial rank by rank. More...
 
void serialEnd (const libMesh::Parallel::Communicator &comm, bool warn=true)
 Closes a section of code that is executed in serial rank by rank, and that was opened with a call to serialBegin. More...
 
bool hasExtension (const std::string &filename, std::string ext, bool strip_exodus_ext=false)
 Function tests if the supplied filename as the desired extension. More...
 
std::string getExtension (const std::string &filename, const bool rfind=false)
 Gets the extension of the passed file name. More...
 
std::string stripExtension (const std::string &s, const bool rfind=false)
 Removes any file extension from the given string s (i.e. More...
 
template<typename T >
std::pair< std::filesystem::path, std::filesystem::path > splitFileName (const T &full_file)
 Function for splitting path and filename. More...
 
std::string getCurrentWorkingDir ()
 Returns the current working directory as a string. More...
 
void makedirs (const std::string &dir_name, bool throw_on_failure=false)
 Recursively make directories. More...
 
void removedirs (const std::string &dir_name, bool throw_on_failure=false)
 Recursively remove directories from inner-most when the directories are empty. More...
 
std::string camelCaseToUnderscore (const std::string &camel_case_name)
 Function for converting a camel case name to a name containing underscores. More...
 
std::string underscoreToCamelCase (const std::string &underscore_name, bool leading_upper_case)
 Function for converting an underscore name to a camel case name. More...
 
std::string shortName (const std::string &name)
 Function for stripping name after the file / in parser block. More...
 
std::string baseName (const std::string &name)
 Function for string the information before the final / in a parser block. More...
 
std::string hostname ()
 Get the hostname the current process is running on. More...
 
unsigned short getTermWidth (bool use_environment)
 Returns the width of the terminal using sys/ioctl. More...
 
std::string prettyCppType (const std::string &cpp_type)
 
template<typename T >
std::string prettyCppType (const T *obj=nullptr)
 
template<typename T1 , typename T2 >
bool doesMapContainValue (const std::map< T1, T2 > &the_map, const T2 &value)
 This routine is a simple helper function for searching a map by values instead of keys. More...
 
template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool absoluteFuzzyEqual (const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether two variables are equal within an absolute tolerance. More...
 
template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool absoluteFuzzyGreaterEqual (const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether a variable is greater than or equal to another variable within an absolute tolerance. More...
 
template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool absoluteFuzzyGreaterThan (const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether a variable is greater than another variable within an absolute tolerance. More...
 
template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool absoluteFuzzyLessEqual (const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether a variable is less than or equal to another variable within an absolute tolerance. More...
 
template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool absoluteFuzzyLessThan (const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether a variable is less than another variable within an absolute tolerance. More...
 
template<typename T , typename T2 , typename T3 = Real>
bool relativeFuzzyEqual (const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether two variables are equal within a relative tolerance. More...
 
template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool relativeFuzzyGreaterEqual (const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether a variable is greater than or equal to another variable within a relative tolerance. More...
 
template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool relativeFuzzyGreaterThan (const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether a variable is greater than another variable within a relative tolerance. More...
 
template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool relativeFuzzyLessEqual (const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether a variable is less than or equal to another variable within a relative tolerance. More...
 
template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool relativeFuzzyLessThan (const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether a variable is less than another variable within a relative tolerance. More...
 
template<typename T >
void getUnion (const std::vector< T > &vector1, const std::vector< T > &vector2, std::vector< T > &common)
 Function which takes the union of vector1 and vector2 and copies them to common . More...
 
template<typename T >
bool isZero (const T &value, const Real tolerance=TOLERANCE *TOLERANCE *TOLERANCE)
 
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, bool dont_indent_first_line=true, const std::string &post_prefix=": ")
 Indents the supplied message given the prefix and color. More...
 
std::string & removeColor (std::string &msg)
 remove ANSI escape sequences for terminal color from msg More...
 
std::list< std::string > listDir (const std::string path, bool files_only=false)
 
bool pathExists (const std::string &path)
 
std::list< std::string > getFilesInDirs (const std::list< std::string > &directory_list, const bool files_only=true)
 Retrieves the names of all of the files contained within the list of directories passed into the routine. More...
 
std::string getLatestCheckpointFilePrefix (const std::list< std::string > &checkpoint_files)
 Returns the most recent checkpoint prefix (the four numbers at the beginning) If a suitable file isn't found the empty string is returned. More...
 
bool wildCardMatch (std::string name, std::string search_string)
 
bool globCompare (const std::string &candidate, const std::string &pattern, std::size_t c=0, std::size_t p=0)
 
template<typename T >
void expandAllMatches (const std::vector< T > &candidates, std::vector< T > &patterns)
 
template<typename T >
convert (const std::string &str, bool throw_on_failure=false)
 Takes the string representation of a value and converts it to the value. More...
 
void createSymlink (const std::string &target, const std::string &link)
 Create a symbolic link, if the link already exists it is replaced. More...
 
void clearSymlink (const std::string &link)
 Remove a symbolic link, if the given filename is a link. More...
 
template<typename T >
concatenate (T c1, const T &c2)
 Returns a container that contains the content of second passed in container inserted into the first passed in container (set or map union). More...
 
template<typename T >
std::vector< T > concatenate (std::vector< T > c1, const std::vector< T > &c2)
 Returns a vector that contains is the concatenation of the two passed in vectors. More...
 
template<typename T >
std::vector< T > concatenate (std::vector< T > c1, const T &item)
 Returns the passed in vector with the item appended to it. More...
 
std::string stringJoin (const std::vector< std::string > &values, const std::string &separator=" ")
 Concatenates value into a single string separated by separator. More...
 
bool beginsWith (const std::string &value, const std::string &begin_value)
 
template<typename T >
int numDigits (const T &num)
 Return the number of digits for a number. More...
 
ExecFlagEnum getDefaultExecFlagEnum ()
 Return the default ExecFlagEnum for MOOSE. More...
 
int stringToInteger (const std::string &input, bool throw_on_failure=false)
 Robust string to integer conversion that fails for cases such at "1foo". More...
 
void linearPartitionItems (dof_id_type num_items, dof_id_type num_chunks, dof_id_type chunk_id, dof_id_type &num_local_items, dof_id_type &local_items_begin, dof_id_type &local_items_end)
 Linearly partition a number of items. More...
 
processor_id_type linearPartitionChunk (dof_id_type num_items, dof_id_type num_chunks, dof_id_type item_id)
 Return the chunk_id that is assigned to handle item_id. More...
 
std::string realpath (const std::string &path)
 Wrapper around PetscGetRealPath, which is a cross-platform replacement for realpath. More...
 
template<typename C , typename It , typename M1 , typename M2 >
auto findPair (C &container, It start_iterator, const M1 &first, const M2 &second)
 Find a specific pair in a container matching on first, second or both pair components. More...
 
libMesh::BoundingBox buildBoundingBox (const Point &p1, const Point &p2)
 Construct a valid bounding box from 2 arbitrary points. More...
 
template<typename T >
T * get (const std::unique_ptr< T > &u)
 The MooseUtils::get() specializations are used to support making forwards-compatible code changes from dumb pointers to smart pointers. More...
 
template<typename T >
T * get (T *p)
 
template<typename T >
T * get (const std::shared_ptr< T > &s)
 
template<class InputIterator >
bool setsIntersect (InputIterator first1, InputIterator last1, InputIterator first2, InputIterator last2)
 This method detects whether two sets intersect without building a result set. More...
 
template<class T >
bool setsIntersect (const T &s1, const T &s2)
 
bool isDigits (const std::string &str)
 Courtesy https://stackoverflow.com/a/8889045 and https://en.cppreference.com/w/cpp/string/byte/isdigit. More...
 
bool isFloat (const std::string &str)
 Courtesy https://stackoverflow.com/a/57163016 and https://stackoverflow.com/questions/447206/c-isfloat-function. More...
 
std::string canonicalPath (const std::string &path)
 Gets the canonical path of the given path. More...
 
bool startsWith (const std::string &string1, const std::string &string2)
 
void replaceStart (std::string &string1, const std::string &string2, const std::string &string3)
 Replace the starting string string2 of string1 with string3. More...
 
bool isAllLowercase (const std::string &str)
 
template<class T , typename... Args>
auto reset (int, T &obj, Args... args) -> decltype(obj.reset(args...), void())
 
template<class T , typename... Args>
void reset (double, T &, Args...)
 
void addLineBreaks (std::string &message, unsigned int line_width)
 
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. More...
 
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. More...
 
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. More...
 
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. More...
 
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)
 
static const struct MooseUtils::AnyType Any
 
template<typename T1 , typename T2 >
bool wildcardEqual (const T1 &a, const T2 &b)
 
template<typename T >
bool wildcardEqual (const T &, AnyType)
 
template<typename T >
bool wildcardEqual (AnyType, const T &)
 

Typedef Documentation

◆ DelimitedFileOfStringReader

Definition at line 201 of file DelimitedFileReader.h.

◆ DelimitedFileReader

Definition at line 200 of file DelimitedFileReader.h.

Function Documentation

◆ absoluteFuzzyEqual()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::absoluteFuzzyEqual ( const T &  var1,
const T2 &  var2,
const T3 &  tol = libMesh::TOLERANCE * libMesh::TOLERANCE 
)

Function to check whether two variables are equal within an absolute tolerance.

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

Definition at line 382 of file MooseUtils.h.

Referenced by MultiAppGeneralFieldTransfer::acceptPointInOriginMesh(), FormattedTable::addData(), MultiAppVariableValueSamplePostprocessorTransfer::cacheElemToPostprocessorData(), MultiAppGeneralFieldTransfer::cacheIncomingInterpVals(), CartesianGridDivision::CartesianGridDivision(), MeshDiagnosticsGenerator::checkNonConformalMeshFromAdaptivity(), MeshDiagnosticsGenerator::checkNonPlanarSides(), CircularBoundaryCorrectionGenerator::circularCenterCalculator(), MultiAppGeneralFieldTransfer::closestToPosition(), CSG::CSGPlane::coeffsFromPoints(), ComparisonPostprocessor::comparisonIsTrue(), VariableCondensationPreconditioner::computeDInverseDiag(), ThresholdElementSubdomainModifier::computeSubdomainID(), TimesEnableControl::conditionMet(), ParsedConvergence::convertRealToBool(), CylindricalGridDivision::CylindricalGridDivision(), MultiAppGeneralFieldTransfer::detectConflict(), SphericalGridDivision::divisionIndex(), CartesianGridDivision::divisionIndex(), CylindricalGridDivision::divisionIndex(), MultiAppGeneralFieldNearestLocationTransfer::evaluateInterpValuesNearestNode(), MultiAppGeneralFieldTransfer::examineLocalValueConflicts(), MultiAppGeneralFieldTransfer::examineReceivedValueConflicts(), PIDChainControl::execute(), RealToBoolChainControl::execute(), SmootherChainControl::execute(), MatrixSymmetryCheck::execute(), PointValue::execute(), FindValueOnLine::execute(), FillBetweenPointVectorsTools::fillBetweenPointVectorsGenerator(), MeshDivisionFunctorReductionVectorPostprocessor::finalize(), Moose::findContactPoint(), BicubicInterpolation::findInterval(), MeshRepairGenerator::fixOverlappingNodes(), Boundary2DDelaunayGenerator::General2DDelaunay(), AdvancedExtruderGenerator::generate(), CircularBoundaryCorrectionGenerator::generate(), ParsedCurveGenerator::generate(), CircularBoundaryCorrectionGenerator::generateRadialCorrectionFactor(), FunctorBinnedValuesDivision::getBinIndex(), TransfiniteMeshGenerator::getEdge(), MultiAppGeneralFieldTransfer::getRestrictedFromBoundingBoxes(), AverageVariableChange::getValue(), SideAverageValue::getValue(), RelativeDifferencePostprocessor::getValue(), LineValueSampler::getValue(), Moose::FV::greenGaussGradient(), MooseAppCoordTransform::hasScalingOrRotationTransformation(), AutomaticMortarGeneration::householderOrthogolization(), ElementGroupCentroidPositions::initialize(), MooseVariableBase::initialSetup(), LinearInterpolation::integratePartial(), MooseMeshUtils::isCoPlanar(), ActivateElementsCoupled::isElementActivated(), MultiAppCoordTransform::isIdentity(), RankTwoTensorTempl< Real >::isSymmetric(), isZero(), MooseMeshXYCuttingUtils::lineRemoverCutElemTri(), MooseMeshXYCuttingUtils::lineRemoverMoveNode(), LineValueSampler::LineValueSampler(), FillBetweenPointVectorsTools::needFlip(), CutMeshByLevelSetGeneratorBase::nonDuplicateNodeCreator(), EigenExecutionerBase::normalizeSolution(), MultiAppCoordTransform::operator()(), RankTwoTensorTempl< Real >::operator==(), TableOutput::outputReporter(), FixedPointSolve::performingRelaxation(), PointIndexedMap::PointIndexedMap(), CutMeshByLevelSetGeneratorBase::pointPairLevelSetInterception(), RankTwoTensorTempl< Real >::positiveProjectionEigenDecomposition(), EigenExecutionerBase::postExecute(), EigenProblem::preScaleEigenVector(), MooseMeshXYCuttingUtils::quasiTriElementsFixer(), CoarsenBlockGenerator::recursiveCoarsen(), relativeFuzzyEqual(), BicubicInterpolation::sample2ndDerivative(), BicubicInterpolation::sampleDerivative(), BicubicInterpolation::sampleValueAndDerivativesInternal(), TimeSequenceStepperBase::setupSequence(), Predictor::shouldApply(), TableOutput::shouldOutputPostprocessorsRow(), SphericalGridDivision::SphericalGridDivision(), SymmetryTransformGenerator::SymmetryTransformGenerator(), CutMeshByLevelSetGeneratorBase::tet4ElemCutter(), TimeIntervalTimes::TimeIntervalTimes(), SecantSolve::transformPostprocessors(), SteffensenSolve::transformPostprocessors(), SecantSolve::transformVariables(), SteffensenSolve::transformVariables(), MooseMeshXYCuttingUtils::triElemSplitter(), ParsedCurveGenerator::tSectionSpaceDefiner(), PIDChainControl::updateValues(), Axisymmetric2D3DSolutionFunction::value(), and XYMeshLineCutter::XYMeshLineCutter().

385 {
386  return (std::abs(MetaPhysicL::raw_value(var1) - MetaPhysicL::raw_value(var2)) <=
388 }
MetaPhysicL::DualNumber< V, D, asd > abs(const MetaPhysicL::DualNumber< V, D, asd > &a)
Definition: EigenADReal.h:42
auto raw_value(const Eigen::Map< T > &in)
Definition: EigenADReal.h:73

◆ absoluteFuzzyGreaterEqual()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::absoluteFuzzyGreaterEqual ( const T &  var1,
const T2 &  var2,
const T3 &  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

Definition at line 406 of file MooseUtils.h.

Referenced by TimeSequenceStepperBase::acceptStep(), ComparisonPostprocessor::comparisonIsTrue(), TimePeriod::conditionMet(), CylindricalGridDivision::divisionIndex(), SphericalGridDivision::divisionIndex(), CartesianGridDivision::divisionIndex(), PlaneIDMeshGenerator::PlaneIDMeshGenerator(), and relativeFuzzyGreaterEqual().

409 {
410  return (MetaPhysicL::raw_value(var1) >=
412 }
auto raw_value(const Eigen::Map< T > &in)
Definition: EigenADReal.h:73

◆ absoluteFuzzyGreaterThan()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::absoluteFuzzyGreaterThan ( const T &  var1,
const T2 &  var2,
const T3 &  tol = libMesh::TOLERANCE * libMesh::TOLERANCE 
)

◆ absoluteFuzzyLessEqual()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::absoluteFuzzyLessEqual ( const T &  var1,
const T2 &  var2,
const T3 &  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

Definition at line 454 of file MooseUtils.h.

Referenced by MultiAppConservativeTransfer::adjustTransferredSolution(), MultiAppConservativeTransfer::adjustTransferredSolutionNearestPoint(), ComparisonPostprocessor::comparisonIsTrue(), FunctorBinnedValuesDivision::FunctorBinnedValuesDivision(), relativeFuzzyLessEqual(), and TimeIntervalTimes::TimeIntervalTimes().

457 {
458  return (MetaPhysicL::raw_value(var1) <=
460 }
auto raw_value(const Eigen::Map< T > &in)
Definition: EigenADReal.h:73

◆ absoluteFuzzyLessThan()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::absoluteFuzzyLessThan ( const T &  var1,
const T2 &  var2,
const T3 &  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

Definition at line 477 of file MooseUtils.h.

Referenced by FormattedTable::addData(), MultiAppVariableValueSamplePostprocessorTransfer::cacheElemToPostprocessorData(), ComparisonPostprocessor::comparisonIsTrue(), TimePeriod::conditionMet(), CartesianGridDivision::divisionIndex(), SphericalGridDivision::divisionIndex(), CylindricalGridDivision::divisionIndex(), Boundary2DDelaunayGenerator::General2DDelaunay(), CSG::CSGSurface::getHalfspaceFromPoint(), CutMeshByLevelSetGeneratorBase::pointLevelSetRelation(), and relativeFuzzyLessThan().

480 {
481  return (MetaPhysicL::raw_value(var1) <
483 }
auto raw_value(const Eigen::Map< T > &in)
Definition: EigenADReal.h:73

◆ addLineBreaks()

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

Definition at line 730 of file MooseUtils.C.

732 {
733  for (auto i : make_range(int(message.length() / line_width)))
734  message.insert((i + 1) * (line_width + 2) - 2, "\n");
735 }
IntRange< T > make_range(T beg, T end)

◆ baseName()

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

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

Definition at line 618 of file MooseUtils.C.

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

619 {
620  return name.substr(0, name.find_last_of('/') != std::string::npos ? name.find_last_of('/') : 0);
621 }
std::string name(const ElemQuality q)

◆ beginsWith()

bool MooseUtils::beginsWith ( const std::string &  value,
const std::string &  begin_value 
)
Returns
Whether or not value begins with begin_value

Definition at line 966 of file MooseUtils.C.

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

967 {
968  return value.rfind(begin_value, 0) == 0;
969 }
Real value(unsigned n, unsigned alpha, unsigned beta, Real x)

◆ buildBoundingBox()

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

Construct a valid bounding box from 2 arbitrary points.

If you have 2 points in space and you wish to construct a bounding box, you should use this method to avoid unexpected behavior of the underlying BoundingBox class in libMesh. BoundingBox class expect 2 points whose coordinates are "sorted" (i.e., x-, y- and -z coordinates of the first point are smaller then the corresponding coordinates of the second point). If this "sorting" is not present, the BoundingBox class will build an empty box and any further testing of points inside the box will fail. This method will allow you to obtain the correct bounding box for any valid combination of 2 corner points of a box.

Parameters
p1First corner of the constructed bounding box
p2Second corner of the constructed bounding box
Returns
Valid bounding box

Definition at line 1142 of file MooseUtils.C.

Referenced by PropertyReadFile::PropertyReadFile().

1143 {
1144  BoundingBox bb;
1145  bb.union_with(p1);
1146  bb.union_with(p2);
1147  return bb;
1148 }

◆ camelCaseToUnderscore()

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

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

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

Definition at line 568 of file MooseUtils.C.

Referenced by MooseApp::appNameToLibName().

569 {
570  std::string replaced = camel_case_name;
571  // Put underscores in front of each contiguous set of capital letters
572  pcrecpp::RE("(?!^)(?<![A-Z_])([A-Z]+)").GlobalReplace("_\\1", &replaced);
573 
574  // Convert all capital letters to lower case
575  std::transform(replaced.begin(), replaced.end(), replaced.begin(), ::tolower);
576  return replaced;
577 }

◆ canonicalPath()

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

Gets the canonical path of the given path.

Definition at line 1171 of file MooseUtils.C.

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

1172 {
1173  return std::filesystem::weakly_canonical(path).c_str();
1174 }

◆ checkFileReadable()

bool MooseUtils::checkFileReadable ( const std::string &  filename,
bool  check_line_endings = false,
bool  throw_on_unreadable = true,
bool  check_for_git_lfs_pointer = 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
check_for_git_lfs_pointerWhether or not to call a subroutine utility to make sure that the file in question is not actually a git-lfs pointer.
Returns
a Boolean indicating whether the file exists and is readable

Definition at line 254 of file MooseUtils.C.

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

258 {
259  std::ifstream in(filename.c_str(), std::ifstream::in);
260  if (in.fail())
261  {
262  if (throw_on_unreadable)
263  mooseError(
264  (std::string("Unable to open file \"") + filename +
265  std::string("\". Check to make sure that it exists and that you have read permission."))
266  .c_str());
267  else
268  return false;
269  }
270 
271  if (check_line_endings)
272  {
273  std::istream_iterator<char> iter(in);
274  std::istream_iterator<char> eos;
275  in >> std::noskipws;
276  while (iter != eos)
277  if (*iter++ == '\r')
278  mooseError(filename + " contains Windows(DOS) line endings which are not supported.");
279  }
280 
281  if (check_for_git_lfs_pointer && checkForGitLFSPointer(in))
282  mooseError(filename + " appears to be a Git-LFS pointer. Make sure you have \"git-lfs\" "
283  "installed so that you may pull this file.");
284  in.close();
285 
286  return true;
287 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
bool checkForGitLFSPointer(std::ifstream &file)
Check if the file is a Git-LFS pointer.
Definition: MooseUtils.C:290

◆ checkFileWriteable()

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

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

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

Definition at line 307 of file MooseUtils.C.

Referenced by PNGOutput::makePNG().

308 {
309  std::ofstream out(filename.c_str(), std::ios_base::app);
310  if (out.fail())
311  {
312  if (throw_on_unwritable)
313  mooseError(
314  (std::string("Unable to open file \"") + filename +
315  std::string("\". Check to make sure that it exists and that you have write permission."))
316  .c_str());
317  else
318  return false;
319  }
320 
321  out.close();
322 
323  return true;
324 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
OStreamProxy out

◆ checkForGitLFSPointer()

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

Check if the file is a Git-LFS pointer.

When using a repository that utilizes Git-LFS, it's possible that the client may not have the right packages installed in which case the clone will contain plain-text files with key information for retrieving the actual (large) files. This can cause odd errors since the file technically exists, is readable, and even has the right name/extension. However, the content of the file will not match the expected content.

Parameters
fileA pointer to the open filestream.

Definition at line 290 of file MooseUtils.C.

Referenced by checkFileReadable().

291 {
292  mooseAssert(file.is_open(), "Passed in file handle is not open");
293 
294  std::string line;
295 
296  // git-lfs pointer files contain several name value pairs. The specification states that the
297  // first name/value pair must be "version {url}". We'll do a simplified check for that.
298  file.seekg(0);
299  std::getline(file, line);
300  if (line.find("version https://") != std::string::npos)
301  return true;
302  else
303  return false;
304 }

◆ clearSymlink()

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

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

Definition at line 1084 of file MooseUtils.C.

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

1085 {
1086 #ifndef __WIN32__
1087  struct stat sbuf;
1088  if (lstat(link.c_str(), &sbuf) == 0)
1089  {
1090  auto err = unlink(link.c_str());
1091  if (err != 0)
1092  mooseError("Failed to remove symbolic link (via 'unlink') to ", link);
1093  }
1094 #else
1095  auto attr = GetFileAttributesA(link.c_str());
1096  if (attr != INVALID_FILE_ATTRIBUTES)
1097  {
1098  auto err = _unlink(link.c_str());
1099  if (err != 0)
1100  mooseError("Failed to remove link/file (via '_unlink') to ", link);
1101  }
1102 #endif
1103 }
OStreamProxy err
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323

◆ concatenate() [1/3]

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

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

Definition at line 879 of file MooseUtils.h.

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

880 {
881  c1.insert(c2.begin(), c2.end());
882  return c1;
883 }

◆ concatenate() [2/3]

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

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

Definition at line 890 of file MooseUtils.h.

891 {
892  c1.insert(c1.end(), c2.begin(), c2.end());
893  return c1;
894 }

◆ concatenate() [3/3]

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

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

Definition at line 901 of file MooseUtils.h.

902 {
903  c1.push_back(item);
904  return c1;
905 }

◆ convert() [1/2]

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.

Referenced by convert(), and MooseServer::getDocumentSymbolKind().

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 name(const ElemQuality q)
Real value(unsigned n, unsigned alpha, unsigned beta, Real x)
std::string trim(const std::string &str, const std::string &white_space=" \\\)
Standard scripting language trim function.
std::string demangle(const char *name)

◆ convert() [2/2]

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

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

See the convert method in MooseStringUtils.h for more information on handling of each case.

Parameters
strThe string to convert from
throw_on_failureIf true, throw on a failure to convert, otherwise use mooseError
Returns
The converted value on success

Definition at line 847 of file MooseUtils.h.

848 {
849  T val;
850  try
851  {
852  convert(str, val, true);
853  }
854  catch (std::exception const & e)
855  {
856  if (throw_on_failure)
857  throw;
858  mooseError(e.what());
859  }
860  return val;
861 }
T convert(const std::string &str, bool throw_on_failure=false)
Takes the string representation of a value and converts it to the value.
Definition: MooseUtils.h:847
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323

◆ convertLatestCheckpoint()

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

Replaces "LATEST" placeholders with the latest checkpoint file name.

Definition at line 157 of file MooseUtils.C.

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

158 {
159  auto slash_pos = orig.find_last_of("/");
160  auto path = orig.substr(0, slash_pos);
161  auto file = orig.substr(slash_pos + 1);
162  if (file != "LATEST")
163  return orig;
164 
166 
167  if (converted.empty())
168  mooseError("Unable to find suitable recovery file!");
169 
170  return converted;
171 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
std::string getLatestCheckpointFilePrefix(const std::list< std::string > &checkpoint_files)
Returns the most recent checkpoint prefix (the four numbers at the beginning) If a suitable file isn&#39;...
Definition: MooseUtils.C:819
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:782

◆ createSymlink()

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

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

Definition at line 1071 of file MooseUtils.C.

Referenced by CSV::output().

1072 {
1073  clearSymlink(link);
1074 #ifndef __WIN32__
1075  auto err = symlink(target.c_str(), link.c_str());
1076 #else
1077  auto err = CreateSymbolicLink(target.c_str(), link.c_str(), 0);
1078 #endif
1079  if (err)
1080  mooseError("Failed to create symbolic link (via 'symlink') from ", target, " to ", link);
1081 }
OStreamProxy err
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
void clearSymlink(const std::string &link)
Remove a symbolic link, if the given filename is a link.
Definition: MooseUtils.C:1084

◆ docsDir()

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

Returns the directory of any installed docs/site.

Definition at line 125 of file MooseUtils.C.

Referenced by MooseApp::run().

126 {
127  // See moose.mk for a detailed explanation of the assumed installed application
128  // layout. Installed docs are expected to be installed in "share/<app_name>/doc".
129  // The binary, which has a defined location will be in "bin", a peer directory to "share".
130  std::string installed_path = pathjoin(Moose::getExecutablePath(), "..", "share", app_name, "doc");
131 
132  auto docfile = pathjoin(installed_path, "css", "moose.css");
133  if (pathExists(docfile) && checkFileReadable(docfile))
134  return installed_path;
135  return "";
136 }
std::string getExecutablePath()
Gets the directory the running executable is on Mac OS X and linux.
bool checkFileReadable(const std::string &filename, bool check_line_endings=false, bool throw_on_unreadable=true, bool check_for_git_lfs_pointer=true)
Checks to see if a file is readable (exists and permissions)
Definition: MooseUtils.C:254
std::filesystem::path pathjoin(const std::filesystem::path &p)
Definition: MooseUtils.C:59
bool pathExists(const std::string &path)
Definition: MooseUtils.C:247

◆ doesMapContainValue()

template<typename T1 , typename T2 >
bool MooseUtils::doesMapContainValue ( const std::map< T1, T2 > &  the_map,
const T2 &  value 
)

This routine is a simple helper function for searching a map by values instead of keys.

Definition at line 358 of file MooseUtils.h.

Referenced by MooseMeshUtils::getBoundaryIDs().

359 {
360  for (typename std::map<T1, T2>::const_iterator iter = the_map.begin(); iter != the_map.end();
361  ++iter)
362  if (iter->second == value)
363  return true;
364  return false;
365 }

◆ escape()

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

This function will escape all of the standard C++ escape characters so that they can be printed.

The passed in parameter is modified in place

Definition at line 207 of file MooseUtils.C.

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

208 {
209  std::map<char, std::string> escapes;
210  escapes['\a'] = "\\a";
211  escapes['\b'] = "\\b";
212  escapes['\f'] = "\\f";
213  escapes['\n'] = "\\n";
214  escapes['\t'] = "\\t";
215  escapes['\v'] = "\\v";
216  escapes['\r'] = "\\r";
217 
218  for (const auto & it : escapes)
219  for (size_t pos = 0; (pos = str.find(it.first, pos)) != std::string::npos;
220  pos += it.second.size())
221  str.replace(pos, 1, it.second);
222 }

◆ expandAllMatches()

template<typename T >
void MooseUtils::expandAllMatches ( const std::vector< T > &  candidates,
std::vector< T > &  patterns 
)

Definition at line 817 of file MooseUtils.h.

Referenced by SingleMatrixPreconditioner::SingleMatrixPreconditioner().

818 {
819  std::set<T> expanded;
820  for (const auto & p : patterns)
821  {
822  unsigned int found = 0;
823  for (const auto & c : candidates)
824  if (globCompare(c, p))
825  {
826  expanded.insert(c);
827  found++;
828  }
829  if (!found)
830  throw std::invalid_argument(p);
831  }
832  patterns.assign(expanded.begin(), expanded.end());
833 }
bool globCompare(const std::string &candidate, const std::string &pattern, std::size_t c=0, std::size_t p=0)
Definition: MooseUtils.C:932

◆ fileSize()

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

Check the file size.

Definition at line 1106 of file MooseUtils.C.

Referenced by Exodus::output().

1107 {
1108 #ifndef __WIN32__
1109  struct stat buffer;
1110  if (!stat(filename.c_str(), &buffer))
1111  return buffer.st_size;
1112 #else
1113  HANDLE hFile = CreateFile(filename.c_str(),
1114  GENERIC_READ,
1115  FILE_SHARE_READ | FILE_SHARE_WRITE,
1116  NULL,
1117  OPEN_EXISTING,
1118  FILE_ATTRIBUTE_NORMAL,
1119  NULL);
1120  if (hFile == INVALID_HANDLE_VALUE)
1121  return 0;
1122 
1123  LARGE_INTEGER size;
1124  if (GetFileSizeEx(hFile, &size))
1125  {
1126  CloseHandle(hFile);
1127  return size.QuadPart;
1128  }
1129 
1130  CloseHandle(hFile);
1131 #endif
1132  return 0;
1133 }

◆ findPair()

template<typename C , typename It , typename M1 , typename M2 >
auto MooseUtils::findPair ( C &  container,
It  start_iterator,
const M1 &  first,
const M2 &  second 
)

Find a specific pair in a container matching on first, second or both pair components.

Definition at line 1041 of file MooseUtils.h.

Referenced by Moose::PetscSupport::addPetscPairsToPetscOptions(), and Moose::PetscSupport::isSNESVI().

1042 {
1043  return std::find_if(start_iterator,
1044  container.end(),
1045  [&](auto & item) {
1046  return wildcardEqual(first, item.first) &&
1047  wildcardEqual(second, item.second);
1048  });
1049 }
bool wildcardEqual(AnyType, const T &)
Definition: MooseUtils.h:1030

◆ findTestRoot()

std::string MooseUtils::findTestRoot ( )

Searches in the current working directory and then recursively up in each parent directory looking for a "testroot" file.

Returns the full path to the first testroot file found.

Definition at line 75 of file MooseUtils.C.

Referenced by MooseApp::runInputs().

76 {
77  std::string path = ".";
78  for (int i = 0; i < 5; i++)
79  {
80  auto testroot = pathjoin(path, "testroot");
81  if (pathExists(testroot) && checkFileReadable(testroot))
82  return testroot;
83  path += "/..";
84  }
85  return "";
86 }
bool checkFileReadable(const std::string &filename, bool check_line_endings=false, bool throw_on_unreadable=true, bool check_for_git_lfs_pointer=true)
Checks to see if a file is readable (exists and permissions)
Definition: MooseUtils.C:254
std::filesystem::path pathjoin(const std::filesystem::path &p)
Definition: MooseUtils.C:59
bool pathExists(const std::string &path)
Definition: MooseUtils.C:247

◆ get() [1/3]

template<typename T >
T* MooseUtils::get ( const std::unique_ptr< T > &  u)

The MooseUtils::get() specializations are used to support making forwards-compatible code changes from dumb pointers to smart pointers.

The same line of code, e.g.

libMesh::Parameters::Value * value = MooseUtils::get(map_iter->second);

will then work regardless of whether map_iter->second is a dumb pointer or a smart pointer. Note that the smart pointer get() functions are const so they can be (ab)used to get a non-const pointer to the underlying resource. We are simply following this convention here.

Definition at line 1135 of file MooseUtils.h.

Referenced by InputParameterWarehouse::addInputParameters(), JsonSyntaxTree::buildOptions(), YAMLFormatter::buildOutputString(), JsonSyntaxTree::buildOutputString(), RestartableDataIO::currentData(), and RestartableDataIO::dataSize().

1136 {
1137  return u.get();
1138 }

◆ get() [2/3]

template<typename T >
T* MooseUtils::get ( T *  p)

Definition at line 1142 of file MooseUtils.h.

1143 {
1144  return p;
1145 }

◆ get() [3/3]

template<typename T >
T* MooseUtils::get ( const std::shared_ptr< T > &  s)

Definition at line 1149 of file MooseUtils.h.

1150 {
1151  return s.get();
1152 }

◆ getCurrentWorkingDir()

std::string MooseUtils::getCurrentWorkingDir ( )

Returns the current working directory as a string.

If there's a problem obtaining the current working directory, this function just returns an empty string. It doesn't not throw.

Definition at line 436 of file MooseUtils.C.

Referenced by MooseApp::runInputs().

437 {
438  // Note: At the time of creating this method, our minimum compiler still
439  // does not support <filesystem>. Additionally, the inclusion of that header
440  // requires an additional library to be linked so for now, we'll just
441  // use the Unix standard library to get us the cwd().
442  constexpr unsigned int BUF_SIZE = 1024;
443  char buffer[BUF_SIZE];
444 
445  return getcwd(buffer, BUF_SIZE) != nullptr ? buffer : "";
446 }

◆ getDefaultExecFlagEnum()

ExecFlagEnum MooseUtils::getDefaultExecFlagEnum ( )

◆ getExtension()

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

Gets the extension of the passed file name.

Parameters
filenameThe filename of which to get the extension
rfindWhen true, searches for last "." in filename. Otherwise, searches for first "."
Returns
file_ext The extension of filename (does not include the leading "."). If filename has no extension, returns "".

Definition at line 411 of file MooseUtils.C.

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

412 {
413  std::string file_ext = "";
414  if (filename != "")
415  {
416  // The next line splits filename at the last "/" and gives the file name after "/"
417  const std::string stripped_filename = splitFileName<std::string>(filename).second;
418  auto pos = rfind ? stripped_filename.rfind(".") : stripped_filename.find(".");
419  if (pos != std::string::npos)
420  file_ext += stripped_filename.substr(pos + 1, std::string::npos);
421  }
422 
423  return file_ext;
424 }

◆ getFilesInDirs()

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

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.
file_onlyWhether or not to list only files

Definition at line 808 of file MooseUtils.C.

Referenced by MooseApp::getCheckpointFiles().

809 {
810  std::list<std::string> files;
811 
812  for (const auto & dir_name : directory_list)
813  files.splice(files.end(), listDir(dir_name, files_only));
814 
815  return files;
816 }
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:782

◆ getLatestCheckpointFilePrefix()

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

Returns the most recent checkpoint prefix (the four numbers at the beginning) If a suitable file isn't found the empty string is returned.

Parameters
checkpoint_filesthe list of files to analyze

Definition at line 819 of file MooseUtils.C.

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

820 {
821  // Create storage for newest restart files
822  // Note that these might have the same modification time if the simulation was fast.
823  // In that case we're going to save all of the "newest" files and sort it out momentarily
824  std::time_t newest_time = 0;
825  std::list<std::string> newest_restart_files;
826 
827  // Loop through all possible files and store the newest
828  for (const auto & cp_file : checkpoint_files)
829  {
830  if (MooseUtils::hasExtension(cp_file, "rd"))
831  {
832  struct stat stats;
833  stat(cp_file.c_str(), &stats);
834 
835  std::time_t mod_time = stats.st_mtime;
836  if (mod_time > newest_time)
837  {
838  newest_restart_files.clear(); // If the modification time is greater, clear the list
839  newest_time = mod_time;
840  }
841 
842  if (mod_time == newest_time)
843  newest_restart_files.push_back(cp_file);
844  }
845  }
846 
847  // Loop through all of the newest files according the number in the file name
848  int max_file_num = -1;
849  std::string max_file;
850  std::string max_prefix;
851 
852  // Pull out the path including the number and the number itself
853  // This takes something_blah_out_cp/0024-restart-1.rd
854  // and returns "something_blah_out_cp/0024" as the "prefix"
855  // and then "24" as the number itself
856  pcrecpp::RE re_file_num("(.*?(\\d+))-restart-\\d+.rd$");
857 
858  // Now, out of the newest files find the one with the largest number in it
859  for (const auto & res_file : newest_restart_files)
860  {
861  int file_num = 0;
862 
863  // All of the file up to and including the digits
864  std::string file_prefix;
865 
866  re_file_num.FullMatch(res_file, &file_prefix, &file_num);
867 
868  if (file_num > max_file_num)
869  {
870  // Need both the header and the data
871  if (!RestartableDataReader::isAvailable(res_file))
872  continue;
873 
874  max_file_num = file_num;
875  max_file = res_file;
876  max_prefix = file_prefix;
877  }
878  }
879 
880  // Error if nothing was located
881  if (max_file_num == -1)
882  mooseError("No checkpoint file found!");
883 
884  return max_prefix;
885 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
bool hasExtension(const std::string &filename, std::string ext, bool strip_exodus_ext=false)
Function tests if the supplied filename as the desired extension.
Definition: MooseUtils.C:387
static bool isAvailable(const std::filesystem::path &folder_base)

◆ getTermWidth()

unsigned short MooseUtils::getTermWidth ( bool  use_environment)

Returns the width of the terminal using sys/ioctl.

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

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

Definition at line 640 of file MooseUtils.C.

Referenced by FormattedTable::printTable().

641 {
642 #ifndef __WIN32__
643  struct winsize w;
644 #else
645  struct
646  {
647  unsigned short ws_col;
648  } w;
649 #endif
650 
655 
656  if (use_environment)
657  {
658  char * pps_width = std::getenv("MOOSE_PPS_WIDTH");
659  if (pps_width != NULL)
660  {
661  std::stringstream ss(pps_width);
662  ss >> w.ws_col;
663  }
664  }
665  // Default to AUTO if no environment variable was set
667  {
668 #ifndef __WIN32__
669  try
670  {
671  ioctl(0, TIOCGWINSZ, &w);
672  }
673  catch (...)
674 #endif
675  {
676  }
677  }
678 
679  // Something bad happened, make sure we have a sane value
680  // 132 seems good for medium sized screens, and is available as a GNOME preset
682  w.ws_col = 132;
683 
684  return w.ws_col;
685 }
auto max(const L &left, const R &right)

◆ getUnion()

template<typename T >
void MooseUtils::getUnion ( const std::vector< T > &  vector1,
const std::vector< T > &  vector2,
std::vector< T > &  common 
)

Function which takes the union of vector1 and vector2 and copies them to common .

Depending on the vector size and data type this can be very expensive!

Definition at line 647 of file MooseUtils.h.

Referenced by ComputeLinearFVElementalThread::fetchBlockSystemContributionObjects(), ComputeLinearFVFaceThread::fetchBlockSystemContributionObjects(), ComputeLinearFVElementalThread::setupSystemContributionObjects(), and ComputeLinearFVFaceThread::setupSystemContributionObjects().

648 {
649  std::unordered_set<T> unique_elements;
650  unique_elements.reserve(vector1.size() + vector2.size());
651 
652  for (const T & entry : vector1)
653  unique_elements.insert(entry);
654  for (const T & entry : vector2)
655  unique_elements.insert(entry);
656 
657  // Now populate the common vector with the union
658  common.clear();
659  common.assign(unique_elements.begin(), unique_elements.end());
660 }

◆ globCompare()

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

Definition at line 932 of file MooseUtils.C.

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

936 {
937  if (p == pattern.size())
938  return c == candidate.size();
939 
940  if (pattern[p] == '*')
941  {
942  for (; c < candidate.size(); ++c)
943  if (globCompare(candidate, pattern, c, p + 1))
944  return true;
945  return globCompare(candidate, pattern, c, p + 1);
946  }
947 
948  if (pattern[p] != '?' && pattern[p] != candidate[c])
949  return false;
950 
951  return globCompare(candidate, pattern, c + 1, p + 1);
952 }
bool globCompare(const std::string &candidate, const std::string &pattern, std::size_t c=0, std::size_t p=0)
Definition: MooseUtils.C:932

◆ hasExtension()

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

Function tests if the supplied filename as the desired extension.

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

Definition at line 387 of file MooseUtils.C.

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

388 {
389  // Extract the extension, w/o the '.'
390  std::string file_ext;
391  if (strip_exodus_ext)
392  {
393  pcrecpp::RE re(
394  ".*\\.([^\\.]*?)(?:-s\\d+)?\\s*$"); // capture the complete extension, ignoring -s*
395  re.FullMatch(filename, &file_ext);
396  }
397  else
398  {
399  pcrecpp::RE re(".*\\.([^\\.]*?)\\s*$"); // capture the complete extension
400  re.FullMatch(filename, &file_ext);
401  }
402 
403  // Perform the comparision
404  if (file_ext == ext)
405  return true;
406  else
407  return false;
408 }

◆ hostname()

std::string MooseUtils::hostname ( )

Get the hostname the current process is running on.

Definition at line 624 of file MooseUtils.C.

625 {
626  char hostname[1024];
627  hostname[1023] = '\0';
628 #ifndef __WIN32__
629  if (gethostname(hostname, 1023))
630  mooseError("Failed to retrieve hostname!");
631 #else
632  DWORD dwSize = sizeof(hostname);
633  if (!GetComputerNameEx(ComputerNamePhysicalDnsHostname, hostname, &dwSize))
634  mooseError("Failed to retrieve hostname!");
635 #endif
636  return hostname;
637 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
std::string hostname()
Get the hostname the current process is running on.
Definition: MooseUtils.C:624

◆ indentMessage()

void MooseUtils::indentMessage ( const std::string &  prefix,
std::string &  message,
const char *  color = COLOR_CYAN,
bool  dont_indent_first_line = true,
const std::string &  post_prefix = ": " 
)

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)
indent_first_lineIf true this will indent the first line too (default)
post_prefixA string to append right after the prefix, defaults to a column and a space

Takes a message like the following and indents it with another color code (see below)

Input message: 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 Nonlinear |R| = COLOR_GREEN 1.0e-10 COLOR_DEFAULT

Not indenting the first line is useful in the case where the first line is actually finishing the line before it.

Definition at line 738 of file MooseUtils.C.

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

743 {
744  // First we need to see if the message we need to indent (with color) also contains color codes
745  // that span lines.
746  // The code matches all of the XTERM constants (see XTermConstants.h). If it does, then we'll work
747  // on formatting
748  // each colored multiline chunk one at a time with the right codes.
749  std::string colored_message;
750  std::string curr_color = COLOR_DEFAULT; // tracks last color code before newline
751  std::string line, color_code;
752 
753  bool ends_in_newline = message.empty() ? true : message.back() == '\n';
754 
755  bool first = true;
756 
757  std::istringstream iss(message);
758  for (std::string line; std::getline(iss, line);) // loop over each line
759  {
760  const static pcrecpp::RE match_color(".*(\\33\\[3\\dm)((?!\\33\\[3\\d)[^\n])*");
761  pcrecpp::StringPiece line_piece(line);
762  match_color.FindAndConsume(&line_piece, &color_code);
763 
764  if (!first || indent_first_line)
765  colored_message += color + prefix + post_prefix + curr_color;
766 
767  colored_message += line;
768 
769  // Only add a newline to the last line if it had one to begin with!
770  if (!iss.eof() || ends_in_newline)
771  colored_message += "\n";
772 
773  if (!color_code.empty())
774  curr_color = color_code; // remember last color of this line
775 
776  first = false;
777  }
778  message = colored_message;
779 }

◆ installedInputsDir()

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

Returns the directory of any installed inputs or the empty string if none are found.

Definition at line 103 of file MooseUtils.C.

Referenced by MooseApp::copyInputs().

106 {
107  // See moose.mk for a detailed explanation of the assumed installed application
108  // layout. Installed inputs are expected to be installed in "share/<app_name>/<folder>".
109  // The binary, which has a defined location will be in "bin", a peer directory to "share".
110  std::string installed_path =
111  pathjoin(Moose::getExecutablePath(), "..", "share", app_name, dir_name);
112 
113  auto test_root = pathjoin(installed_path, "testroot");
114  if (!pathExists(installed_path))
115  mooseError("Couldn't locate any installed inputs to copy in path: ",
116  installed_path,
117  '\n',
118  extra_error_msg);
119 
120  checkFileReadable(test_root);
121  return installed_path;
122 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
std::string getExecutablePath()
Gets the directory the running executable is on Mac OS X and linux.
bool checkFileReadable(const std::string &filename, bool check_line_endings=false, bool throw_on_unreadable=true, bool check_for_git_lfs_pointer=true)
Checks to see if a file is readable (exists and permissions)
Definition: MooseUtils.C:254
std::filesystem::path pathjoin(const std::filesystem::path &p)
Definition: MooseUtils.C:59
bool pathExists(const std::string &path)
Definition: MooseUtils.C:247

◆ isAllLowercase()

bool MooseUtils::isAllLowercase ( const std::string &  str)
Returns
whether every alphabetic character in a string is lower-case

Definition at line 1193 of file MooseUtils.C.

1194 {
1195  return std::all_of(
1196  str.begin(), str.end(), [](unsigned char c) { return !std::isalpha(c) || std::islower(c); });
1197 }

◆ isDigits()

bool MooseUtils::isDigits ( const std::string &  str)
inline

Courtesy https://stackoverflow.com/a/8889045 and https://en.cppreference.com/w/cpp/string/byte/isdigit.

Returns
Whether every character in the string is a digit

Definition at line 1188 of file MooseUtils.h.

Referenced by RenameBlockGenerator::generate(), RenameBoundaryGenerator::generate(), SideSetsFromNodeSetsGenerator::generate(), XYZDelaunayGenerator::generate(), MooseMeshUtils::getBoundaryID(), MooseMeshUtils::getBoundaryIDs(), MooseMeshUtils::getIDFromName(), and MooseMeshUtils::getSubdomainID().

1189 {
1190  return std::all_of(str.begin(), str.end(), [](unsigned char c) { return std::isdigit(c); });
1191 }

◆ isFloat()

bool MooseUtils::isFloat ( const std::string &  str)
inline

Courtesy https://stackoverflow.com/a/57163016 and https://stackoverflow.com/questions/447206/c-isfloat-function.

Returns
Whether the string is convertible to a float

Definition at line 1199 of file MooseUtils.h.

Referenced by ChainControlParsedFunctionWrapper::initializeFunctionInputs().

1200 {
1201  if (str.empty())
1202  return false;
1203  char * ptr;
1204  strtof(str.c_str(), &ptr);
1205  return (*ptr) == '\0';
1206 }

◆ isZero()

template<typename T >
bool MooseUtils::isZero ( const T &  value,
const Real  tolerance = TOLERANCE * TOLERANCE * TOLERANCE 
)
Parameters
valueThe quantity to test for zero-ness
toleranceThe tolerance for testing zero-ness. The default is 1e-18 for double precision configurations of libMesh/MOOSE
Returns
whether the L_infty norm of the value is (close enough to) zero

Definition at line 693 of file MooseUtils.h.

Referenced by MathUtils::barycentricToCartesian2D(), MathUtils::barycentricToCartesian3D(), MathUtils::circumcenter2D(), MathUtils::circumcenter3D(), LinearFVAdvectionDiffusionFunctorRobinBC::computeBoundaryNormalGradient(), and LinearFVAdvectionDiffusionFunctorRobinBC::LinearFVAdvectionDiffusionFunctorRobinBC().

694 {
695  if constexpr (Has_size<T>::value)
696  {
697  for (const auto & element : value)
698  if (!isZero(element, tolerance))
699  return false;
700 
701  return true;
702  }
703  else if constexpr (libMesh::TensorTools::TensorTraits<T>::rank == 0)
704  return MooseUtils::absoluteFuzzyEqual(MetaPhysicL::raw_value(value), 0, tolerance);
705  else if constexpr (libMesh::TensorTools::TensorTraits<T>::rank == 1)
706  {
707  for (const auto i : make_range(Moose::dim))
709  return false;
710 
711  return true;
712  }
713  else if constexpr (libMesh::TensorTools::TensorTraits<T>::rank == 2)
714  {
715  for (const auto i : make_range(Moose::dim))
716  for (const auto j : make_range(Moose::dim))
718  return false;
719 
720  return true;
721  }
722 }
bool absoluteFuzzyEqual(const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
Function to check whether two variables are equal within an absolute tolerance.
Definition: MooseUtils.h:382
bool isZero(const T &value, const Real tolerance=TOLERANCE *TOLERANCE *TOLERANCE)
Definition: MooseUtils.h:693
auto raw_value(const Eigen::Map< T > &in)
Definition: EigenADReal.h:73
static constexpr std::size_t dim
This is the dimension of all vector and tensor datastructures used in MOOSE.
Definition: Moose.h:162
We need to instantiate the following CompareTypes to tell the compiler that ADReal is a subtype of Ch...
The following methods are specializations for using the libMesh::Parallel::packed_range_* routines fo...
Real value(unsigned n, unsigned alpha, unsigned beta, Real x)
if(!dmm->_nl) SETERRQ(PETSC_COMM_WORLD
IntRange< T > make_range(T beg, T end)

◆ join() [1/2]

template<typename Iterator >
std::string MooseUtils::join ( Iterator  begin,
Iterator  end,
const std::string &  delimiter 
)

Python-like join function for strings over an iterator range.

Definition at line 144 of file MooseUtils.h.

Referenced by MooseObjectWarehouseBase< Indicator >::activeObjectsToFormattedString(), BatchMeshGeneratorAction::BatchMeshGeneratorAction(), boundaryIntegrityCheckError(), ControllableParameter::checkExecuteOnType(), MeshGeneratorSystem::createAddedMeshGenerators(), MeshGeneratorSystem::createMeshGeneratorOrder(), DependencyResolverInterface::cyclicDependencyError(), MaterialBase::declareGenericPropertyByName(), Moose::Kokkos::MaterialBase::declareKokkosPropertyByName(), MaterialPropertyInterface::getBlockMaterialProperty(), Material::getGenericMaterialPropertyByName(), MaterialPropertyInterface::getGenericMaterialPropertyByName(), MaterialPropertyInterface::getKokkosMaterialPropertyByName(), Syntax::getSortedTask(), TransientBase::getTimeIntegratorNames(), MaterialPropertyInterface::hasADMaterialPropertyByName(), MaterialPropertyInterface::hasKokkosMaterialPropertyByName(), MaterialPropertyInterface::hasMaterialPropertyByName(), ParsedConvergence::initialSetup(), SubProblem::initialSetup(), join(), ConsoleUtils::mooseObjectVectorToString(), NEML2Action::NEML2Action(), MaterialPropertyDebugOutput::output(), ConsoleUtils::outputExecutionInformation(), MooseApp::setMFEMDevice(), CreateExecutionerAction::setupAutoPreconditioning(), and SubProblem::showFunctorRequestors().

145 {
146  std::ostringstream oss;
147  std::copy(begin, end, infix_ostream_iterator<std::string>(oss, delimiter.c_str()));
148  return oss.str();
149 }
charT const * delimiter
Definition: InfixIterator.h:34

◆ join() [2/2]

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

Python-like join function for strings over a container.

Definition at line 156 of file MooseUtils.h.

157 {
158  return join(strings.begin(), strings.end(), delimiter);
159 }
charT const * delimiter
Definition: InfixIterator.h:34
std::string join(const T &strings, const std::string &delimiter)
Python-like join function for strings over a container.
Definition: MooseUtils.h:156

◆ levenshteinDist()

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

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

Definition at line 176 of file MooseUtils.C.

Referenced by Moose::findSimilar().

177 {
178  // To change the type this function manipulates and returns, change
179  // the return type and the types of the two variables below.
180  auto s1len = s1.size();
181  auto s2len = s2.size();
182 
183  auto column_start = (decltype(s1len))1;
184 
185  auto column = new decltype(s1len)[s1len + 1];
186  std::iota(column + column_start, column + s1len + 1, column_start);
187 
188  for (auto x = column_start; x <= s2len; x++)
189  {
190  column[0] = x;
191  auto last_diagonal = x - column_start;
192  for (auto y = column_start; y <= s1len; y++)
193  {
194  auto old_diagonal = column[y];
195  auto possibilities = {
196  column[y] + 1, column[y - 1] + 1, last_diagonal + (s1[y - 1] == s2[x - 1] ? 0 : 1)};
197  column[y] = std::min(possibilities);
198  last_diagonal = old_diagonal;
199  }
200  }
201  auto result = column[s1len];
202  delete[] column;
203  return result;
204 }
auto min(const L &left, const R &right)

◆ linearPartitionChunk()

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

Return the chunk_id that is assigned to handle item_id.

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

Definition at line 1010 of file MooseUtils.C.

Referenced by DistributedRectilinearMeshGenerator::buildCube().

1011 {
1012  auto global_num_local_items = num_items / num_chunks;
1013 
1014  auto leftovers = num_items % num_chunks;
1015 
1016  auto first_item_past_first_part = leftovers * (global_num_local_items + 1);
1017 
1018  // Is it in the first section (that gets an extra item)
1019  if (item_id < first_item_past_first_part)
1020  return item_id / (global_num_local_items + 1);
1021  else
1022  {
1023  auto new_item_id = item_id - first_item_past_first_part;
1024 
1025  // First chunk after the first section + the number of chunks after that
1026  return leftovers + (new_item_id / global_num_local_items);
1027  }
1028 }

◆ linearPartitionItems()

void MooseUtils::linearPartitionItems ( dof_id_type  num_items,
dof_id_type  num_chunks,
dof_id_type  chunk_id,
dof_id_type num_local_items,
dof_id_type local_items_begin,
dof_id_type local_items_end 
)

Linearly partition a number of items.

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

Definition at line 984 of file MooseUtils.C.

Referenced by DistributedRectilinearMeshGenerator::buildCube().

990 {
991  auto global_num_local_items = num_items / num_chunks;
992 
993  num_local_items = global_num_local_items;
994 
995  auto leftovers = num_items % num_chunks;
996 
997  if (chunk_id < leftovers)
998  {
999  num_local_items++;
1000  local_items_begin = num_local_items * chunk_id;
1001  }
1002  else
1003  local_items_begin =
1004  (global_num_local_items + 1) * leftovers + global_num_local_items * (chunk_id - leftovers);
1005 
1006  local_items_end = local_items_begin + num_local_items;
1007 }

◆ listDir()

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

Definition at line 782 of file MooseUtils.C.

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

783 {
784  std::list<std::string> files;
785 
786  tinydir_dir dir;
787  dir.has_next = 0; // Avoid a garbage value in has_next (clang StaticAnalysis)
788  tinydir_open(&dir, path.c_str());
789 
790  while (dir.has_next)
791  {
792  tinydir_file file;
793  file.is_dir = 0; // Avoid a garbage value in is_dir (clang StaticAnalysis)
794  tinydir_readfile(&dir, &file);
795 
796  if (!files_only || !file.is_dir)
797  files.push_back(path + "/" + file.name);
798 
799  tinydir_next(&dir);
800  }
801 
802  tinydir_close(&dir);
803 
804  return files;
805 }

◆ makedirs()

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

Recursively make directories.

Parameters
dir_nameA complete path
throw_on_failureTrue to throw instead of error out when creating a directory is failed.

The path can be relative like 'a/b/c' or absolute like '/a/b/c'. The path is allowed to contain '.' or '..'.

Definition at line 449 of file MooseUtils.C.

450 {
451  // split path into directories with delimiter '/'
452  std::vector<std::string> split_dir_names;
453  MooseUtils::tokenize(dir_name, split_dir_names);
454 
455  auto n = split_dir_names.size();
456 
457  // remove '.' and '..' when possible
458  auto i = n;
459  i = 0;
460  while (i != n)
461  {
462  if (split_dir_names[i] == ".")
463  {
464  for (auto j = i + 1; j < n; ++j)
465  split_dir_names[j - 1] = split_dir_names[j];
466  --n;
467  }
468  else if (i > 0 && split_dir_names[i] == ".." && split_dir_names[i - 1] != "..")
469  {
470  for (auto j = i + 1; j < n; ++j)
471  split_dir_names[j - 2] = split_dir_names[j];
472  n -= 2;
473  --i;
474  }
475  else
476  ++i;
477  }
478  if (n == 0)
479  return;
480 
481  split_dir_names.resize(n);
482 
483  // start creating directories recursively
484  std::string cur_dir = dir_name[0] == '/' ? "" : ".";
485  for (auto & dir : split_dir_names)
486  {
487  cur_dir += "/" + dir;
488 
489  if (!pathExists(cur_dir))
490  {
491  auto code = Utility::mkdir(cur_dir.c_str());
492  if (code != 0)
493  {
494  std::string msg = "Failed creating directory " + dir_name;
495  if (throw_on_failure)
496  throw std::invalid_argument(msg);
497  else
498  mooseError(msg);
499  }
500  }
501  }
502 }
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 ...
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
int mkdir(const char *pathname)
bool pathExists(const std::string &path)
Definition: MooseUtils.C:247

◆ MaterialPropertyStorageDump()

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

Function to dump the contents of MaterialPropertyStorage for debugging purposes.

Parameters
propsThe storage item to dump, this should be MaterialPropertyStorage.props(state)

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

690 {
691  // Loop through the elements
692  for (const auto & elem_it : props)
693  {
694  Moose::out << "Element " << elem_it.first->id() << '\n';
695 
696  // Loop through the sides
697  for (const auto & side_it : elem_it.second)
698  {
699  Moose::out << " Side " << side_it.first << '\n';
700 
701  // Loop over properties
702  unsigned int cnt = 0;
703  for (const auto & mat_prop : side_it.second)
704  {
705  if (auto mp = dynamic_cast<const MaterialProperty<Real> *>(&mat_prop))
706  {
707  Moose::out << " Property " << cnt << '\n';
708  cnt++;
709 
710  // Loop over quadrature points
711  for (unsigned int qp = 0; qp < mp->size(); ++qp)
712  Moose::out << " prop[" << qp << "] = " << (*mp)[qp] << '\n';
713  }
714  }
715  }
716  }
717 
718  Moose::out << std::flush;
719 }

◆ mooseDocsURL()

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

Returns the URL of a page located on the MOOSE documentation site.

Parameters
[in]pathURL path following the domain name. For example, in the URL "www.example.com/folder1/folder2/file.html", this would be "folder1/folder2/file.html".

Definition at line 139 of file MooseUtils.C.

Referenced by ExecFlagEnum::getDocString().

140 {
141  return "https://mooseframework.inl.gov/" + path;
142 }

◆ numDigits()

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

Return the number of digits for a number.

This can foster quite a large discussion: https://stackoverflow.com/questions/1489830/efficient-way-to-determine-number-of-digits-in-an-integer

For our purposes I like the following algorithm.

Definition at line 928 of file MooseUtils.h.

Referenced by XMLOutput::filename(), JSONOutput::filename(), CSV::getVectorPostprocessorFileName(), CSV::output(), MooseUtils::DelimitedFileReaderTempl< T >::readColumnData(), and MooseUtils::DelimitedFileReaderTempl< T >::readRowData().

929 {
930  return num > 9 ? static_cast<int>(std::log10(static_cast<double>(num))) + 1 : 1;
931 }

◆ parallelBarrierNotify()

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

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

Definition at line 327 of file MooseUtils.C.

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

328 {
329  processor_id_type secondary_processor_id;
330 
331  if (messaging)
332  Moose::out << "Waiting For Other Processors To Finish" << std::endl;
333  if (comm.rank() == 0)
334  {
335  // The primary process is already through, so report it
336  if (messaging)
337  Moose::out << "Jobs complete: 1/" << comm.size() << (1 == comm.size() ? "\n" : "\r")
338  << std::flush;
339  for (unsigned int i = 2; i <= comm.size(); ++i)
340  {
341  comm.receive(MPI_ANY_SOURCE, secondary_processor_id);
342  if (messaging)
343  Moose::out << "Jobs complete: " << i << "/" << comm.size()
344  << (i == comm.size() ? "\n" : "\r") << std::flush;
345  }
346  }
347  else
348  {
349  secondary_processor_id = comm.rank();
350  comm.send(0, secondary_processor_id);
351  }
352 
353  comm.barrier();
354 }
processor_id_type rank() const
processor_id_type size() const
uint8_t processor_id_type
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

◆ parsesToReal()

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

Check if the input string can be parsed into a Real.

Parameters
inputinput to check / parse
parsed_realpointer to a Real that gets set to the parsed real if it does parse to Real

Definition at line 89 of file MooseUtils.C.

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

90 {
91  std::istringstream ss(input);
92  Real real_value;
93  if (ss >> real_value && ss.eof())
94  {
95  if (parsed_real)
96  (*parsed_real) = real_value;
97  return true;
98  }
99  return false;
100 }
DIE A HORRIBLE DEATH HERE typedef LIBMESH_DEFAULT_SCALAR_TYPE Real

◆ pathContains()

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

This function tokenizes a path and checks to see if it contains the string to look for.

Definition at line 231 of file MooseUtils.C.

234 {
235  std::vector<std::string> elements;
236  tokenize(expression, elements, 0, delims);
237 
238  std::vector<std::string>::iterator found_it =
239  std::find(elements.begin(), elements.end(), string_to_find);
240  if (found_it != elements.end())
241  return true;
242  else
243  return false;
244 }
KOKKOS_INLINE_FUNCTION const T * find(const T &target, const T *const begin, const T *const end)
Find a value in an array.
Definition: KokkosUtils.h:30
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 ...

◆ pathExists()

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

Definition at line 247 of file MooseUtils.C.

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

248 {
249  struct stat buffer;
250  return (stat(path.c_str(), &buffer) == 0);
251 }

◆ pathjoin() [1/2]

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

◆ pathjoin() [2/2]

template<typename... Args>
std::filesystem::path MooseUtils::pathjoin ( const std::filesystem::path &  p,
Args...  args 
)

Definition at line 65 of file MooseUtils.h.

66 {
67  return p / pathjoin(args...);
68 }
std::filesystem::path pathjoin(const std::filesystem::path &p, Args... args)
Definition: MooseUtils.h:65

◆ prettyCppType() [1/2]

std::string MooseUtils::prettyCppType ( const std::string &  cpp_type)
Returns
A cleaner representation of the c++ type cpp_type.

Definition at line 1151 of file MooseUtils.C.

Referenced by MooseServer::addParametersToList(), MooseServer::addValuesToList(), InputParametersChecksUtils< BatchMeshGeneratorAction >::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(), prettyCppType(), ThreadedElementLoop< ConstElemPointerRange >::printExecutionOrdering(), Moose::ParameterRegistry::set(), JsonSyntaxTree::setParams(), and MFEMProblem::solverTypeString().

1152 {
1153  // On mac many of the std:: classes are inline namespaced with __1
1154  // On linux std::string can be inline namespaced with __cxx11
1155  std::string s = cpp_type;
1156  // Remove all spaces surrounding a >
1157  pcrecpp::RE("\\s(?=>)").GlobalReplace("", &s);
1158  pcrecpp::RE("std::__\\w+::").GlobalReplace("std::", &s);
1159  // It would be nice if std::string actually looked normal
1160  pcrecpp::RE("\\s*std::basic_string<char, std::char_traits<char>, std::allocator<char>>\\s*")
1161  .GlobalReplace("std::string", &s);
1162  // It would be nice if std::vector looked normal
1163  pcrecpp::RE r("std::vector<([[:print:]]+),\\s?std::allocator<\\s?\\1\\s?>\\s?>");
1164  r.GlobalReplace("std::vector<\\1>", &s);
1165  // Do it again for nested vectors
1166  r.GlobalReplace("std::vector<\\1>", &s);
1167  return s;
1168 }

◆ prettyCppType() [2/2]

template<typename T >
std::string MooseUtils::prettyCppType ( const T *  obj = nullptr)
Returns
A cleaner representation of the type for the given object

Definition at line 345 of file MooseUtils.h.

346 {
347  if (obj)
348  return prettyCppType(libMesh::demangle(typeid(*obj).name()));
349  else
350  return prettyCppType(libMesh::demangle(typeid(T).name()));
351 }
std::string name(const ElemQuality q)
std::string prettyCppType(const T *obj=nullptr)
Definition: MooseUtils.h:345
std::string demangle(const char *name)

◆ realpath()

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

Wrapper around PetscGetRealPath, which is a cross-platform replacement for realpath.

Definition at line 1136 of file MooseUtils.C.

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

1137 {
1138  return std::filesystem::absolute(path);
1139 }

◆ relativeFuzzyEqual()

template<typename T , typename T2 , typename T3 = Real>
bool MooseUtils::relativeFuzzyEqual ( const T &  var1,
const T2 &  var2,
const T3 &  tol = libMesh::TOLERANCE * libMesh::TOLERANCE 
)

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

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

Definition at line 494 of file MooseUtils.h.

Referenced by MortarNodalAuxKernelTempl< ComputeValueType >::compute(), MatrixSymmetryCheck::execute(), SymmetricRankFourTensorTempl< T >::fillGeneralOrthotropicFromInputVector(), RankFourTensorTempl< T >::fillGeneralOrthotropicFromInputVector(), SymmetricRankFourTensorTempl< T >::isIsotropic(), RankFourTensorTempl< T >::isIsotropic(), SymmetricRankTwoTensorTempl< Real >::positiveProjectionEigenDecomposition(), and EigenProblem::postScaleEigenVector().

497 {
498  if constexpr (libMesh::ScalarTraits<T>::value ||
500  {
503  "Mathematical types must be same for arguments to relativelyFuzzEqual");
505  return absoluteFuzzyEqual(
506  var1,
507  var2,
508  tol * (std::abs(MetaPhysicL::raw_value(var1)) + std::abs(MetaPhysicL::raw_value(var2))));
509  else if constexpr (libMesh::TensorTools::TensorTraits<T>::rank == 1)
510  {
511  for (const auto i : make_range(Moose::dim))
512  if (!relativeFuzzyEqual(var1(i), var2(i), tol))
513  return false;
514 
515  return true;
516  }
517  else if constexpr (libMesh::TensorTools::TensorTraits<T>::rank == 2)
518  {
519  for (const auto i : make_range(Moose::dim))
520  for (const auto j : make_range(Moose::dim))
521  if (!relativeFuzzyEqual(var1(i, j), var2(i, j), tol))
522  return false;
523 
524  return true;
525  }
526  }
527  else
528  {
529  // We dare to dream
530  mooseAssert(var1.size() == var2.size(), "These must be the same size");
531  for (const auto i : index_range(var1))
532  if (!relativeFuzzyEqual(var1(i), var2(i), tol))
533  return false;
534 
535  return true;
536  }
537 }
MetaPhysicL::DualNumber< V, D, asd > abs(const MetaPhysicL::DualNumber< V, D, asd > &a)
Definition: EigenADReal.h:42
bool absoluteFuzzyEqual(const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
Function to check whether two variables are equal within an absolute tolerance.
Definition: MooseUtils.h:382
auto raw_value(const Eigen::Map< T > &in)
Definition: EigenADReal.h:73
static constexpr std::size_t dim
This is the dimension of all vector and tensor datastructures used in MOOSE.
Definition: Moose.h:162
We need to instantiate the following CompareTypes to tell the compiler that ADReal is a subtype of Ch...
The following methods are specializations for using the libMesh::Parallel::packed_range_* routines fo...
bool relativeFuzzyEqual(const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
Function to check whether two variables are equal within a relative tolerance.
Definition: MooseUtils.h:494
if(!dmm->_nl) SETERRQ(PETSC_COMM_WORLD
IntRange< T > make_range(T beg, T end)
auto index_range(const T &sizable)

◆ relativeFuzzyGreaterEqual()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::relativeFuzzyGreaterEqual ( const T &  var1,
const T2 &  var2,
const T3 &  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

Definition at line 555 of file MooseUtils.h.

Referenced by FunctionDT::computeDT().

558 {
560  var1,
561  var2,
563 }
MetaPhysicL::DualNumber< V, D, asd > abs(const MetaPhysicL::DualNumber< V, D, asd > &a)
Definition: EigenADReal.h:42
auto raw_value(const Eigen::Map< T > &in)
Definition: EigenADReal.h:73
bool absoluteFuzzyGreaterEqual(const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
Function to check whether a variable is greater than or equal to another variable within an absolute ...
Definition: MooseUtils.h:406

◆ relativeFuzzyGreaterThan()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::relativeFuzzyGreaterThan ( const T &  var1,
const T2 &  var2,
const T3 &  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

Definition at line 580 of file MooseUtils.h.

583 {
584  return (absoluteFuzzyGreaterThan(
585  var1,
586  var2,
588 }
MetaPhysicL::DualNumber< V, D, asd > abs(const MetaPhysicL::DualNumber< V, D, asd > &a)
Definition: EigenADReal.h:42
auto raw_value(const Eigen::Map< T > &in)
Definition: EigenADReal.h:73
bool absoluteFuzzyGreaterThan(const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
Function to check whether a variable is greater than another variable within an absolute tolerance...
Definition: MooseUtils.h:430

◆ relativeFuzzyLessEqual()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::relativeFuzzyLessEqual ( const T &  var1,
const T2 &  var2,
const T3 &  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

Definition at line 606 of file MooseUtils.h.

609 {
610  return (absoluteFuzzyLessEqual(
611  var1,
612  var2,
614 }
MetaPhysicL::DualNumber< V, D, asd > abs(const MetaPhysicL::DualNumber< V, D, asd > &a)
Definition: EigenADReal.h:42
auto raw_value(const Eigen::Map< T > &in)
Definition: EigenADReal.h:73
bool absoluteFuzzyLessEqual(const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
Function to check whether a variable is less than or equal to another variable within an absolute tol...
Definition: MooseUtils.h:454

◆ relativeFuzzyLessThan()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< libMesh::ScalarTraits< T >::value &&libMesh::ScalarTraits< T2 >::value &&libMesh::ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::relativeFuzzyLessThan ( const T &  var1,
const T2 &  var2,
const T3 &  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

Definition at line 631 of file MooseUtils.h.

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

634 {
635  return (absoluteFuzzyLessThan(
636  var1,
637  var2,
639 }
MetaPhysicL::DualNumber< V, D, asd > abs(const MetaPhysicL::DualNumber< V, D, asd > &a)
Definition: EigenADReal.h:42
auto raw_value(const Eigen::Map< T > &in)
Definition: EigenADReal.h:73
bool absoluteFuzzyLessThan(const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
Function to check whether a variable is less than another variable within an absolute tolerance...
Definition: MooseUtils.h:477

◆ removeColor()

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

remove ANSI escape sequences for terminal color from msg

Definition at line 722 of file MooseUtils.C.

Referenced by Console::writeStreamToFile().

723 {
724  pcrecpp::RE re("(\\33\\[3[0-7]m))", pcrecpp::DOTALL());
725  re.GlobalReplace(std::string(""), &msg);
726  return msg;
727 }

◆ removedirs()

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

Recursively remove directories from inner-most when the directories are empty.

Parameters
dir_nameA complete path
throw_on_failureTrue to throw instead of error out when deleting a directory is failed.

The path can be relative like 'a/b/c' or absolute like '/a/b/c'. The path is allowed to contain '.' or '..'.

Definition at line 505 of file MooseUtils.C.

506 {
507  // split path into directories with delimiter '/'
508  std::vector<std::string> split_dir_names;
509  MooseUtils::tokenize(dir_name, split_dir_names);
510 
511  auto n = split_dir_names.size();
512 
513  // remove '.' and '..' when possible
514  auto i = n;
515  i = 0;
516  while (i != n)
517  {
518  if (split_dir_names[i] == ".")
519  {
520  for (auto j = i + 1; j < n; ++j)
521  split_dir_names[j - 1] = split_dir_names[j];
522  --n;
523  }
524  else if (i > 0 && split_dir_names[i] == ".." && split_dir_names[i - 1] != "..")
525  {
526  for (auto j = i + 1; j < n; ++j)
527  split_dir_names[j - 2] = split_dir_names[j];
528  n -= 2;
529  --i;
530  }
531  else
532  ++i;
533  }
534  if (n == 0)
535  return;
536 
537  split_dir_names.resize(n);
538 
539  // start removing directories recursively
540  std::string base_dir = dir_name[0] == '/' ? "" : ".";
541  for (i = n; i > 0; --i)
542  {
543  std::string cur_dir = base_dir;
544  auto j = i;
545  for (j = 0; j < i; ++j)
546  cur_dir += "/" + split_dir_names[j];
547 
548  // listDir should return at least '.' and '..'
549  if (pathExists(cur_dir) && listDir(cur_dir).size() == 2)
550  {
551  auto code = rmdir(cur_dir.c_str());
552  if (code != 0)
553  {
554  std::string msg = "Failed removing directory " + dir_name;
555  if (throw_on_failure)
556  throw std::invalid_argument(msg);
557  else
558  mooseError(msg);
559  }
560  }
561  else
562  // stop removing
563  break;
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 ...
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:782
bool pathExists(const std::string &path)
Definition: MooseUtils.C:247

◆ removeExtraWhitespace()

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

Removes additional whitespace from a string.

Removes beginning whitespace, end whitespace, and repeated whitespace into a single space

Definition at line 225 of file MooseUtils.C.

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

226 {
227  return std::regex_replace(input, std::regex("^\\s+|\\s+$|\\s+(?=\\s)"), "");
228 }

◆ replaceAll()

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

Replaces all occurrences of from in str with to and returns the result.

Definition at line 145 of file MooseUtils.C.

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

146 {
147  size_t start_pos = 0;
148  while ((start_pos = str.find(from, start_pos)) != std::string::npos)
149  {
150  str.replace(start_pos, from.length(), to);
151  start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
152  }
153  return str;
154 }

◆ replaceStart()

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

Replace the starting string string2 of string1 with string3.

A user should have checked that string1 startsWith string2

Definition at line 1185 of file MooseUtils.C.

1186 {
1187  mooseAssert(startsWith(string1, string2),
1188  "Cannot replace the start because it doesn't match the start string");
1189  string1.replace(0, string2.size(), string3);
1190 }
bool startsWith(const std::string &string1, const std::string &string2)
Definition: MooseUtils.C:1177

◆ resample() [1/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 530 of file Shuffle.h.

Referenced by resample().

533 {
534  return MooseUtils::resample(data, generator, seed_index, nullptr);
535 }
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:530

◆ resample() [2/4]

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

Definition at line 539 of file Shuffle.h.

542 {
543  return MooseUtils::resample(data, generator, 0, &comm);
544 }
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:530

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

Definition at line 548 of file Shuffle.h.

552 {
553  return MooseUtils::resample(data, generator, seed_index, &comm);
554 }
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:530

◆ resample() [4/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 334 of file Shuffle.h.

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

◆ resampleWithFunctor() [1/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 558 of file Shuffle.h.

Referenced by resampleWithFunctor().

562 {
563  return MooseUtils::resampleWithFunctor(data, functor, generator, seed_index, nullptr);
564 }
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:558

◆ resampleWithFunctor() [2/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 568 of file Shuffle.h.

572 {
573  return MooseUtils::resampleWithFunctor(data, functor, generator, 0, &comm);
574 }
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:558

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

Definition at line 578 of file Shuffle.h.

583 {
584  return MooseUtils::resampleWithFunctor(data, functor, generator, seed_index, &comm);
585 }
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:558

◆ 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,
const libMesh::Parallel::Communicator comm_ptr 
)

Definition at line 426 of file Shuffle.h.

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

◆ reset() [1/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.

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

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

◆ reset() [2/2]

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

Definition at line 28 of file SharedPool.h.

29 {
30 }

◆ rsplit()

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

Definition at line 1051 of file MooseUtils.C.

1052 {
1053  std::vector<std::string> output;
1054  std::size_t count = 0;
1055  size_t prev = str.length(), pos = str.length();
1056  do
1057  {
1058  pos = str.rfind(delimiter, prev);
1059  output.insert(output.begin(), str.substr(pos + delimiter.length(), prev - pos));
1060  prev = pos - delimiter.length();
1061  count += 1;
1062  } while (pos != std::string::npos && pos > 0 && count < max_count);
1063 
1064  if (pos != std::string::npos)
1065  output.insert(output.begin(), str.substr(0, pos));
1066 
1067  return output;
1068 }
charT const * delimiter
Definition: InfixIterator.h:34

◆ runTestsExecutable()

std::string MooseUtils::runTestsExecutable ( )

Returns the location of either a local repo run_tests script - or an installed test executor script if run_tests isn't found.

Definition at line 65 of file MooseUtils.C.

Referenced by MooseApp::runInputs().

66 {
67  auto build_loc = pathjoin(Moose::getExecutablePath(), "run_tests");
68  if (pathExists(build_loc) && checkFileReadable(build_loc))
69  return build_loc;
70  // TODO: maybe no path prefix - just moose_test_runner here?
71  return pathjoin(Moose::getExecutablePath(), "moose_test_runner");
72 }
std::string getExecutablePath()
Gets the directory the running executable is on Mac OS X and linux.
bool checkFileReadable(const std::string &filename, bool check_line_endings=false, bool throw_on_unreadable=true, bool check_for_git_lfs_pointer=true)
Checks to see if a file is readable (exists and permissions)
Definition: MooseUtils.C:254
std::filesystem::path pathjoin(const std::filesystem::path &p)
Definition: MooseUtils.C:59
bool pathExists(const std::string &path)
Definition: MooseUtils.C:247

◆ serialBegin()

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

This function marks the begin of a section of code that is executed in serial rank by rank.

The section must be closed with a call to serialEnd. These functions are intended for debugging use to obtain clean terminal output from multiple ranks (use –keep-cout).

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

Definition at line 357 of file MooseUtils.C.

Referenced by SerializerGuard::SerializerGuard().

358 {
359  // unless we are the first processor...
360  if (comm.rank() > 0)
361  {
362  // ...wait for the previous processor to finish
363  int dummy = 0;
364  comm.receive(comm.rank() - 1, dummy);
365  }
366  else if (warn)
367  mooseWarning("Entering serial execution block (use only for debugging)");
368 }
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:357
processor_id_type rank() const
Status receive(const unsigned int dest_processor_id, T &buf, const MessageTag &tag=any_tag) const

◆ serialEnd()

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

Closes a section of code that is executed in serial rank by rank, and that was opened with a call to serialBegin.

No MPI communication can happen in this block.

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

Definition at line 371 of file MooseUtils.C.

Referenced by SerializerGuard::~SerializerGuard().

372 {
373  // unless we are the last processor...
374  if (comm.rank() + 1 < comm.size())
375  {
376  // ...notify the next processor of its turn
377  int dummy = 0;
378  comm.send(comm.rank() + 1, dummy);
379  }
380 
381  comm.barrier();
382  if (comm.rank() == 0 && warn)
383  mooseWarning("Leaving serial execution block (use only for debugging)");
384 }
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:357
processor_id_type rank() const
processor_id_type size() const
void send(const unsigned int dest_processor_id, const T &buf, const MessageTag &tag=no_tag) const

◆ setsIntersect() [1/2]

template<class InputIterator >
bool MooseUtils::setsIntersect ( InputIterator  first1,
InputIterator  last1,
InputIterator  first2,
InputIterator  last2 
)

This method detects whether two sets intersect without building a result set.

It exits as soon as any intersection is detected.

Definition at line 1160 of file MooseUtils.h.

Referenced by Coupleable::checkWritableVar(), and setsIntersect().

1161 {
1162  while (first1 != last1 && first2 != last2)
1163  {
1164  if (*first1 == *first2)
1165  return true;
1166 
1167  if (*first1 < *first2)
1168  ++first1;
1169  else if (*first1 > *first2)
1170  ++first2;
1171  }
1172  return false;
1173 }

◆ setsIntersect() [2/2]

template<class T >
bool MooseUtils::setsIntersect ( const T &  s1,
const T &  s2 
)

Definition at line 1177 of file MooseUtils.h.

1178 {
1179  return setsIntersect(s1.begin(), s1.end(), s2.begin(), s2.end());
1180 }
bool setsIntersect(const T &s1, const T &s2)
Definition: MooseUtils.h:1177

◆ shortName()

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

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

Definition at line 612 of file MooseUtils.C.

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

613 {
614  return name.substr(name.find_last_of('/') != std::string::npos ? name.find_last_of('/') + 1 : 0);
615 }
std::string name(const ElemQuality q)

◆ shuffle() [1/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 504 of file Shuffle.h.

Referenced by shuffle().

505 {
506  return MooseUtils::shuffle(data, generator, seed_index, nullptr);
507 }
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:504

◆ shuffle() [2/4]

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

Definition at line 511 of file Shuffle.h.

514 {
515  return MooseUtils::shuffle(data, generator, 0, &comm);
516 }
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:504

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

Definition at line 520 of file Shuffle.h.

524 {
525  return MooseUtils::shuffle(data, generator, seed_index, &comm);
526 }
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:504

◆ shuffle() [4/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 243 of file Shuffle.h.

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

◆ split()

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

Python like split functions for strings.

NOTE: This is similar to the tokenize function, but it maintains empty items, which tokenize does not. For example, "foo;bar;;" becomes {"foo", "bar", "", ""}.

Definition at line 1031 of file MooseUtils.C.

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

1032 {
1033  std::vector<std::string> output;
1034  std::size_t count = 0;
1035  size_t prev = 0, pos = 0;
1036  do
1037  {
1038  pos = str.find(delimiter, prev);
1039  output.push_back(str.substr(prev, pos - prev));
1040  prev = pos + delimiter.length();
1041  count += 1;
1042  } while (pos != std::string::npos && count < max_count);
1043 
1044  if (pos != std::string::npos)
1045  output.push_back(str.substr(prev));
1046 
1047  return output;
1048 }
charT const * delimiter
Definition: InfixIterator.h:34

◆ splitFileName()

template<typename T >
std::pair<std::filesystem::path, std::filesystem::path> MooseUtils::splitFileName ( const T &  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 263 of file MooseUtils.h.

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

264 {
265  const auto p = std::filesystem::path(std::string(full_file));
266  // Error if path ends with /
267  if (!p.has_filename())
268  mooseError("Invalid full file name: ", p);
269 
270  const auto d = p.parent_path();
271  return {d.empty() ? "." : d, p.filename()};
272 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:323

◆ startsWith()

bool MooseUtils::startsWith ( const std::string &  string1,
const std::string &  string2 
)
Returns
Whether the string1 starts with string2

Definition at line 1177 of file MooseUtils.C.

Referenced by replaceStart().

1178 {
1179  if (string2.size() > string1.size())
1180  return false;
1181  return string1.compare(0, string2.size(), string2) == 0;
1182 }

◆ stringJoin()

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

Concatenates value into a single string separated by separator.

Definition at line 955 of file MooseUtils.C.

Referenced by InputParameters::addCommandLineParamHelper(), Moose::Builder::build(), InputParameters::checkParams(), Parser::joinErrorMessages(), Parser::parse(), and ParsedPostprocessor::ParsedPostprocessor().

956 {
957  std::string combined;
958  for (const auto & value : values)
959  combined += value + separator;
960  if (values.size())
961  combined = combined.substr(0, combined.size() - separator.size());
962  return combined;
963 }
Real value(unsigned n, unsigned alpha, unsigned beta, Real x)

◆ stringToInteger()

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

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

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

Definition at line 978 of file MooseUtils.C.

Referenced by FormattedTable::printTable().

979 {
980  return convert<int>(input, throw_on_failure);
981 }

◆ stripExtension()

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

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

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

Definition at line 427 of file MooseUtils.C.

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

428 {
429  const std::string ext = getExtension(s, rfind);
430  const bool offset = (ext.size() != 0);
431  // -1 offset accounts for the extension's leading dot ("."), if there is an extension
432  return s.substr(0, s.size() - ext.size() - offset);
433 }
std::string getExtension(const std::string &filename, const bool rfind=false)
Gets the extension of the passed file name.
Definition: MooseUtils.C:411

◆ 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 494 of file Shuffle.h.

Referenced by Syntax::addDependencySets(), AllNodesSendListThread::AllNodesSendListThread(), Moose::applyIndices(), AutomaticMortarGeneration::buildMortarSegmentMesh(), RestartableDataReader::clear(), AdvancedExtruderGenerator::generate(), DistributedRectilinearMeshGenerator::paritionSquarely(), MaterialPropertyStorage::shift(), shuffle(), swap(), MooseUtils::StaticallyAllocatedSet< T, N >::swap(), Moose::Kokkos::Map< unsigned int, unsigned int >::swap(), MooseArray< libMesh::VectorValue >::swap(), MooseUtils::Buffer< T >::swap(), and ElementSubdomainModifierBase::timestepSetup().

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

◆ 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 155 of file Shuffle.h.

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

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

Referenced by InputParameters::addCommandLineParamHelper(), Syntax::addDependencySets(), MooseEnumBase::addEnumerationName(), MooseEnumBase::addEnumerationNames(), JsonInputFileFormatter::addLine(), InputParameters::addParamNamesToGroup(), MultiMooseEnum::eraseSetValue(), TransfiniteMeshGenerator::getDiscreteEdge(), MooseApp::getLibrarySearchPaths(), 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().

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 }
auto min(const L &left, const R &right)

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

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

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 }
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 ...
charT const * delimiter
Definition: InfixIterator.h:34

◆ toLower()

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

Convert supplied string to lower case.

name The string to convert upper case.

Definition at line 191 of file MooseStringUtils.h.

Referenced by Moose::Capabilities::add(), Registry::appNameFromAppPath(), CapabilityUtils::check(), MooseServer::getDocumentSymbolKind(), SubProblem::getVariableHelper(), ConsoleUtils::outputRelationshipManagerInformation(), MooseUtils::DelimitedFileReaderTempl< T >::processLine(), Moose::PetscSupport::setSinglePetscOption(), and WorkBalance::WorkBalance().

192 {
193  std::transform(name.begin(), name.end(), name.begin(), ::tolower);
194  return name;
195 }
std::string name(const ElemQuality q)

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

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

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

581 {
582  pcrecpp::StringPiece input(underscore_name);
583  pcrecpp::RE re("([^_]*)(_|$)");
584 
585  std::string result;
586  std::string us, not_us;
587  bool make_upper = leading_upper_case;
588  while (re.Consume(&input, &not_us, &us))
589  {
590  if (not_us.length() > 0)
591  {
592  if (make_upper)
593  {
594  result += std::toupper(not_us[0]);
595  if (not_us.length() > 1)
596  result += not_us.substr(1);
597  }
598  else
599  result += not_us;
600  }
601  if (us == "")
602  break;
603 
604  // Toggle flag so next match is upper cased
605  make_upper = true;
606  }
607 
608  return result;
609 }

◆ wildcardEqual() [1/3]

template<typename T1 , typename T2 >
bool MooseUtils::wildcardEqual ( const T1 &  a,
const T2 &  b 
)

Definition at line 1017 of file MooseUtils.h.

Referenced by findPair().

1018 {
1019  return a == b;
1020 }

◆ wildcardEqual() [2/3]

template<typename T >
bool MooseUtils::wildcardEqual ( const T &  ,
AnyType   
)

Definition at line 1024 of file MooseUtils.h.

1025 {
1026  return true;
1027 }

◆ wildcardEqual() [3/3]

template<typename T >
bool MooseUtils::wildcardEqual ( AnyType  ,
const T &   
)

Definition at line 1030 of file MooseUtils.h.

1031 {
1032  return true;
1033 }

◆ wildCardMatch()

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

Definition at line 888 of file MooseUtils.C.

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

889 {
890  // Assume that an empty string matches anything
891  if (search_string == "")
892  return true;
893 
894  // transform to lower for case insenstive matching
895  std::transform(name.begin(), name.end(), name.begin(), (int (*)(int))std::toupper);
896  std::transform(search_string.begin(),
897  search_string.end(),
898  search_string.begin(),
899  (int (*)(int))std::toupper);
900 
901  // exact match!
902  if (search_string.find("*") == std::string::npos)
903  return search_string == name;
904 
905  // wildcard
906  std::vector<std::string> tokens;
907  MooseUtils::tokenize(search_string, tokens, 1, "*");
908 
909  size_t pos = 0;
910  for (unsigned int i = 0; i < tokens.size() && pos != std::string::npos; ++i)
911  {
912  pos = name.find(tokens[i], pos);
913  // See if we have a leading wildcard
914  if (search_string[0] != '*' && i == 0 && pos != 0)
915  return false;
916  }
917 
918  if (pos != std::string::npos && tokens.size() > 0)
919  {
920  // Now see if we have a trailing wildcard
921  size_t last_token_length = tokens.back().length();
922  if (*search_string.rbegin() == '*' || pos == name.size() - last_token_length)
923  return true;
924  else
925  return false;
926  }
927  else
928  return false;
929 }
std::string name(const ElemQuality q)
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 ...
void ErrorVector unsigned int

Variable Documentation

◆ Any

const struct MooseUtils::AnyType MooseUtils::Any
static