www.mooseframework.org
Classes | 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  DelimitedFileReader
 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 interchangably with Real. More...
 
struct  IsLikeReal< DualReal >
 
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...
 

Functions

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)
 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 replaceAll (std::string str, const std::string &from, const std::string &to)
 Replaces all occurences 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 trim (const std::string &str, const std::string &white_space=" \\\)
 Standard scripting language trim function. More...
 
std::vector< std::string > split (const std::string &str, const std::string &delimiter, 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 T >
std::string join (const T &strings, const std::string &delimiter)
 Python like join function for strings. More...
 
std::size_t fileSize (const std::string &filename)
 Check the file size. More...
 
bool pathContains (const std::string &expression, const std::string &string_to_find, const std::string &delims="/")
 This function tokenizes a path and checks to see if it contains the string to look for. More...
 
bool checkFileReadable (const std::string &filename, bool check_line_endings=false, bool throw_on_unreadable=true, 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 stripExtension (const std::string &s)
 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 *=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< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&ScalarTraits< T3 >::value, int >::type = 0>
bool absoluteFuzzyEqual (const T &var1, const T2 &var2, const T3 &tol=libMesh::TOLERANCE *libMesh::TOLERANCE)
 Function to check whether two variables are equal within an absolute tolerance. More...
 
template<typename T , typename T2 , typename T3 = T, typename std::enable_if< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&ScalarTraits< T3 >::value, int >::type = 0>
bool 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< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&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< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&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< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&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< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&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< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&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< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&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< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&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 >
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)
 
bool pathIsDirectory (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 begining) 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 >
void tokenize (const std::string &str, std::vector< T > &elements, unsigned int min_len=1, const std::string &delims="/")
 This function will split the passed in string on a set of delimiters appending the substrings to the passed in vector. More...
 
template<typename T >
bool tokenizeAndConvert (const std::string &str, std::vector< T > &tokenized_vector, const std::string &delimiter=" \\\)
 tokenizeAndConvert splits a string using delimiter and then converts to type T. More...
 
template<typename T >
convert (const std::string &str, bool throw_on_failure=false)
 convert takes a string representation of a number type and converts it to the number. More...
 
template<>
short int convert< short int > (const std::string &str, bool throw_on_failure)
 
template<>
unsigned short int convert< unsigned short int > (const std::string &str, bool throw_on_failure)
 
template<>
int convert< int > (const std::string &str, bool throw_on_failure)
 
template<>
unsigned int convert< unsigned int > (const std::string &str, bool throw_on_failure)
 
template<>
long int convert< long int > (const std::string &str, bool throw_on_failure)
 
template<>
unsigned long int convert< unsigned long int > (const std::string &str, bool throw_on_failure)
 
template<>
long long int convert< long long int > (const std::string &str, bool throw_on_failure)
 
template<>
unsigned long long int convert< unsigned long long int > (const std::string &str, bool throw_on_failure)
 
void createSymlink (const std::string &target, const std::string &link)
 Create a symbolic link, if the link already exists it is replaced. More...
 
void clearSymlink (const std::string &link)
 Remove a symbolic link, if the given filename is a link. More...
 
std::string toUpper (const std::string &name)
 Convert supplied string to upper case. More...
 
std::string toLower (const std::string &name)
 Convert supplied string to lower case. More...
 
template<typename T >
concatenate (T c1, const T &c2)
 Returns a container that contains the content of second passed in container inserted into the first passed in container (set or map union). More...
 
template<typename T >
std::vector< T > concatenate (std::vector< T > c1, const std::vector< T > &c2)
 Returns a vector that contains is the concatenation of the two passed in vectors. More...
 
template<typename T >
std::vector< T > concatenate (std::vector< T > c1, const T &item)
 Returns the passed in vector with the item appended to it. More...
 
template<typename T >
int numDigits (const T &num)
 Return the number of digits for a number. More...
 
ExecFlagEnum getDefaultExecFlagEnum ()
 Return the default ExecFlagEnum for MOOSE. More...
 
int stringToInteger (const std::string &input, bool throw_on_failure=false)
 Robust string to integer conversion that fails for cases such at "1foo". More...
 
void linearPartitionItems (dof_id_type num_items, dof_id_type num_chunks, dof_id_type chunk_id, dof_id_type &num_local_items, dof_id_type &local_items_begin, dof_id_type &local_items_end)
 Linearly partition a number of items. More...
 
processor_id_type linearPartitionChunk (dof_id_type num_items, dof_id_type num_chunks, dof_id_type item_id)
 Return the chunk_id that is assigned to handle item_id. More...
 
std::string realpath (const std::string &path)
 Wrapper around PetscGetRealPath, which is a cross-platform replacement for realpath. More...
 
template<typename C , typename M1 , typename M2 >
C::iterator findPair (C &container, const M1 &first, const M2 &second)
 Find a specific pair in a container matching on first, second or both pair components. More...
 
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...
 
template<class T , typename... Args>
auto reset (int, T &obj, Args... args) -> decltype(obj.reset(args...), void())
 
template<class T , typename... Args>
void reset (double, T &, Args...)
 
void parallelBarrierNotify (const Parallel::Communicator &comm, bool messaging)
 
void addLineBreaks (std::string &message, unsigned int line_width)
 
template<typename T >
convertStringToInt (const std::string &str, bool throw_on_failure)
 
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 &)
 

Function Documentation

◆ absoluteFuzzyEqual()

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

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

Referenced by FormattedTable::addData(), MultiAppVariableValueSamplePostprocessorTransfer::cacheElemToPostprocessorData(), MultiAppGeneralFieldTransfer::cacheIncomingInterpVals(), CartesianGridDivision::CartesianGridDivision(), MeshDiagnosticsGenerator::checkNonConformalMeshFromAdaptivity(), MeshDiagnosticsGenerator::checkNonPlanarSides(), CircularBoundaryCorrectionGenerator::circularCenterCalculator(), ComparisonPostprocessor::comparisonIsTrue(), VariableCondensationPreconditioner::computeDInverseDiag(), ThresholdElementSubdomainModifier::computeSubdomainID(), CylindricalGridDivision::CylindricalGridDivision(), MultiAppGeneralFieldTransfer::detectConflict(), CartesianGridDivision::divisionIndex(), CylindricalGridDivision::divisionIndex(), SphericalGridDivision::divisionIndex(), MultiAppGeneralFieldNearestLocationTransfer::evaluateInterpValuesNearestNode(), MultiAppGeneralFieldTransfer::examineLocalValueConflicts(), MultiAppGeneralFieldTransfer::examineReceivedValueConflicts(), PointValue::execute(), FindValueOnLine::execute(), FillBetweenPointVectorsTools::fillBetweenPointVectorsGenerator(), RankFourTensorTempl< T >::fillGeneralOrthotropicFromInputVector(), MeshDivisionFunctorReductionVectorPostprocessor::finalize(), BicubicInterpolation::findInterval(), MeshRepairGenerator::fixOverlappingNodes(), ParsedCurveGenerator::generate(), AdvancedExtruderGenerator::generate(), CircularBoundaryCorrectionGenerator::generate(), CircularBoundaryCorrectionGenerator::generateRadialCorrectionFactor(), FunctorBinnedValuesDivision::getBinIndex(), TransfiniteMeshGenerator::getEdge(), Positions::getNearestPositionIndex(), MultiAppGeneralFieldTransfer::getRestrictedFromBoundingBoxes(), SideAverageValue::getValue(), RelativeDifferencePostprocessor::getValue(), LineValueSampler::getValue(), Moose::FV::greenGaussGradient(), MooseAppCoordTransform::hasScalingOrRotationTransformation(), AutomaticMortarGeneration::householderOrthogolization(), ElementGroupCentroidPositions::initialize(), MooseVariableBase::initialSetup(), MooseMeshUtils::isCoPlanar(), ActivateElementsCoupled::isElementActivated(), MultiAppCoordTransform::isIdentity(), RankTwoTensorTempl< Real >::isSymmetric(), isZero(), MooseMeshXYCuttingUtils::lineRemoverCutElemTri(), MooseMeshXYCuttingUtils::lineRemoverMoveNode(), LineValueSampler::LineValueSampler(), FillBetweenPointVectorsTools::needFlip(), CutMeshByPlaneGenerator::nonDuplicateNodeCreator(), EigenExecutionerBase::normalizeSolution(), MultiAppCoordTransform::operator()(), RankTwoTensorTempl< Real >::operator==(), TableOutput::outputPostprocessors(), TableOutput::outputReporter(), PointIndexedMap::PointIndexedMap(), CutMeshByPlaneGenerator::pointPairPlaneInterception(), RankTwoTensorTempl< Real >::positiveProjectionEigenDecomposition(), EigenExecutionerBase::postExecute(), EigenProblem::preScaleEigenVector(), MooseMeshXYCuttingUtils::quasiTriElementsFixer(), CoarsenBlockGenerator::recursiveCoarsen(), relativeFuzzyEqual(), BicubicInterpolation::sample2ndDerivative(), BicubicInterpolation::sampleDerivative(), BicubicInterpolation::sampleValueAndDerivativesInternal(), TimeSequenceStepperBase::setupSequence(), Predictor::shouldApply(), SphericalGridDivision::SphericalGridDivision(), SymmetryTransformGenerator::SymmetryTransformGenerator(), CutMeshByPlaneGenerator::tet4ElemCutter(), TimeIntervalTimes::TimeIntervalTimes(), SecantSolve::transformPostprocessors(), SteffensenSolve::transformPostprocessors(), SteffensenSolve::transformVariables(), SecantSolve::transformVariables(), MooseMeshXYCuttingUtils::triElemSplitter(), ParsedCurveGenerator::tSectionSpaceDefiner(), Axisymmetric2D3DSolutionFunction::value(), and XYMeshLineCutter::XYMeshLineCutter().

349 {
350  return (std::abs(MetaPhysicL::raw_value(var1) - MetaPhysicL::raw_value(var2)) <=
352 }
auto raw_value(const Eigen::Map< T > &in)
Definition: ADReal.h:73
ADRealEigenVector< T, D, asd > abs(const ADRealEigenVector< T, D, asd > &)

◆ absoluteFuzzyGreaterEqual()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::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 369 of file MooseUtils.h.

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

372 {
373  return (MetaPhysicL::raw_value(var1) >=
375 }
auto raw_value(const Eigen::Map< T > &in)
Definition: ADReal.h:73

◆ absoluteFuzzyGreaterThan()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::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< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&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 415 of file MooseUtils.h.

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

418 {
419  return (MetaPhysicL::raw_value(var1) <=
421 }
auto raw_value(const Eigen::Map< T > &in)
Definition: ADReal.h:73

◆ absoluteFuzzyLessThan()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::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 437 of file MooseUtils.h.

Referenced by FormattedTable::addData(), MultiAppVariableValueSamplePostprocessorTransfer::cacheElemToPostprocessorData(), ComparisonPostprocessor::comparisonIsTrue(), TimePeriod::conditionMet(), CartesianGridDivision::divisionIndex(), CylindricalGridDivision::divisionIndex(), SphericalGridDivision::divisionIndex(), Positions::getNearestPositionIndex(), CutMeshByPlaneGenerator::pointPlaneRelation(), and relativeFuzzyLessThan().

440 {
441  return (MetaPhysicL::raw_value(var1) <
443 }
auto raw_value(const Eigen::Map< T > &in)
Definition: ADReal.h:73

◆ addLineBreaks()

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

Definition at line 716 of file MooseUtils.C.

718 {
719  for (auto i : make_range(int(message.length() / line_width)))
720  message.insert((i + 1) * (line_width + 2) - 2, "\n");
721 }
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 604 of file MooseUtils.C.

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

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

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

Referenced by PropertyReadFile::PropertyReadFile().

1227 {
1228  BoundingBox bb;
1229  bb.union_with(p1);
1230  bb.union_with(p2);
1231  return bb;
1232 }

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

Referenced by MooseApp::appNameToLibName().

555 {
556  std::string replaced = camel_case_name;
557  // Put underscores in front of each contiguous set of capital letters
558  pcrecpp::RE("(?!^)(?<![A-Z_])([A-Z]+)").GlobalReplace("_\\1", &replaced);
559 
560  // Convert all capital letters to lower case
561  std::transform(replaced.begin(), replaced.end(), replaced.begin(), ::tolower);
562  return replaced;
563 }

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

Referenced by FileMesh::buildMesh(), docsDir(), MooseApp::dynamicRegistration(), ExodusFileTimes::ExodusFileTimes(), ExodusTimeSequenceStepper::ExodusTimeSequenceStepper(), findTestRoot(), MooseServer::gatherDocumentDefinitionLocations(), FileMeshGenerator::generate(), DataFileInterface< Action >::getDataFileName(), DataFileInterface< Action >::getDataFileNameByName(), installedInputsDir(), RestartableDataReader::isAvailable(), ADFParser::JITCompile(), MooseApp::loadLibraryAndDependencies(), Exodus::output(), Parser::parse(), MooseUtils::DelimitedFileReader::read(), JSONFileReader::read(), MultiApp::readCommandLineArguments(), SolutionUserObject::readXda(), MooseApp::run(), runTestsExecutable(), and ValueCache< T >::ValueCache().

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

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

Referenced by PNGOutput::makePNG().

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

Referenced by checkFileReadable().

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

◆ clearSymlink()

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

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

Definition at line 1168 of file MooseUtils.C.

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

1169 {
1170 #ifndef __WIN32__
1171  struct stat sbuf;
1172  if (lstat(link.c_str(), &sbuf) == 0)
1173  {
1174  auto err = unlink(link.c_str());
1175  if (err != 0)
1176  mooseError("Failed to remove symbolic link (via 'unlink') to ", link);
1177  }
1178 #else
1179  auto attr = GetFileAttributesA(link.c_str());
1180  if (attr != INVALID_FILE_ATTRIBUTES)
1181  {
1182  auto err = _unlink(link.c_str());
1183  if (err != 0)
1184  mooseError("Failed to remove link/file (via '_unlink') to ", link);
1185  }
1186 #endif
1187 }
OStreamProxy err
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:299

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

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

903 {
904  c1.insert(c2.begin(), c2.end());
905  return c1;
906 }

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

914 {
915  c1.insert(c1.end(), c2.begin(), c2.end());
916  return c1;
917 }

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

925 {
926  c1.push_back(item);
927  return c1;
928 }

◆ convert()

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

convert takes a string representation of a number type and converts it to the number.

This method is here to get around deficiencies in the STL stoi and stod methods where they might successfully convert part of a string to a number when we'd like to throw an error.

Definition at line 831 of file MooseUtils.h.

Referenced by MooseServer::getDocumentSymbolKind().

832 {
833  std::stringstream ss(str);
834  T val;
835  if ((ss >> val).fail() || !ss.eof())
836  {
837  std::string msg =
838  std::string("Unable to convert '") + str + "' to type " + demangle(typeid(T).name());
839 
840  if (throw_on_failure)
841  throw std::invalid_argument(msg);
842  else
843  mooseError(msg);
844  }
845 
846  return val;
847 }
std::string name(const ElemQuality q)
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:299
std::string demangle(const char *name)

◆ convert< int >()

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

Definition at line 999 of file MooseUtils.C.

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

1000 {
1001  return convertStringToInt<int>(str, throw_on_failure);
1002 }

◆ convert< long int >()

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

Definition at line 1013 of file MooseUtils.C.

1014 {
1015  return convertStringToInt<long int>(str, throw_on_failure);
1016 }

◆ convert< long long int >()

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

Definition at line 1027 of file MooseUtils.C.

1028 {
1029  return convertStringToInt<long long int>(str, throw_on_failure);
1030 }

◆ convert< short int >()

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

Definition at line 985 of file MooseUtils.C.

986 {
987  return convertStringToInt<short int>(str, throw_on_failure);
988 }

◆ convert< unsigned int >()

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

Definition at line 1006 of file MooseUtils.C.

1007 {
1008  return convertStringToInt<unsigned int>(str, throw_on_failure);
1009 }

◆ convert< unsigned long int >()

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

Definition at line 1020 of file MooseUtils.C.

1021 {
1022  return convertStringToInt<unsigned long int>(str, throw_on_failure);
1023 }

◆ convert< unsigned long long int >()

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

Definition at line 1034 of file MooseUtils.C.

1035 {
1036  return convertStringToInt<unsigned long long int>(str, throw_on_failure);
1037 }

◆ convert< unsigned short int >()

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

Definition at line 992 of file MooseUtils.C.

993 {
994  return convertStringToInt<unsigned short int>(str, throw_on_failure);
995 }

◆ convertLatestCheckpoint()

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

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

Definition at line 146 of file MooseUtils.C.

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

147 {
148  auto slash_pos = orig.find_last_of("/");
149  auto path = orig.substr(0, slash_pos);
150  auto file = orig.substr(slash_pos + 1);
151  if (file != "LATEST")
152  return orig;
153 
155 
156  if (converted.empty())
157  mooseError("Unable to find suitable recovery file!");
158 
159  return converted;
160 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:299
std::string getLatestCheckpointFilePrefix(const std::list< std::string > &checkpoint_files)
Returns the most recent checkpoint prefix (the four numbers at the begining) If a suitable file isn&#39;t...
Definition: MooseUtils.C:805
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:768

◆ convertStringToInt()

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

Definition at line 942 of file MooseUtils.C.

943 {
944  T val;
945 
946  // Let's try to read a double and see if we can cast it to an int
947  // This would be the case for scientific notation
948  long double double_val;
949  std::stringstream double_ss(str);
950  double_ss >> double_val;
951 
952  // on arm64 the long double does not have sufficient precission
953  bool use_int = false;
954  std::stringstream int_ss(str);
955  if (!(int_ss >> val).fail() && int_ss.eof())
956  use_int = true;
957 
958  if (double_ss.fail() || !double_ss.eof())
959  {
960  std::string msg =
961  std::string("Unable to convert '") + str + "' to type " + demangle(typeid(T).name());
962 
963  if (throw_on_failure)
964  throw std::invalid_argument(msg);
965  else
966  mooseError(msg);
967  }
968 
969  // Check to see if it's an integer (and within range of an integer)
970  if (double_val == static_cast<T>(double_val))
971  return use_int ? val : static_cast<T>(double_val);
972 
973  // Still failure
974  std::string msg =
975  std::string("Unable to convert '") + str + "' to type " + demangle(typeid(T).name());
976 
977  if (throw_on_failure)
978  throw std::invalid_argument(msg);
979  else
980  mooseError(msg);
981 }
std::string name(const ElemQuality q)
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:299
std::string demangle(const char *name)

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

Referenced by CSV::output().

1156 {
1157  clearSymlink(link);
1158 #ifndef __WIN32__
1159  auto err = symlink(target.c_str(), link.c_str());
1160 #else
1161  auto err = CreateSymbolicLink(target.c_str(), link.c_str(), 0);
1162 #endif
1163  if (err)
1164  mooseError("Failed to create symbolic link (via 'symlink') from ", target, " to ", link);
1165 }
OStreamProxy err
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:299
void clearSymlink(const std::string &link)
Remove a symbolic link, if the given filename is a link.
Definition: MooseUtils.C:1168

◆ docsDir()

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

Returns the directory of any installed docs/site.

Definition at line 120 of file MooseUtils.C.

Referenced by MooseApp::run().

121 {
122  // See moose.mk for a detailed explanation of the assumed installed application
123  // layout. Installed docs are expected to be installed in "share/<app_name>/doc".
124  // The binary, which has a defined location will be in "bin", a peer directory to "share".
125  std::string installed_path = pathjoin(Moose::getExecutablePath(), "..", "share", app_name, "doc");
126 
127  auto docfile = pathjoin(installed_path, "css", "moose.css");
128  if (pathExists(docfile) && checkFileReadable(docfile))
129  return installed_path;
130  return "";
131 }
std::string getExecutablePath()
This function returns the PATH of the running executable.
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:256
std::filesystem::path pathjoin(const std::filesystem::path &p)
Definition: MooseUtils.C:58
bool pathExists(const std::string &path)
Definition: MooseUtils.C:240

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

Referenced by MooseMeshUtils::getBoundaryIDs().

324 {
325  for (typename std::map<T1, T2>::const_iterator iter = the_map.begin(); iter != the_map.end();
326  ++iter)
327  if (iter->second == value)
328  return true;
329  return false;
330 }

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

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

197 {
198  std::map<char, std::string> escapes;
199  escapes['\a'] = "\\a";
200  escapes['\b'] = "\\b";
201  escapes['\f'] = "\\f";
202  escapes['\n'] = "\\n";
203  escapes['\t'] = "\\t";
204  escapes['\v'] = "\\v";
205  escapes['\r'] = "\\r";
206 
207  for (const auto & it : escapes)
208  for (size_t pos = 0; (pos = str.find(it.first, pos)) != std::string::npos;
209  pos += it.second.size())
210  str.replace(pos, 1, it.second);
211 }

◆ expandAllMatches()

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

Definition at line 753 of file MooseUtils.h.

Referenced by SingleMatrixPreconditioner::SingleMatrixPreconditioner().

754 {
755  std::set<T> expanded;
756  for (const auto & p : patterns)
757  {
758  unsigned int found = 0;
759  for (const auto & c : candidates)
760  if (globCompare(c, p))
761  {
762  expanded.insert(c);
763  found++;
764  }
765  if (!found)
766  throw std::invalid_argument(p);
767  }
768  patterns.assign(expanded.begin(), expanded.end());
769 }
bool globCompare(const std::string &candidate, const std::string &pattern, std::size_t c=0, std::size_t p=0)
Definition: MooseUtils.C:918

◆ fileSize()

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

Check the file size.

Definition at line 1190 of file MooseUtils.C.

Referenced by Exodus::output().

1191 {
1192 #ifndef __WIN32__
1193  struct stat buffer;
1194  if (!stat(filename.c_str(), &buffer))
1195  return buffer.st_size;
1196 #else
1197  HANDLE hFile = CreateFile(filename.c_str(),
1198  GENERIC_READ,
1199  FILE_SHARE_READ | FILE_SHARE_WRITE,
1200  NULL,
1201  OPEN_EXISTING,
1202  FILE_ATTRIBUTE_NORMAL,
1203  NULL);
1204  if (hFile == INVALID_HANDLE_VALUE)
1205  return 0;
1206 
1207  LARGE_INTEGER size;
1208  if (GetFileSizeEx(hFile, &size))
1209  {
1210  CloseHandle(hFile);
1211  return size.QuadPart;
1212  }
1213 
1214  CloseHandle(hFile);
1215 #endif
1216  return 0;
1217 }

◆ findPair()

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

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

Definition at line 1053 of file MooseUtils.h.

Referenced by Moose::PetscSupport::disableLinearConvergedReason(), Moose::PetscSupport::disableNonlinearConvergedReason(), Moose::PetscSupport::isSNESVI(), and Moose::PetscSupport::processPetscPairs().

1054 {
1055  return std::find_if(container.begin(),
1056  container.end(),
1057  [&](auto & item) {
1058  return wildcardEqual(first, item.first) &&
1059  wildcardEqual(second, item.second);
1060  });
1061 }
bool wildcardEqual(AnyType, const T &)
Definition: MooseUtils.h:1042

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

Referenced by MooseApp::runInputs().

75 {
76  std::string path = ".";
77  for (int i = 0; i < 5; i++)
78  {
79  auto testroot = pathjoin(path, "testroot");
80  if (pathExists(testroot) && checkFileReadable(testroot))
81  return testroot;
82  path += "/..";
83  }
84  return "";
85 }
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:256
std::filesystem::path pathjoin(const std::filesystem::path &p)
Definition: MooseUtils.C:58
bool pathExists(const std::string &path)
Definition: MooseUtils.C:240

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

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

1148 {
1149  return u.get();
1150 }

◆ get() [2/3]

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

Definition at line 1154 of file MooseUtils.h.

1155 {
1156  return p;
1157 }

◆ get() [3/3]

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

Definition at line 1161 of file MooseUtils.h.

1162 {
1163  return s.get();
1164 }

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

Referenced by MooseApp::runInputs().

423 {
424  // Note: At the time of creating this method, our minimum compiler still
425  // does not support <filesystem>. Additionally, the inclusion of that header
426  // requires an additional library to be linked so for now, we'll just
427  // use the Unix standard library to get us the cwd().
428  constexpr unsigned int BUF_SIZE = 1024;
429  char buffer[BUF_SIZE];
430 
431  return getcwd(buffer, BUF_SIZE) != nullptr ? buffer : "";
432 }

◆ getDefaultExecFlagEnum()

ExecFlagEnum MooseUtils::getDefaultExecFlagEnum ( )

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

Referenced by MooseApp::getCheckpointFiles().

795 {
796  std::list<std::string> files;
797 
798  for (const auto & dir_name : directory_list)
799  files.splice(files.end(), listDir(dir_name, files_only));
800 
801  return files;
802 }
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:768

◆ getLatestCheckpointFilePrefix()

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

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

Parameters
checkpoint_filesthe list of files to analyze

Definition at line 805 of file MooseUtils.C.

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

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

Referenced by FormattedTable::printTable().

627 {
628 #ifndef __WIN32__
629  struct winsize w;
630 #else
631  struct
632  {
633  unsigned short ws_col;
634  } w;
635 #endif
636 
641 
642  if (use_environment)
643  {
644  char * pps_width = std::getenv("MOOSE_PPS_WIDTH");
645  if (pps_width != NULL)
646  {
647  std::stringstream ss(pps_width);
648  ss >> w.ws_col;
649  }
650  }
651  // Default to AUTO if no environment variable was set
653  {
654 #ifndef __WIN32__
655  try
656  {
657  ioctl(0, TIOCGWINSZ, &w);
658  }
659  catch (...)
660 #endif
661  {
662  }
663  }
664 
665  // Something bad happened, make sure we have a sane value
666  // 132 seems good for medium sized screens, and is available as a GNOME preset
668  w.ws_col = 132;
669 
670  return w.ws_col;
671 }
auto max(const L &left, const R &right)

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

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

922 {
923  if (p == pattern.size())
924  return c == candidate.size();
925 
926  if (pattern[p] == '*')
927  {
928  for (; c < candidate.size(); ++c)
929  if (globCompare(candidate, pattern, c, p + 1))
930  return true;
931  return globCompare(candidate, pattern, c, p + 1);
932  }
933 
934  if (pattern[p] != '?' && pattern[p] != candidate[c])
935  return false;
936 
937  return globCompare(candidate, pattern, c + 1, p + 1);
938 }
bool globCompare(const std::string &candidate, const std::string &pattern, std::size_t c=0, std::size_t p=0)
Definition: MooseUtils.C:918

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

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

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

◆ hostname()

std::string MooseUtils::hostname ( )

Get the hostname the current process is running on.

Definition at line 610 of file MooseUtils.C.

Referenced by MooseApp::MooseApp().

611 {
612  char hostname[1024];
613  hostname[1023] = '\0';
614 #ifndef __WIN32__
615  if (gethostname(hostname, 1023))
616  mooseError("Failed to retrieve hostname!");
617 #else
618  DWORD dwSize = sizeof(hostname);
619  if (!GetComputerNameEx(ComputerNamePhysicalDnsHostname, hostname, &dwSize))
620  mooseError("Failed to retrieve hostname!");
621 #endif
622  return hostname;
623 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:299
std::string hostname()
Get the hostname the current process is running on.
Definition: MooseUtils.C:610

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

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

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

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

Referenced by MooseApp::copyInputs().

101 {
102  // See moose.mk for a detailed explanation of the assumed installed application
103  // layout. Installed inputs are expected to be installed in "share/<app_name>/<folder>".
104  // The binary, which has a defined location will be in "bin", a peer directory to "share".
105  std::string installed_path =
106  pathjoin(Moose::getExecutablePath(), "..", "share", app_name, dir_name);
107 
108  auto test_root = pathjoin(installed_path, "testroot");
109  if (!pathExists(installed_path))
110  mooseError("Couldn't locate any installed inputs to copy in path: ",
111  installed_path,
112  '\n',
113  extra_error_msg);
114 
115  checkFileReadable(test_root);
116  return installed_path;
117 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:299
std::string getExecutablePath()
This function returns the PATH of the running executable.
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:256
std::filesystem::path pathjoin(const std::filesystem::path &p)
Definition: MooseUtils.C:58
bool pathExists(const std::string &path)
Definition: MooseUtils.C:240

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

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

1201 {
1202  return std::all_of(str.begin(), str.end(), [](unsigned char c) { return std::isdigit(c); });
1203 }

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

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

629 {
630  if constexpr (Has_size<T>::value)
631  {
632  for (const auto & element : value)
633  if (!isZero(element, tolerance))
634  return false;
635 
636  return true;
637  }
638  else if constexpr (libMesh::TensorTools::TensorTraits<T>::rank == 0)
639  return MooseUtils::absoluteFuzzyEqual(MetaPhysicL::raw_value(value), 0, tolerance);
640  else if constexpr (libMesh::TensorTools::TensorTraits<T>::rank == 1)
641  {
642  for (const auto i : make_range(Moose::dim))
644  return false;
645 
646  return true;
647  }
648  else if constexpr (libMesh::TensorTools::TensorTraits<T>::rank == 2)
649  {
650  for (const auto i : make_range(Moose::dim))
651  for (const auto j : make_range(Moose::dim))
653  return false;
654 
655  return true;
656  }
657 }
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:346
bool isZero(const T &value, const Real tolerance=TOLERANCE *TOLERANCE *TOLERANCE)
Definition: MooseUtils.h:628
auto raw_value(const Eigen::Map< T > &in)
Definition: ADReal.h:73
static constexpr std::size_t dim
This is the dimension of all vector and tensor datastructures used in MOOSE.
Definition: Moose.h:148
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)
IntRange< T > make_range(T beg, T end)

◆ join()

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

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

Referenced by Moose::findSimilar().

166 {
167  // To change the type this function manipulates and returns, change
168  // the return type and the types of the two variables below.
169  auto s1len = s1.size();
170  auto s2len = s2.size();
171 
172  auto column_start = (decltype(s1len))1;
173 
174  auto column = new decltype(s1len)[s1len + 1];
175  std::iota(column + column_start, column + s1len + 1, column_start);
176 
177  for (auto x = column_start; x <= s2len; x++)
178  {
179  column[0] = x;
180  auto last_diagonal = x - column_start;
181  for (auto y = column_start; y <= s1len; y++)
182  {
183  auto old_diagonal = column[y];
184  auto possibilities = {
185  column[y] + 1, column[y - 1] + 1, last_diagonal + (s1[y - 1] == s2[x - 1] ? 0 : 1)};
186  column[y] = std::min(possibilities);
187  last_diagonal = old_diagonal;
188  }
189  }
190  auto result = column[s1len];
191  delete[] column;
192  return result;
193 }
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 1094 of file MooseUtils.C.

Referenced by DistributedRectilinearMeshGenerator::buildCube().

1095 {
1096  auto global_num_local_items = num_items / num_chunks;
1097 
1098  auto leftovers = num_items % num_chunks;
1099 
1100  auto first_item_past_first_part = leftovers * (global_num_local_items + 1);
1101 
1102  // Is it in the first section (that gets an extra item)
1103  if (item_id < first_item_past_first_part)
1104  return item_id / (global_num_local_items + 1);
1105  else
1106  {
1107  auto new_item_id = item_id - first_item_past_first_part;
1108 
1109  // First chunk after the first section + the number of chunks after that
1110  return leftovers + (new_item_id / global_num_local_items);
1111  }
1112 }

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

Referenced by DistributedRectilinearMeshGenerator::buildCube().

1074 {
1075  auto global_num_local_items = num_items / num_chunks;
1076 
1077  num_local_items = global_num_local_items;
1078 
1079  auto leftovers = num_items % num_chunks;
1080 
1081  if (chunk_id < leftovers)
1082  {
1083  num_local_items++;
1084  local_items_begin = num_local_items * chunk_id;
1085  }
1086  else
1087  local_items_begin =
1088  (global_num_local_items + 1) * leftovers + global_num_local_items * (chunk_id - leftovers);
1089 
1090  local_items_end = local_items_begin + num_local_items;
1091 }

◆ listDir()

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

Definition at line 768 of file MooseUtils.C.

Referenced by convertLatestCheckpoint(), DataFileInterface< Action >::getDataFileNameByName(), getFilesInDirs(), and removedirs().

769 {
770  std::list<std::string> files;
771 
772  tinydir_dir dir;
773  dir.has_next = 0; // Avoid a garbage value in has_next (clang StaticAnalysis)
774  tinydir_open(&dir, path.c_str());
775 
776  while (dir.has_next)
777  {
778  tinydir_file file;
779  file.is_dir = 0; // Avoid a garbage value in is_dir (clang StaticAnalysis)
780  tinydir_readfile(&dir, &file);
781 
782  if (!files_only || !file.is_dir)
783  files.push_back(path + "/" + file.name);
784 
785  tinydir_next(&dir);
786  }
787 
788  tinydir_close(&dir);
789 
790  return files;
791 }

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

Referenced by MooseApp::MooseApp().

436 {
437  // split path into directories with delimiter '/'
438  std::vector<std::string> split_dir_names;
439  MooseUtils::tokenize(dir_name, split_dir_names);
440 
441  auto n = split_dir_names.size();
442 
443  // remove '.' and '..' when possible
444  auto i = n;
445  i = 0;
446  while (i != n)
447  {
448  if (split_dir_names[i] == ".")
449  {
450  for (auto j = i + 1; j < n; ++j)
451  split_dir_names[j - 1] = split_dir_names[j];
452  --n;
453  }
454  else if (i > 0 && split_dir_names[i] == ".." && split_dir_names[i - 1] != "..")
455  {
456  for (auto j = i + 1; j < n; ++j)
457  split_dir_names[j - 2] = split_dir_names[j];
458  n -= 2;
459  --i;
460  }
461  else
462  ++i;
463  }
464  if (n == 0)
465  return;
466 
467  split_dir_names.resize(n);
468 
469  // start creating directories recursively
470  std::string cur_dir = dir_name[0] == '/' ? "" : ".";
471  for (auto & dir : split_dir_names)
472  {
473  cur_dir += "/" + dir;
474 
475  if (!pathExists(cur_dir))
476  {
477  auto code = Utility::mkdir(cur_dir.c_str());
478  if (code != 0)
479  {
480  std::string msg = "Failed creating directory " + dir_name;
481  if (throw_on_failure)
482  throw std::invalid_argument(msg);
483  else
484  mooseError(msg);
485  }
486  }
487  }
488 }
void tokenize(const std::string &str, std::vector< T > &elements, unsigned int min_len=1, const std::string &delims="/")
This function will split the passed in string on a set of delimiters appending the substrings to the ...
Definition: MooseUtils.h:779
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:299
bool pathExists(const std::string &path)
Definition: MooseUtils.C:240

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

676 {
677  // Loop through the elements
678  for (const auto & elem_it : props)
679  {
680  Moose::out << "Element " << elem_it.first->id() << '\n';
681 
682  // Loop through the sides
683  for (const auto & side_it : elem_it.second)
684  {
685  Moose::out << " Side " << side_it.first << '\n';
686 
687  // Loop over properties
688  unsigned int cnt = 0;
689  for (const auto & mat_prop : side_it.second)
690  {
691  if (auto mp = dynamic_cast<const MaterialProperty<Real> *>(&mat_prop))
692  {
693  Moose::out << " Property " << cnt << '\n';
694  cnt++;
695 
696  // Loop over quadrature points
697  for (unsigned int qp = 0; qp < mp->size(); ++qp)
698  Moose::out << " prop[" << qp << "] = " << (*mp)[qp] << '\n';
699  }
700  }
701  }
702  }
703 
704  Moose::out << std::flush;
705 }

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

Referenced by XMLOutput::filename(), JSONOutput::filename(), CSV::getVectorPostprocessorFileName(), CSV::output(), MooseUtils::DelimitedFileReader::readColumnData(), and MooseUtils::DelimitedFileReader::readRowData().

941 {
942  return num > 9 ? static_cast<int>(std::log10(static_cast<double>(num))) + 1 : 1;
943 }

◆ parallelBarrierNotify() [1/2]

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

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

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

◆ parallelBarrierNotify() [2/2]

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

Definition at line 329 of file MooseUtils.C.

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

◆ parsesToReal()

bool MooseUtils::parsesToReal ( const std::string &  input)

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

Definition at line 88 of file MooseUtils.C.

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

89 {
90  std::istringstream ss(input);
91  Real real_value;
92  if (ss >> real_value && ss.eof())
93  return true;
94  return false;
95 }
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 224 of file MooseUtils.C.

227 {
228  std::vector<std::string> elements;
229  tokenize(expression, elements, 0, delims);
230 
231  std::vector<std::string>::iterator found_it =
232  std::find(elements.begin(), elements.end(), string_to_find);
233  if (found_it != elements.end())
234  return true;
235  else
236  return false;
237 }
void tokenize(const std::string &str, std::vector< T > &elements, unsigned int min_len=1, const std::string &delims="/")
This function will split the passed in string on a set of delimiters appending the substrings to the ...
Definition: MooseUtils.h:779

◆ pathExists()

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

Definition at line 240 of file MooseUtils.C.

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

241 {
242  struct stat buffer;
243  return (stat(path.c_str(), &buffer) == 0);
244 }

◆ pathIsDirectory()

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

Definition at line 247 of file MooseUtils.C.

Referenced by Registry::addDataFilePath(), and DataFileInterface< Action >::getDataFileNameByName().

248 {
249  // We use the non-throwing overload of this so that we suppress any issues with
250  // reading and just report it as an unavailable directory
251  std::error_code ec;
252  return std::filesystem::is_directory(path, ec);
253 }

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

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

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

Referenced by MooseServer::addParametersToList(), MooseServer::addValuesToList(), PhysicsBase::assertParamDefined(), ReporterGeneralContext< T >::contextType(), ReporterBroadcastContext< T >::contextType(), ReporterScatterContext< T >::contextType(), ReporterGatherContext< T >::contextType(), ReporterVectorContext< T >::contextType(), FunctorSmootherTempl< T >::FunctorSmootherTempl(), MooseServer::gatherDocumentDefinitionLocations(), prettyCppType(), ThreadedElementLoop< ConstElemPointerRange >::printExecutionOrdering(), and JsonSyntaxTree::setParams().

1236 {
1237  // On mac many of the std:: classes are inline namespaced with __1
1238  // On linux std::string can be inline namespaced with __cxx11
1239  std::string s = cpp_type;
1240  // Remove all spaces surrounding a >
1241  pcrecpp::RE("\\s(?=>)").GlobalReplace("", &s);
1242  pcrecpp::RE("std::__\\w+::").GlobalReplace("std::", &s);
1243  // It would be nice if std::string actually looked normal
1244  pcrecpp::RE("\\s*std::basic_string<char, std::char_traits<char>, std::allocator<char>>\\s*")
1245  .GlobalReplace("std::string", &s);
1246  // It would be nice if std::vector looked normal
1247  pcrecpp::RE r("std::vector<([[:print:]]+),\\s?std::allocator<\\s?\\1\\s?>\\s?>");
1248  r.GlobalReplace("std::vector<\\1>", &s);
1249  // Do it again for nested vectors
1250  r.GlobalReplace("std::vector<\\1>", &s);
1251  return s;
1252 }

◆ prettyCppType() [2/2]

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

Definition at line 313 of file MooseUtils.h.

314 {
315  return prettyCppType(demangle(typeid(T).name()));
316 }
std::string name(const ElemQuality q)
std::string demangle(const char *name)
std::string prettyCppType(const T *=nullptr)
Definition: MooseUtils.h:313

◆ realpath()

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

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

Definition at line 1220 of file MooseUtils.C.

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

1221 {
1222  return std::filesystem::absolute(path);
1223 }

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

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

457 {
458  if constexpr (libMesh::ScalarTraits<T>::value ||
460  {
463  "Mathematical types must be same for arguments to relativelyFuzzEqual");
465  return absoluteFuzzyEqual(
466  var1,
467  var2,
468  tol * (std::abs(MetaPhysicL::raw_value(var1)) + std::abs(MetaPhysicL::raw_value(var2))));
469  else if constexpr (libMesh::TensorTools::TensorTraits<T>::rank == 1)
470  {
471  for (const auto i : make_range(Moose::dim))
472  if (!relativeFuzzyEqual(var1(i), var2(i), tol))
473  return false;
474 
475  return true;
476  }
477  else if constexpr (libMesh::TensorTools::TensorTraits<T>::rank == 2)
478  {
479  for (const auto i : make_range(Moose::dim))
480  for (const auto j : make_range(Moose::dim))
481  if (!relativeFuzzyEqual(var1(i, j), var2(i, j), tol))
482  return false;
483 
484  return true;
485  }
486  }
487  else
488  {
489  // We dare to dream
490  mooseAssert(var1.size() == var2.size(), "These must be the same size");
491  for (const auto i : index_range(var1))
492  if (!relativeFuzzyEqual(var1(i), var2(i), tol))
493  return false;
494 
495  return true;
496  }
497 }
MetaPhysicL::DualNumber< V, D, asd > abs(const MetaPhysicL::DualNumber< V, D, asd > &a)
Definition: ADReal.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:346
auto raw_value(const Eigen::Map< T > &in)
Definition: ADReal.h:73
static constexpr std::size_t dim
This is the dimension of all vector and tensor datastructures used in MOOSE.
Definition: Moose.h:148
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:454
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< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&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 514 of file MooseUtils.h.

Referenced by FunctionDT::computeDT().

517 {
519  var1,
520  var2,
522 }
auto raw_value(const Eigen::Map< T > &in)
Definition: ADReal.h:73
ADRealEigenVector< T, D, asd > abs(const ADRealEigenVector< T, D, asd > &)
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:369

◆ relativeFuzzyGreaterThan()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::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 538 of file MooseUtils.h.

541 {
542  return (absoluteFuzzyGreaterThan(
543  var1,
544  var2,
546 }
auto raw_value(const Eigen::Map< T > &in)
Definition: ADReal.h:73
ADRealEigenVector< T, D, asd > abs(const ADRealEigenVector< T, D, asd > &)
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:392

◆ relativeFuzzyLessEqual()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::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 563 of file MooseUtils.h.

566 {
567  return (absoluteFuzzyLessEqual(
568  var1,
569  var2,
571 }
auto raw_value(const Eigen::Map< T > &in)
Definition: ADReal.h:73
ADRealEigenVector< T, D, asd > abs(const ADRealEigenVector< T, D, asd > &)
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:415

◆ relativeFuzzyLessThan()

template<typename T , typename T2 , typename T3 = T, typename std::enable_if< ScalarTraits< T >::value &&ScalarTraits< T2 >::value &&ScalarTraits< T3 >::value, int >::type = 0>
bool MooseUtils::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 587 of file MooseUtils.h.

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

590 {
591  return (absoluteFuzzyLessThan(
592  var1,
593  var2,
595 }
auto raw_value(const Eigen::Map< T > &in)
Definition: ADReal.h:73
ADRealEigenVector< T, D, asd > abs(const ADRealEigenVector< T, D, asd > &)
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:437

◆ removeColor()

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

remove ANSI escape sequences for terminal color from msg

Definition at line 708 of file MooseUtils.C.

Referenced by Console::writeStreamToFile().

709 {
710  pcrecpp::RE re("(\\33\\[3[0-7]m))", pcrecpp::DOTALL());
711  re.GlobalReplace(std::string(""), &msg);
712  return msg;
713 }

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

492 {
493  // split path into directories with delimiter '/'
494  std::vector<std::string> split_dir_names;
495  MooseUtils::tokenize(dir_name, split_dir_names);
496 
497  auto n = split_dir_names.size();
498 
499  // remove '.' and '..' when possible
500  auto i = n;
501  i = 0;
502  while (i != n)
503  {
504  if (split_dir_names[i] == ".")
505  {
506  for (auto j = i + 1; j < n; ++j)
507  split_dir_names[j - 1] = split_dir_names[j];
508  --n;
509  }
510  else if (i > 0 && split_dir_names[i] == ".." && split_dir_names[i - 1] != "..")
511  {
512  for (auto j = i + 1; j < n; ++j)
513  split_dir_names[j - 2] = split_dir_names[j];
514  n -= 2;
515  --i;
516  }
517  else
518  ++i;
519  }
520  if (n == 0)
521  return;
522 
523  split_dir_names.resize(n);
524 
525  // start removing directories recursively
526  std::string base_dir = dir_name[0] == '/' ? "" : ".";
527  for (i = n; i > 0; --i)
528  {
529  std::string cur_dir = base_dir;
530  auto j = i;
531  for (j = 0; j < i; ++j)
532  cur_dir += "/" + split_dir_names[j];
533 
534  // listDir should return at least '.' and '..'
535  if (pathExists(cur_dir) && listDir(cur_dir).size() == 2)
536  {
537  auto code = rmdir(cur_dir.c_str());
538  if (code != 0)
539  {
540  std::string msg = "Failed removing directory " + dir_name;
541  if (throw_on_failure)
542  throw std::invalid_argument(msg);
543  else
544  mooseError(msg);
545  }
546  }
547  else
548  // stop removing
549  break;
550  }
551 }
void tokenize(const std::string &str, std::vector< T > &elements, unsigned int min_len=1, const std::string &delims="/")
This function will split the passed in string on a set of delimiters appending the substrings to the ...
Definition: MooseUtils.h:779
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:299
std::list< std::string > listDir(const std::string path, bool files_only=false)
Definition: MooseUtils.C:768
bool pathExists(const std::string &path)
Definition: MooseUtils.C:240

◆ replaceAll()

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

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

Definition at line 134 of file MooseUtils.C.

Referenced by ReporterDebugOutput::output(), and MooseBaseParameterInterface::paramErrorMsg().

135 {
136  size_t start_pos = 0;
137  while ((start_pos = str.find(from, start_pos)) != std::string::npos)
138  {
139  str.replace(start_pos, from.length(), to);
140  start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
141  }
142  return str;
143 }

◆ 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:70
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:70
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 1135 of file MooseUtils.C.

Referenced by Moose::Builder::setScalarParameter< ReporterName, std::string >(), Moose::Builder::setVectorParameter< CLIArgString, std::string >(), and Moose::Builder::setVectorParameter< ReporterName, std::string >().

1136 {
1137  std::vector<std::string> output;
1138  std::size_t count = 0;
1139  size_t prev = str.length(), pos = str.length();
1140  do
1141  {
1142  pos = str.rfind(delimiter, prev);
1143  output.insert(output.begin(), str.substr(pos + delimiter.length(), prev - pos));
1144  prev = pos - delimiter.length();
1145  count += 1;
1146  } while (pos != std::string::npos && pos > 0 && count < max_count);
1147 
1148  if (pos != std::string::npos)
1149  output.insert(output.begin(), str.substr(0, pos));
1150 
1151  return output;
1152 }
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 64 of file MooseUtils.C.

Referenced by MooseApp::runInputs().

65 {
66  auto build_loc = pathjoin(Moose::getExecutablePath(), "run_tests");
67  if (pathExists(build_loc) && checkFileReadable(build_loc))
68  return build_loc;
69  // TODO: maybe no path prefix - just moose_test_runner here?
70  return pathjoin(Moose::getExecutablePath(), "moose_test_runner");
71 }
std::string getExecutablePath()
This function returns the PATH of the running executable.
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:256
std::filesystem::path pathjoin(const std::filesystem::path &p)
Definition: MooseUtils.C:58
bool pathExists(const std::string &path)
Definition: MooseUtils.C:240

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

Referenced by SerializerGuard::SerializerGuard().

360 {
361  // unless we are the first processor...
362  if (comm.rank() > 0)
363  {
364  // ...wait for the previous processor to finish
365  int dummy = 0;
366  comm.receive(comm.rank() - 1, dummy);
367  }
368  else if (warn)
369  mooseWarning("Entering serial execution block (use only for debugging)");
370 }
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:333
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 373 of file MooseUtils.C.

Referenced by SerializerGuard::~SerializerGuard().

374 {
375  // unless we are the last processor...
376  if (comm.rank() + 1 < comm.size())
377  {
378  // ...notify the next processor of its turn
379  int dummy = 0;
380  comm.send(comm.rank() + 1, dummy);
381  }
382 
383  comm.barrier();
384  if (comm.rank() == 0 && warn)
385  mooseWarning("Leaving serial execution block (use only for debugging)");
386 }
void mooseWarning(Args &&... args)
Emit a warning message with the given stringified, concatenated args.
Definition: MooseError.h:333
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 1172 of file MooseUtils.h.

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

1173 {
1174  while (first1 != last1 && first2 != last2)
1175  {
1176  if (*first1 == *first2)
1177  return true;
1178 
1179  if (*first1 < *first2)
1180  ++first1;
1181  else if (*first1 > *first2)
1182  ++first2;
1183  }
1184  return false;
1185 }

◆ setsIntersect() [2/2]

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

Definition at line 1189 of file MooseUtils.h.

1190 {
1191  return setsIntersect(s1.begin(), s1.end(), s2.begin(), s2.end());
1192 }
bool setsIntersect(const T &s1, const T &s2)
Definition: MooseUtils.h:1189

◆ shortName()

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

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

Definition at line 598 of file MooseUtils.C.

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

599 {
600  return name.substr(name.find_last_of('/') != std::string::npos ? name.find_last_of('/') + 1 : 0);
601 }
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:70
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 1115 of file MooseUtils.C.

Referenced by SONDefinitionFormatter::addParameters(), MultiApp::createApp(), and MeshGenerator::generateInternal().

1116 {
1117  std::vector<std::string> output;
1118  std::size_t count = 0;
1119  size_t prev = 0, pos = 0;
1120  do
1121  {
1122  pos = str.find(delimiter, prev);
1123  output.push_back(str.substr(prev, pos - prev));
1124  prev = pos + delimiter.length();
1125  count += 1;
1126  } while (pos != std::string::npos && count < max_count);
1127 
1128  if (pos != std::string::npos)
1129  output.push_back(str.substr(prev));
1130 
1131  return output;
1132 }
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 231 of file MooseUtils.h.

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

232 {
233  const auto p = std::filesystem::path(std::string(full_file));
234  // Error if path ends with /
235  if (!p.has_filename())
236  mooseError("Invalid full file name: ", p);
237 
238  const auto d = p.parent_path();
239  return {d.empty() ? "." : d, p.filename()};
240 }
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:299

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

Referenced by FormattedTable::printTable().

1063 {
1064  return convert<int>(input, throw_on_failure);
1065 }
int convert< int >(const std::string &str, bool throw_on_failure)
Definition: MooseUtils.C:999

◆ stripExtension()

std::string MooseUtils::stripExtension ( const std::string &  s)

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

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

Definition at line 413 of file MooseUtils.C.

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

414 {
415  auto pos = s.rfind(".");
416  if (pos != std::string::npos)
417  return s.substr(0, pos);
418  return s;
419 }

◆ 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(), DistributedRectilinearMeshGenerator::paritionSquarely(), MaterialPropertyStorage::shift(), shuffle(), swap(), MooseUtils::StaticallyAllocatedSet< T, N >::swap(), MooseArray< libMesh::VectorValue >::swap(), and MooseUtils::Buffer< T >::swap().

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

Definition at line 779 of file MooseUtils.h.

Referenced by CommandLine::addArgument(), InputParameters::addCommandLineParamHelper(), Syntax::addDependencySets(), MooseEnumBase::addEnumerationName(), MooseEnumBase::addEnumerationNames(), JsonInputFileFormatter::addLine(), InputParameters::addParamNamesToGroup(), MultiMooseEnum::erase(), TransfiniteMeshGenerator::getDiscreteEdge(), MooseApp::getLibrarySearchPaths(), TransfiniteMeshGenerator::getParsedEdge(), Syntax::isAssociated(), makedirs(), MultiMooseEnum::operator=(), FunctionMaterialPropertyDescriptor< is_ad >::parseDependentSymbols(), FunctionMaterialPropertyDescriptor< is_ad >::parseDerivative(), pathContains(), InputFileFormatter::printParams(), MultiMooseEnum::push_back(), MooseUtils::DelimitedFileReader::readColumnData(), InputParameters::registerBuildableTypes(), removedirs(), Moose::Builder::setDoubleIndexParameter(), Moose::Builder::setScalarParameter(), Moose::Builder::setTripleIndexParameter(), Moose::Builder::setVectorVectorComponentParameter(), MooseApp::showInputs(), SingleMatrixPreconditioner::SingleMatrixPreconditioner(), tokenizeAndConvert(), and wildCardMatch().

783 {
784  elements.clear();
785 
786  std::string::size_type last_pos = str.find_first_not_of(delims, 0);
787  std::string::size_type pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
788 
789  while (last_pos != std::string::npos)
790  {
791  elements.push_back(str.substr(last_pos, pos - last_pos));
792  // skip delims between tokens
793  last_pos = str.find_first_not_of(delims, pos);
794  if (last_pos == std::string::npos)
795  break;
796  pos = str.find_first_of(delims, std::min(last_pos + min_len, str.size()));
797  }
798 }
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 806 of file MooseUtils.h.

Referenced by SplitMeshAction::act(), TransfiniteMeshGenerator::getCircarcEdge(), TransfiniteMeshGenerator::getDiscreteEdge(), and MooseApp::MooseApp().

809 {
810  std::vector<std::string> tokens;
811  MooseUtils::tokenize(str, tokens, 1, delimiter);
812  tokenized_vector.resize(tokens.size());
813  for (unsigned int j = 0; j < tokens.size(); ++j)
814  {
815  std::stringstream ss(trim(tokens[j]));
816  // we have to make sure that the conversion succeeded _and_ that the string
817  // was fully read to avoid situations like [conversion to Real] 3.0abc to work
818  if ((ss >> tokenized_vector[j]).fail() || !ss.eof())
819  return false;
820  }
821  return true;
822 }
void tokenize(const std::string &str, std::vector< T > &elements, unsigned int min_len=1, const std::string &delims="/")
This function will split the passed in string on a set of delimiters appending the substrings to the ...
Definition: MooseUtils.h:779
std::string trim(const std::string &str, const std::string &white_space=" \\\)
Standard scripting language trim function.
Definition: MooseUtils.C:214
charT const * delimiter
Definition: InfixIterator.h:34

◆ toLower()

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

Convert supplied string to lower case.

name The string to convert upper case.

Definition at line 1048 of file MooseUtils.C.

Referenced by MooseServer::getDocumentSymbolKind(), SubProblem::getVariableHelper(), ConsoleUtils::outputRelationshipManagerInformation(), and WorkBalance::WorkBalance().

1049 {
1050  std::string lower(name);
1051  std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
1052  return lower;
1053 }

◆ toUpper()

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

Convert supplied string to upper case.

name The string to convert upper case.

Definition at line 1040 of file MooseUtils.C.

Referenced by SubProblem::addMatrixTag(), SubProblem::addVectorTag(), MooseEnumBase::find(), SubProblem::getMatrixTagID(), SubProblem::getVectorTagID(), SubProblem::matrixTagExists(), MooseEnumItem::operator!=(), MooseEnumItem::operator==(), MooseEnum::operator==(), moose::internal::ExecFlagRegistry::registerFlag(), Coupleable::vectorTagDofValueHelper(), SubProblem::vectorTagExists(), and Coupleable::vectorTagValueHelper().

1041 {
1042  std::string upper(name);
1043  std::transform(upper.begin(), upper.end(), upper.begin(), ::toupper);
1044  return upper;
1045 }

◆ trim()

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

Standard scripting language trim function.

Definition at line 214 of file MooseUtils.C.

Referenced by CommandLine::addArgument(), MooseEnumBase::addEnumerationName(), JsonInputFileFormatter::addLine(), JsonInputFileFormatter::addParameters(), SONDefinitionFormatter::addParameters(), MooseServer::addParametersToList(), InputParameters::appendFunctorDescription(), MooseServer::formatDocument(), MooseUtils::DelimitedFileReader::preprocessLine(), InputFileFormatter::printParams(), MooseUtils::DelimitedFileReader::readColumnData(), and tokenizeAndConvert().

215 {
216  const auto begin = str.find_first_not_of(white_space);
217  if (begin == std::string::npos)
218  return ""; // no content
219  const auto end = str.find_last_not_of(white_space);
220  return str.substr(begin, end - begin + 1);
221 }

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

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

567 {
568  pcrecpp::StringPiece input(underscore_name);
569  pcrecpp::RE re("([^_]*)(_|$)");
570 
571  std::string result;
572  std::string us, not_us;
573  bool make_upper = leading_upper_case;
574  while (re.Consume(&input, &not_us, &us))
575  {
576  if (not_us.length() > 0)
577  {
578  if (make_upper)
579  {
580  result += std::toupper(not_us[0]);
581  if (not_us.length() > 1)
582  result += not_us.substr(1);
583  }
584  else
585  result += not_us;
586  }
587  if (us == "")
588  break;
589 
590  // Toggle flag so next match is upper cased
591  make_upper = true;
592  }
593 
594  return result;
595 }

◆ wildcardEqual() [1/3]

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

Definition at line 1029 of file MooseUtils.h.

Referenced by findPair().

1030 {
1031  return a == b;
1032 }

◆ wildcardEqual() [2/3]

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

Definition at line 1036 of file MooseUtils.h.

1037 {
1038  return true;
1039 }

◆ wildcardEqual() [3/3]

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

Definition at line 1042 of file MooseUtils.h.

1043 {
1044  return true;
1045 }

◆ wildCardMatch()

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

Definition at line 874 of file MooseUtils.C.

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

875 {
876  // Assume that an empty string matches anything
877  if (search_string == "")
878  return true;
879 
880  // transform to lower for case insenstive matching
881  std::transform(name.begin(), name.end(), name.begin(), (int (*)(int))std::toupper);
882  std::transform(search_string.begin(),
883  search_string.end(),
884  search_string.begin(),
885  (int (*)(int))std::toupper);
886 
887  // exact match!
888  if (search_string.find("*") == std::string::npos)
889  return search_string == name;
890 
891  // wildcard
892  std::vector<std::string> tokens;
893  MooseUtils::tokenize(search_string, tokens, 1, "*");
894 
895  size_t pos = 0;
896  for (unsigned int i = 0; i < tokens.size() && pos != std::string::npos; ++i)
897  {
898  pos = name.find(tokens[i], pos);
899  // See if we have a leading wildcard
900  if (search_string[0] != '*' && i == 0 && pos != 0)
901  return false;
902  }
903 
904  if (pos != std::string::npos && tokens.size() > 0)
905  {
906  // Now see if we have a trailing wildcard
907  size_t last_token_length = tokens.back().length();
908  if (*search_string.rbegin() == '*' || pos == name.size() - last_token_length)
909  return true;
910  else
911  return false;
912  }
913  else
914  return false;
915 }
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 ...
Definition: MooseUtils.h:779
void ErrorVector unsigned int

Variable Documentation

◆ Any

const struct MooseUtils::AnyType MooseUtils::Any
static