OGS
BaseLib Namespace Reference

Namespaces

namespace  detail
namespace  IO
namespace  MPI
namespace  TMP

Classes

class  ConfigTree
class  CPUTime
 Count CPU time. More...
class  GradualSubdivision
class  GradualSubdivisionFixedNum
class  Histogram
class  ISubdivision
class  MemWatch
struct  Overloaded
struct  PolymorphicRandomAccessContainerView
class  Range
 Wraps a pair of iterators for use as a range in range-based for-loops. More...
class  RunTime
 Count the running time. More...
struct  StrongType
class  TCLAPOutput
class  UniformSubdivision

Functions

template<typename T>
std::vector< T > excludeObjectCopy (std::vector< T > const &src_vec, std::vector< std::size_t > const &exclude_positions)
template<typename T>
void excludeObjectCopy (std::vector< T > const &src_vec, std::vector< std::size_t > const &exclude_positions, std::vector< T > &dest_vec)
template<ranges::input_range Range>
ranges::range_reference_t< RangefindElementOrError (Range &range, std::predicate< ranges::range_reference_t< Range > > auto &&predicate, std::invocable auto error_callback)
template<typename Map, typename Key, typename Value>
void insertIfKeyUniqueElseError (Map &map, Key const &key, Value &&value, std::string const &error_message)
template<typename Map, typename Key>
OGS_NO_DANGLING Map::mapped_type & getOrError (Map &map, Key const &key, std::string const &error_message)
template<typename Map, typename Key>
OGS_NO_DANGLING Map::mapped_type const & getOrError (Map const &map, Key const &key, std::string const &error_message)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
template<typename Container, typename Predicate>
OGS_NO_DANGLING Container::value_type const & getIfOrError (Container const &container, Predicate &&predicate, std::string const &error_message)
template<ranges::input_range Range>
requires std::totally_ordered<ranges::range_value_t<Range>> && std::copyable<ranges::range_value_t<Range>>
std::vector< ranges::range_value_t< Range > > getDuplicates (Range &&range)
template<typename T>
void makeVectorUnique (std::vector< T > &v)
template<typename T, class Compare>
void makeVectorUnique (std::vector< T > &v, Compare comp)
template<typename ValueType, typename IndexType>
void reorderVector (std::vector< ValueType > &v, std::vector< IndexType > const &order)
template<typename Container>
void uniquePushBack (Container &container, typename Container::value_type const &element)
template<typename Container>
std::optional< typename Container::value_type > findFirstNotEqualElement (Container const &container, typename Container::value_type const &element)
template<typename Container>
std::size_t findIndex (Container const &container, typename Container::value_type const &element)
template<typename T>
void cleanupVectorElements (std::vector< T * > &items)
template<typename T1, typename... Args>
void cleanupVectorElements (std::vector< T1 * > &dependent_items, Args &&... args)
template<ranges::range R>
requires std::is_integral_v<ranges::range_value_t<R>>
std::vector< ranges::range_value_t< R > > sizesToOffsets (R const &sizes)
template<typename List>
constexpr bool any_of (List const &values)
 Checks if any of the elements in the given list is true.
template<typename List>
constexpr bool all_of (List const &values)
 Checks if all of the elements in the given list are true.
template<typename List>
constexpr bool none_of (List const &values)
 Checks if none of the elements in the given list are true.
void checkAndInvalidate (ConfigTree &conf)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void checkAndInvalidate (ConfigTree *const conf)
void checkAndInvalidate (std::unique_ptr< ConfigTree > const &conf)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
ConfigTree makeConfigTree (const std::string &filepath, const bool be_ruthless, const std::string &toplevel_tag, std::stringstream &prj_stream)
ConfigTree makeConfigTreeFromFile (const std::string &filepath, const bool be_ruthless, const std::string &toplevel_tag)
template<typename E>
constexpr auto to_underlying (E e) noexcept
 Converts an enumeration to its underlying type.
int date2int (int y, int m, int d)
std::string int2date (int date)
std::string date2string (double ddate)
int strDate2int (const std::string &s)
int xmlDate2int (const std::string &s)
std::string formatDate (std::chrono::time_point< std::chrono::system_clock > const &time)
std::string demangle (const char *mangled_name)
template<typename T>
std::string typeToString ()
template<typename T>
std::string typeToString (T &&)
bool IsFileExisting (const std::string &strFilename)
 Returns true if given file exists.
std::tuple< std::string, std::string::size_type, std::string::size_type > getParenthesizedString (std::string const &in, char const open_char, char const close_char, std::string::size_type pos)
std::string containsKeyword (std::string const &str, std::string const &keyword)
template<typename T>
bool substituteKeyword (std::string &result, std::string const &parenthesized_string, std::string::size_type const begin, std::string::size_type const end, std::string const &keyword, T &data)
std::string constructFormattedFileName (std::string const &format_specification, std::string const &mesh_name, int const timestep, double const t, int const iteration, bool const converged)
double swapEndianness (double const &v)
std::string dropFileExtension (std::string const &filename)
std::string extractBaseName (std::string const &pathname)
std::string extractBaseNameWithoutExtension (std::string const &pathname)
std::string getFileExtension (const std::string &path)
bool hasFileExtension (std::string const &extension, std::string const &filename)
std::string extractPath (std::string const &pathname)
std::string joinPaths (std::string const &pathA, std::string const &pathB)
void removeFile (std::string const &filename)
void removeFiles (std::vector< std::string > const &files)
bool createOutputDirectory (std::string const &dir)
std::vector< double > readDoublesFromBinaryFile (const std::string &filename, const std::string &project_directory)
template<typename T>
readBinaryValue (std::istream &in)
template float readBinaryValue< float > (std::istream &)
template double readBinaryValue< double > (std::istream &)
template<typename T>
std::vector< T > readBinaryVector (std::string const &filename, std::size_t const start_element, std::size_t const num_elements)
template std::vector< float > readBinaryVector< float > (std::string const &, std::size_t const, std::size_t const)
template std::vector< double > readBinaryVector< double > (std::string const &, std::size_t const, std::size_t const)
template<typename T>
void writeValueBinary (std::ostream &out, T const &val)
 write value as binary into the given output stream
template void writeValueBinary< std::size_t > (std::ostream &, std::size_t const &)
template<typename T>
swapEndianness (T const &v)
template<typename T>
std::ostream & operator<< (std::ostream &os, const Histogram< T > &h)
template std::ostream & operator<< (std::ostream &os, const Histogram< double > &h)
void setConsoleLogLevel (std::string const &level_string)
void initOGSLogger (std::string const &log_level)
int getNumberOfThreadsFromEnv (char const *env_var_name)
int getNumberOfAssemblyThreads ()
int getNumberOfThreads ()
int getNumberOfChemistryThreads ()
void traverseIncludes (xmlDoc *doc, xmlNode *node, std::filesystem::path const &prj_dir)
void replaceIncludes (std::stringstream &prj_stream, std::filesystem::path const &prj_dir)
void patchStream (std::string const &patch_file, std::stringstream &prj_stream, bool after_includes=false)
void readAndPatchPrj (std::stringstream &prj_stream, std::string &prj_file, std::vector< std::string > &patch_files)
void prepareProjectFile (std::stringstream &prj_stream, const std::string &filepath, const std::vector< std::string > &patch_files, bool write_prj, const std::string &out_directory)
 Applies includes and patch files to project file.
template<typename It1, typename It2, typename Comparator>
void quicksort (It1 first1, It1 last1, It2 first2, Comparator compare)
template<typename It1, typename It2>
void quicksort (It1 first1, It1 last1, It2 first2)
template<typename T1, typename T2 = std::size_t>
void quicksort (T1 *array, std::size_t beg, std::size_t end, T2 *perm)
template<typename T1, typename T2 = std::size_t>
void quicksort (std::vector< T1 > &array, std::size_t beg, std::size_t end, std::vector< T2 > &perm)
template<typename T1, typename T2 = std::size_t>
void quicksort (std::vector< T1 * > &array, std::size_t beg, std::size_t end, std::vector< T2 > &perm)
std::vector< std::string > splitString (std::string const &str)
std::list< std::string > splitString (const std::string &str, char delim)
std::string replaceString (const std::string &searchString, const std::string &replaceString, std::string stringToReplace)
void trim (std::string &str, char ch)
void simplify (std::string &str)
std::string format (const char *format_str,...)
std::string randomString (std::size_t length)
 Returns a random string of the given length containing just a-z,A-Z,0-9.
std::string getUniqueName (std::vector< std::string > const &existing_names, std::string const &input_name)
 Append '-' and a number such that the name is unique.
std::expected< int, std::string > parseInteger (std::string_view const str)
template<typename T>
str2number (const std::string &str)
template<typename T>
std::optional< std::vector< T > > tryParseVector (std::string const &raw, std::size_t *bad_token_idx)
std::string defaultLogLevel ()
TCLAP::ValueArg< std::string > makeLogLevelArg ()
template<typename T>
const char * type_name ()
template<>
const char * type_name< std::string > ()
template<>
const char * type_name< int > ()
template<>
const char * type_name< double > ()
template<>
const char * type_name< float > ()
template<>
const char * type_name< bool > ()
template<>
const char * type_name< size_t > ()
template<>
const char * type_name< long > ()
template<>
const char * type_name< unsigned > ()

Variables

std::shared_ptr< spdlog::logger > console

Function Documentation

◆ all_of()

template<typename List>
bool BaseLib::all_of ( List const & values)
constexpr

Checks if all of the elements in the given list are true.

Definition at line 327 of file Algorithm.h.

328{
329 // std::all_of is not constexpr enough in some STLs
330 for (auto& value : values)
331 {
332 if (!static_cast<bool>(value))
333 {
334 return false;
335 }
336 }
337
338 return true;
339}

◆ any_of()

template<typename List>
bool BaseLib::any_of ( List const & values)
constexpr

Checks if any of the elements in the given list is true.

Definition at line 311 of file Algorithm.h.

312{
313 // std::any_of is not constexpr enough in some STLs
314 for (auto& value : values)
315 {
316 if (static_cast<bool>(value))
317 {
318 return true;
319 }
320 }
321
322 return false;
323}

Referenced by BaseLib::TMP::contains(), and none_of().

◆ checkAndInvalidate() [1/3]

void BaseLib::checkAndInvalidate ( ConfigTree & conf)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 535 of file ConfigTree.cpp.

536{
537 conf.checkAndInvalidate();
538}

◆ checkAndInvalidate() [2/3]

void BaseLib::checkAndInvalidate ( ConfigTree *const conf)

Check if conf has been read entirely and invalidate it.

This method can safely be called on nullptr's.

See also
ConfigTree::checkAndInvalidate()

Definition at line 540 of file ConfigTree.cpp.

541{
542 if (conf)
543 {
544 conf->checkAndInvalidate();
545 }
546}

◆ checkAndInvalidate() [3/3]

void BaseLib::checkAndInvalidate ( std::unique_ptr< ConfigTree > const & conf)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 548 of file ConfigTree.cpp.

549{
550 if (conf)
551 {
552 conf->checkAndInvalidate();
553 }
554}

◆ cleanupVectorElements() [1/2]

template<typename T>
void BaseLib::cleanupVectorElements ( std::vector< T * > & items)

◆ cleanupVectorElements() [2/2]

template<typename T1, typename... Args>
void BaseLib::cleanupVectorElements ( std::vector< T1 * > & dependent_items,
Args &&... args )

Util function to cleanup the memory of multiple containers containing pointers to objects. Sometimes, there are dependencies between the pointer items in the containers. For instance, a GeoLib::Polyline or a GeoLib::Surface depends on the GeoLib::Point pointers stored in a std::vector<GeoLib::Point*>. Then, the dependent items have to cleaned up before the GeoLib::Point objects are deleted. A similar relation exists between MeshLib::Element objects and MeshLib::Node objects.

Definition at line 291 of file Algorithm.h.

292{
293 cleanupVectorElements(dependent_items);
294 cleanupVectorElements(std::forward<Args>(args)...);
295}
void cleanupVectorElements(std::vector< T * > &items)
Definition Algorithm.h:274

References cleanupVectorElements().

◆ constructFormattedFileName()

std::string BaseLib::constructFormattedFileName ( std::string const & format_specification,
std::string const & mesh_name,
int const timestep,
double const t,
int const iteration,
bool const converged )

Definition at line 109 of file FileTools.cpp.

115{
116 char const open_char = '{';
117 char const close_char = '}';
118 std::string::size_type begin = 0;
119 std::string::size_type end = std::string::npos;
120 std::string result = format_specification;
121
122 while (begin != std::string::npos)
123 {
124 auto length_before_substitution = result.length();
125 // find next parenthesized string
126 std::string str = "";
127 std::tie(str, begin, end) =
128 getParenthesizedString(result, open_char, close_char, begin);
129 if (!substituteKeyword(result, str, begin, end, "timestep", timestep) &&
130 !substituteKeyword(result, str, begin, end, "time", t) &&
131 !substituteKeyword(result, str, begin, end, "iteration",
132 iteration) &&
133 !substituteKeyword(result, str, begin, end, "converged", converged))
134 {
135 substituteKeyword(result, str, begin, end, "meshname", mesh_name);
136 }
137 begin = end - (length_before_substitution - result.length());
138 }
139
140 return result;
141}
std::tuple< std::string, std::string::size_type, std::string::size_type > getParenthesizedString(std::string const &in, char const open_char, char const close_char, std::string::size_type pos)
Definition FileTools.cpp:29
bool substituteKeyword(std::string &result, std::string const &parenthesized_string, std::string::size_type const begin, std::string::size_type const end, std::string const &keyword, T &data)
Definition FileTools.cpp:62

References getParenthesizedString(), and substituteKeyword().

Referenced by ProcessLib::OutputVTKFormat::constructFilename(), ProcessLib::OutputXDMFHDF5Format::constructFilename(), and ProcessLib::OutputVTKFormat::constructPVDName().

◆ containsKeyword()

std::string BaseLib::containsKeyword ( std::string const & str,
std::string const & keyword )

Definition at line 51 of file FileTools.cpp.

52{
53 auto const position = str.find(keyword);
54 if (position != std::string::npos)
55 {
56 return str.substr(0, position);
57 }
58 return "";
59}

Referenced by substituteKeyword().

◆ createOutputDirectory()

bool BaseLib::createOutputDirectory ( std::string const & dir)

Definition at line 221 of file FileTools.cpp.

222{
223 if (dir.empty())
224 {
225 return false;
226 }
227
228 std::error_code mkdir_err;
229 if (std::filesystem::create_directories(dir, mkdir_err))
230 {
231 INFO("Output directory {:s} created.", dir);
232 }
233 else if (mkdir_err.value() != 0)
234 {
235 WARN("Could not create output directory {:s}. Error code {:d}, {:s}",
236 dir, mkdir_err.value(), mkdir_err.message());
237 return false;
238 }
239 return true;
240}
void INFO(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:28
void WARN(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:34

References INFO(), and WARN().

Referenced by OGSSimulation::OGSSimulation(), and main().

◆ date2int()

int BaseLib::date2int ( int y,
int m,
int d )

Converts three integers representing a date into a double. Note: It is not really checked if the date actually makes sense.

Definition at line 15 of file DateTools.cpp.

16{
17 if ((y < 1000 || y > 9999) || (m < 1 || m > 12) || (d < 1 || d > 31))
18 {
19 WARN("date2int(): Input not in expected range.");
20 return 0;
21 }
22
23 int ddate(0);
24 ddate = y * 10000;
25 ddate += (m * 100);
26 ddate += d;
27
28 return ddate;
29}

References WARN().

Referenced by strDate2int(), and xmlDate2int().

◆ date2string()

std::string BaseLib::date2string ( double ddate)

Converts a double representing a date into a string. Note: It is not really checked if the date actually makes sense.

Parameters
ddateNumber containing date in double format yyyymmdd
Returns
A string containing the date in format "dd.mm.yyyy".

Definition at line 54 of file DateTools.cpp.

55{
56 if (ddate < 10000101 || ddate > 99991231)
57 {
58 WARN("date2String(): Input not in expected format.");
59 return "0.0.0000";
60 }
61
62 auto rest(static_cast<int>(ddate));
63 auto y = static_cast<int>(std::floor(rest / 10000.0));
64 rest = rest % (y * 10000);
65 auto m = static_cast<int>(std::floor(rest / 100.0));
66 if (m < 1 || m > 12)
67 {
68 WARN("date2String(): month not in [1:12].");
69 }
70 rest = rest % (m * 100);
71 int d = rest;
72 if (d < 1 || d > 31)
73 {
74 WARN("date2String(): day not in [1:31].");
75 }
76
77 std::string day = std::to_string(d);
78 if (d < 10)
79 {
80 day = "0" + day;
81 }
82 std::string month = std::to_string(m);
83 if (m < 10)
84 {
85 month = "0" + month;
86 }
87 std::string s = std::to_string(y) + "-" + month + "-" + day;
88 return s;
89}

References WARN().

Referenced by GeoLib::IO::XmlStnInterface::writeBoreholeData().

◆ defaultLogLevel()

std::string BaseLib::defaultLogLevel ( )

Definition at line 10 of file TCLAPArguments.cpp.

11{
12#ifdef NDEBUG
13 return "info";
14#else
15 return "all";
16#endif
17}

Referenced by OGSSimulation::OGSSimulation(), and makeLogLevelArg().

◆ demangle()

std::string BaseLib::demangle ( const char * mangled_name)

Non-template helper function for demangling mangled type names. Converts a C++ ABI mangled name into a human-readable string. Uses C++ ABI demangling (GCC/Clang) or UnDecorateSymbolName (MSVC). Falls back to the mangled name if demangling fails. See https://gcc.gnu.org/onlinedocs/libstdc++/manual/ext_demangling.html for GCC/Clang details and https://learn.microsoft.com/en-us/windows/win32/api/dbghelp/nf-dbghelp-undecoratesymbolname for MSVC.

Definition at line 21 of file DemangleTypeInfo.cpp.

22{
23#ifdef _MSC_VER
24 // MSVC demangling using UnDecorateSymbolName
25 char demangled_buffer[1024] = {0};
26 if (UnDecorateSymbolName(mangled_name, demangled_buffer,
27 sizeof(demangled_buffer), UNDNAME_COMPLETE))
28 {
29 return demangled_buffer;
30 }
31#else
32 // GCC/Clang demangling using __cxa_demangle
33 int status = 0;
34 std::unique_ptr<char, decltype(&std::free)> demangled(
35 abi::__cxa_demangle(mangled_name, nullptr, nullptr, &status),
36 &std::free);
37
38 if (status == 0 && demangled)
39 {
40 return demangled.get();
41 }
42#endif
43
44 // Fallback to mangled name if demangling fails
45 return mangled_name;
46}

Referenced by BaseLib::MPI::allRanksThrowOrNone(), ApplicationUtils::SolverByElementTypeRegistry< SolverInterface, SolverImplementationTplTpl >::getFor(), NumLib::IntegrationMethodRegistry::getIntegrationMethod(), BaseLib::ConfigTree::markVisited(), ProcessLib::GenericLocalAssemblerFactory< LocalAssemblerInterface, NumLib::DefaultIntegrationMethodProvider, ConstructorArgs... >::operator()(), ProcessLib::HeatTransportBHE::LocalDataInitializer< LocalAssemblerInterface, LocalAssemblerDataSoil, LocalAssemblerDataBHE, ConstructorArgs >::operator()(), ProcessLib::LIE::HydroMechanics::LocalDataInitializer< LocalAssemblerInterface, LocalAssemblerDataMatrix, LocalAssemblerDataMatrixNearFracture, LocalAssemblerDataFracture, DisplacementDim, ConstructorArgs >::operator()(), ProcessLib::LIE::SmallDeformation::LocalDataInitializer< LocalAssemblerInterface, LocalAssemblerDataMatrix, LocalAssemblerDataMatrixNearFracture, LocalAssemblerDataFracture, DisplacementDim, ConstructorArgs >::operator()(), typeToString(), and typeToString().

◆ dropFileExtension()

std::string BaseLib::dropFileExtension ( std::string const & filename)

Returns a string with file extension as found by getFileExtension() dropped.

Definition at line 165 of file FileTools.cpp.

166{
167 auto const filename_path = std::filesystem::path(filename);
168 return (filename_path.parent_path() / filename_path.stem()).string();
169}

Referenced by convert(), extractBaseNameWithoutExtension(), VtkRaster::findWorldFile(), identifyAndWriteBoundaryMeshes(), main(), FileIO::Gocad::GocadAsciiReader::readFile(), MeshLib::IO::readMeshFromFile(), writeCsvOutput(), and writeMeshOutput().

◆ excludeObjectCopy() [1/2]

template<typename T>
std::vector< T > BaseLib::excludeObjectCopy ( std::vector< T > const & src_vec,
std::vector< std::size_t > const & exclude_positions )

excludeObjectCopy copies only those objects that position within the source vector is not in the exclude_positions vector. The implementation of the algorithm requires that the given positions in exclude_positions are sorted in ascending order.

Parameters
src_vecthe vector of source objects
exclude_positionsthe positions of objects in the source vector that do not have to be copied
Returns
vector that contains the copied objects

Definition at line 36 of file Algorithm.h.

39{
40 std::vector<T> dest_vec;
41 if (exclude_positions.empty())
42 {
43 dest_vec = src_vec;
44 return dest_vec;
45 }
46
47 assert(exclude_positions.back() < src_vec.size());
48
49 std::copy_n(src_vec.cbegin(), exclude_positions[0],
50 std::back_inserter(dest_vec));
51 for (std::size_t i = 1; i < exclude_positions.size(); ++i)
52 {
53 std::copy_n(src_vec.cbegin() + exclude_positions[i - 1] + 1,
54 exclude_positions[i] - (exclude_positions[i - 1] + 1),
55 std::back_inserter(dest_vec));
56 }
57 std::copy(src_vec.cbegin() + exclude_positions.back() + 1, src_vec.cend(),
58 std::back_inserter(dest_vec));
59
60 return dest_vec;
61}

Referenced by MeshLib::PropertyVector< PROP_VAL_TYPE >::clone(), excludeObjectCopy(), and MeshToolsLib::removeElements().

◆ excludeObjectCopy() [2/2]

template<typename T>
void BaseLib::excludeObjectCopy ( std::vector< T > const & src_vec,
std::vector< std::size_t > const & exclude_positions,
std::vector< T > & dest_vec )

Definition at line 64 of file Algorithm.h.

67{
68 dest_vec = excludeObjectCopy(src_vec, exclude_positions);
69}
std::vector< T > excludeObjectCopy(std::vector< T > const &src_vec, std::vector< std::size_t > const &exclude_positions)
Definition Algorithm.h:36

References excludeObjectCopy().

◆ extractBaseName()

std::string BaseLib::extractBaseName ( std::string const & pathname)

Extracts basename from given pathname with extension.

Returns a string containing everything after the last path separator. If the the pathname does not contain a path separator original pathname is returned.

Definition at line 171 of file FileTools.cpp.

172{
173 return std::filesystem::path(pathname).filename().string();
174}

Referenced by OGSFileConverter::convertGLI2GML(), extractBaseNameWithoutExtension(), OGSFileConverter::fileExists(), MeshLib::IO::getVtuFileNameForPetscOutputWithoutExtension(), anonymous_namespace{postLIE.cpp}::postPVD(), FileIO::Legacy::readGLIFileV4(), and MeshLib::IO::NodePartitionedMeshReader::readMesh().

◆ extractBaseNameWithoutExtension()

std::string BaseLib::extractBaseNameWithoutExtension ( std::string const & pathname)

◆ extractPath()

std::string BaseLib::extractPath ( std::string const & pathname)

Extracts the path of a pathname.

Returns a string up to the last path separator not including it.

Definition at line 192 of file FileTools.cpp.

193{
194 return std::filesystem::path(pathname).parent_path().string();
195}

Referenced by MeshLib::IO::getVtuFileNameForPetscOutputWithoutExtension(), Simulation::initializeDataStructures(), main(), parseCommandLineArguments(), anonymous_namespace{postLIE.cpp}::postPVD(), readAndPatchPrj(), FileIO::Legacy::readGLIFileV4(), readVtuFileNames(), FileIO::Legacy::writeAllDataToGLIFileV4(), and FileIO::Legacy::writeGLIFileV4().

◆ findElementOrError()

template<ranges::input_range Range>
ranges::range_reference_t< Range > BaseLib::findElementOrError ( Range & range,
std::predicate< ranges::range_reference_t< Range > > auto && predicate,
std::invocable auto error_callback )

Returns reference to an element in the range satisfying the predicate. If no such element is found, error_callback is called and reference to past-the-end of the range is returned.

Definition at line 75 of file Algorithm.h.

79{
80 auto it =
81 ranges::find_if(range, std::forward<decltype(predicate)>(predicate));
82 if (it == ranges::end(range))
83 {
84 error_callback();
86 "Element not found in the input range. The user provided error "
87 "callback is meant not to return. That has not happened.");
88 }
89 return *it;
90}
#define OGS_FATAL(...)
Definition Error.h:10

References OGS_FATAL.

Referenced by MaterialPropertyLib::Phase::component(), MeshLib::findMeshByName(), MaterialLib::Solids::MFront::MFrontGeneric< DisplacementDim, boost::mp11::mp_list< Strain >, boost::mp11::mp_list< Stress >, boost::mp11::mp_list< Temperature > >::initializeInternalStateVariables(), OGSMesh::meshItemType(), MaterialPropertyLib::Medium::phase(), and ChemistryLib::PhreeqcIOData::PhreeqcIO::updateChemicalSystemFromOutput().

◆ findFirstNotEqualElement()

template<typename Container>
std::optional< typename Container::value_type > BaseLib::findFirstNotEqualElement ( Container const & container,
typename Container::value_type const & element )

Definition at line 245 of file Algorithm.h.

247{
248 auto const it =
249 std::find_if_not(container.begin(), container.end(),
250 [&element](typename Container::value_type const& e)
251 { return e == element; });
252 return it == container.end() ? std::nullopt : std::make_optional(*it);
253}

Referenced by ProcessLib::LIE::PostProcessTool::PostProcessTool().

◆ findIndex()

template<typename Container>
std::size_t BaseLib::findIndex ( Container const & container,
typename Container::value_type const & element )

Returns the index of first element in container or, if the element is not found a std::size_t maximum value.

The maximum value of std::size_t is chosen, because such an index cannot exist in a container; the maximum index is std::size_t::max-1.

Definition at line 261 of file Algorithm.h.

263{
264 auto const it = std::find(container.begin(), container.end(), element);
265 if (it == container.end())
266 {
267 return std::numeric_limits<std::size_t>::max();
268 }
269 return std::distance(container.begin(), it);
270}

Referenced by ProcessLib::LIE::PostProcessTool::PostProcessTool(), and ProcessLib::ComponentTransport::LookupTable::getTableEntryID().

◆ format()

std::string BaseLib::format ( const char * format_str,
... )

Definition at line 77 of file StringTools.cpp.

78{
79 va_list args;
80 va_start(args, format_str);
81 // get the number of chars to write
82 va_list args_tmp;
83 va_copy(args_tmp, args);
84 int char_length = std::vsnprintf(nullptr, 0, format_str, args_tmp);
85 va_end(args_tmp);
86 // allocate buffer and store formatted output there
87 std::vector<char> buffer(char_length + 1); // note +1 for null terminator
88 vsnprintf(buffer.data(), buffer.size(), format_str, args);
89 va_end(args);
90
91 return std::string(buffer.data());
92}

◆ formatDate()

std::string BaseLib::formatDate ( std::chrono::time_point< std::chrono::system_clock > const & time)

Formats the given time point according to RFC 3339 (cf. man-page of the unix date utility).

Example: 2006-08-14 02:34:56-06:00

Definition at line 126 of file DateTools.cpp.

128{
129 auto const time_t = std::chrono::system_clock::to_time_t(time);
130 char time_str[100];
131 if (std::strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S%z",
132 std::localtime(&time_t)))
133 {
134 return time_str;
135 }
136 return "FAILED FORMATTING THE GIVEN TIME POINT.";
137}

Referenced by OGSSimulation::OGSSimulation(), OGSSimulation::executeSimulation(), initializeLogger(), main(), Simulation::runTestDefinitions(), and signalHandler().

◆ getDuplicates()

template<ranges::input_range Range>
requires std::totally_ordered<ranges::range_value_t<Range>> && std::copyable<ranges::range_value_t<Range>>
std::vector< ranges::range_value_t< Range > > BaseLib::getDuplicates ( Range && range)

Returns the elements occurring more than once in the range range, each of them reported once. The result is sorted ascendingly because the duplicates are collected in a std::set, which the elements are copied into. The returned vector is empty if all elements are pairwise different.

Definition at line 178 of file Algorithm.h.

179{
180 using Element = ranges::range_value_t<Range>;
181
182 std::set<Element> seen;
183 std::set<Element> duplicates;
184 for (auto const& element : range)
185 {
186 if (!seen.insert(element).second)
187 {
188 duplicates.insert(element);
189 }
190 }
191
192 return {duplicates.begin(), duplicates.end()};
193}

Referenced by MeshLib::IntegrationPointMetaData::checkFieldNamesAreUnique(), ProcessLib::createSubmeshResiduumOutputConfig(), anonymous_namespace{CreateOutput.cpp}::getDuplicateOutputNames(), and anonymous_namespace{ProjectData.cpp}::readMeshes().

◆ getFileExtension()

◆ getIfOrError()

template<typename Container, typename Predicate>
OGS_NO_DANGLING Container::value_type const & BaseLib::getIfOrError ( Container const & container,
Predicate && predicate,
std::string const & error_message )

Returns the value of from the given container if such an entry fulfilling the predicate exists; otherwise an error_message is printed and the program is aborted.

Definition at line 157 of file Algorithm.h.

161{
162 auto it = std::find_if(begin(container), end(container), predicate);
163 if (it == end(container))
164 {
165 OGS_FATAL("Could not find element matching the predicate: {:s}",
166 error_message);
167 }
168 return *it;
169}

References OGS_FATAL, and OGS_NO_DANGLING.

Referenced by ProcessLib::createPerProcessData(), and ParameterLib::createRasterParameter().

◆ getNumberOfAssemblyThreads()

int BaseLib::getNumberOfAssemblyThreads ( )

Returns the number of threads to use for parallel assembly.

Returns
The number of threads set in OGS_ASM_THREADS environment variable or 1 if nothing is set.

Definition at line 67 of file OgsAsmThreads.cpp.

68{
69 return getNumberOfThreadsFromEnv("OGS_ASM_THREADS");
70}
int getNumberOfThreadsFromEnv(char const *env_var_name)

References getNumberOfThreadsFromEnv().

Referenced by getNumberOfChemistryThreads(), and getNumberOfThreads().

◆ getNumberOfChemistryThreads()

int BaseLib::getNumberOfChemistryThreads ( )

Returns the number of threads to use for parallel chemistry calculations. Priority: OGS_CHEM_THREADS env var, then OGS_ASM_THREADS env var, then 1.

Definition at line 12 of file OgsChemThreads.cpp.

13{
14 if (std::getenv("OGS_CHEM_THREADS"))
15 {
16 return getNumberOfThreadsFromEnv("OGS_CHEM_THREADS");
17 }
19}
int getNumberOfAssemblyThreads()

References getNumberOfAssemblyThreads(), and getNumberOfThreadsFromEnv().

◆ getNumberOfThreads()

int BaseLib::getNumberOfThreads ( )

Returns the maximum of getNumberOfAssemblyThreads() and omp_get_max_threads().

Definition at line 72 of file OgsAsmThreads.cpp.

73{
74#ifdef _OPENMP
75 int const num_omp_threads = omp_get_max_threads();
76#else
77 int const num_omp_threads = 1;
78#endif
79 return std::max(getNumberOfAssemblyThreads(), num_omp_threads);
80}

References getNumberOfAssemblyThreads().

Referenced by MaterialPropertyLib::Function::Function().

◆ getNumberOfThreadsFromEnv()

int BaseLib::getNumberOfThreadsFromEnv ( char const * env_var_name)

Reads the integer value from the given environment variable and returns it. Returns 1 if the variable is unset. Calls OGS_FATAL if the variable is set but empty, cannot be parsed as an integer, or its value is less than 1.

Definition at line 19 of file OgsAsmThreads.cpp.

20{
21 char const* const num_threads_env = std::getenv(env_var_name);
22
23 if (!num_threads_env)
24 {
25 return 1;
26 }
27
28 if (std::strlen(num_threads_env) == 0)
29 {
30 OGS_FATAL("The environment variable {} is set but empty.",
31 env_var_name);
32 }
33
34 std::string num_threads_str{num_threads_env};
35 BaseLib::trim(num_threads_str);
36
37 std::istringstream num_threads_iss{num_threads_str};
38 int num_threads = -1;
39
40 num_threads_iss >> num_threads;
41
42 if (!num_threads_iss)
43 {
44 OGS_FATAL("Error parsing {} (= \"{}\").", env_var_name,
45 num_threads_env);
46 }
47
48 if (!num_threads_iss.eof())
49 {
51 "Error parsing {} (= \"{}\"): not read entirely, the "
52 "remainder is \"{}\"",
53 env_var_name,
54 num_threads_env,
55 num_threads_iss.str().substr(num_threads_iss.tellg()));
56 }
57
58 if (num_threads < 1)
59 {
60 OGS_FATAL("You asked (via {}) to use {} < 1 thread.", env_var_name,
61 num_threads);
62 }
63
64 return num_threads;
65}
void trim(std::string &str, char ch)

References OGS_FATAL, and trim().

Referenced by getNumberOfAssemblyThreads(), and getNumberOfChemistryThreads().

◆ getOrError() [1/2]

template<typename Map, typename Key>
OGS_NO_DANGLING Map::mapped_type & BaseLib::getOrError ( Map & map,
Key const & key,
std::string const & error_message )

Returns the value of key from the given map if such an entry exists; otherwise an error_message is printed and the program is aborted. Cf. also the const overload below.

Definition at line 112 of file Algorithm.h.

114{
115 auto it = map.find(key);
116 if (it == map.end())
117 {
118 if constexpr (std::is_convertible<Key, std::string>::value)
119 {
120 OGS_FATAL("{:s} Key `{:s}' does not exist.", error_message, key);
121 }
122 else
123 {
124 OGS_FATAL("{:s} Key `{:s}' does not exist.", error_message,
125 std::to_string(key));
126 }
127 }
128
129 return it->second;
130}

References OGS_FATAL, and OGS_NO_DANGLING.

Referenced by MaterialPropertyLib::createCurve(), ProcessLib::HeatTransportBHE::BHE::createFlowAndTemperatureControl(), ProcessLib::createPerProcessData(), ProcessLib::HeatTransportBHE::BHE::createPowerWithCOPStruct(), MaterialPropertyLib::createSaturationWeightedThermalConductivity(), anonymous_namespace{SubmeshResiduumOutputConfig.cpp}::filterMeshesForResiduumOutput(), ProjectData::parseNonlinearSolvers(), and ProcessLib::parseTimeIntervalOrCurve().

◆ getOrError() [2/2]

template<typename Map, typename Key>
OGS_NO_DANGLING Map::mapped_type const & BaseLib::getOrError ( Map const & map,
Key const & key,
std::string const & error_message )

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 133 of file Algorithm.h.

135{
136 auto it = map.find(key);
137 if (it == map.end())
138 {
139 if constexpr (std::is_convertible<Key, std::string>::value)
140 {
141 OGS_FATAL("{:s} Key `{:s}' does not exist.", error_message, key);
142 }
143 else
144 {
145 OGS_FATAL("{:s} Key `{:s}' does not exist.", error_message,
146 std::to_string(key));
147 }
148 }
149
150 return it->second;
151}

References OGS_FATAL, and OGS_NO_DANGLING.

◆ getParenthesizedString()

std::tuple< std::string, std::string::size_type, std::string::size_type > BaseLib::getParenthesizedString ( std::string const & in,
char const open_char,
char const close_char,
std::string::size_type pos )

Returns the begin and end position of the string enclosed in open_char and close_char and the enclosed string itself. Search starts at position pos within the string str. Nested open_char and close_char are not handled correctly.

Definition at line 29 of file FileTools.cpp.

33{
34 auto const pos_curly_brace_open = in.find_first_of(open_char, pos);
35 if (pos_curly_brace_open == std::string::npos)
36 {
37 return std::make_tuple("", std::string::npos, std::string::npos);
38 }
39 auto const pos_curly_brace_close =
40 in.find_first_of(close_char, pos_curly_brace_open);
41 if (pos_curly_brace_close == std::string::npos)
42 {
43 return std::make_tuple("", std::string::npos, std::string::npos);
44 }
45 return std::make_tuple(
46 in.substr(pos_curly_brace_open + 1,
47 pos_curly_brace_close - (pos_curly_brace_open + 1)),
48 pos_curly_brace_open, pos_curly_brace_close);
49}

Referenced by constructFormattedFileName().

◆ getUniqueName()

std::string BaseLib::getUniqueName ( std::vector< std::string > const & existing_names,
std::string const & input_name )

Append '-' and a number such that the name is unique.

Definition at line 112 of file StringTools.cpp.

114{
115 std::string result_name = input_name;
116 std::size_t count = 1;
117 while (std::find(existing_names.cbegin(),
118 existing_names.cend(),
119 result_name) != existing_names.end())
120 {
121 count++;
122 result_name = input_name + "-" + std::to_string(count);
123 }
124 return result_name;
125}

Referenced by ParameterLib::getNamedOrCreateInlineParameter(), GeoLib::GEOObjects::isUniquePointVecName(), and MeshToolsLib::RasterDataToMesh::projectToMeshItems().

◆ hasFileExtension()

bool BaseLib::hasFileExtension ( std::string const & extension,
std::string const & filename )

Compares filename's extension with query extension. The comparison is case insensitive.

Definition at line 187 of file FileTools.cpp.

188{
189 return boost::iequals(extension, getFileExtension(filename));
190}
std::string getFileExtension(const std::string &path)

References getFileExtension().

Referenced by main(), and anonymous_namespace{readMeshFromFile.cpp}::readMeshFromFileSerial().

◆ initOGSLogger()

void BaseLib::initOGSLogger ( std::string const & log_level)

Definition at line 104 of file Logging.cpp.

105{
106 if (!console)
107 {
108#if defined(_WIN32) && defined(OGS_BUILD_WHEEL)
109 // Custom sink re-resolving stdout per write; see Fd1StdoutSink above.
110 // No colour on Windows console as a consequence.
111#if defined(USE_PETSC) || defined(_OPENMP)
112 console = std::make_shared<spdlog::logger>(
113 "ogs", std::make_shared<Fd1StdoutSink<std::mutex>>());
114#else
115 console = std::make_shared<spdlog::logger>(
116 "ogs",
117 std::make_shared<Fd1StdoutSink<spdlog::details::null_mutex>>());
118#endif
119 spdlog::register_logger(console);
120#else
121#if defined(USE_PETSC) || defined(_OPENMP)
122 // Thread-safe sink is required when OGS logs concurrently, e.g. from
123 // OpenMP assembly threads. Otherwise the non-thread-safe sink races and
124 // may corrupt output (e.g. console output interleaved into other
125 // files).
126 console = spdlog::stdout_color_mt("ogs");
127#else
128 console = spdlog::stdout_color_st("ogs");
129#endif
130#endif // defined(_WIN32) && defined(OGS_BUILD_WHEEL)
131 // Default pattern and error handler both for MPI and non-MPI builds.
132 spdlog::set_pattern("%^%l:%$ %v");
133 spdlog::set_error_handler(error_handler);
134
135#ifdef USE_PETSC
136 int mpi_init;
137 MPI_Initialized(&mpi_init);
138 if (mpi_init == 1)
139 {
140 MPI_Comm_rank(BaseLib::MPI::OGS_COMM_WORLD, &mpi_rank);
141 spdlog::set_pattern(fmt::format("[{}] %^%l:%$ %v", mpi_rank));
142 spdlog::set_error_handler(mpi_error_handler);
143 }
144#endif // USE_PETSC
145 }
147}
MPI_Comm OGS_COMM_WORLD
Definition MPI.cpp:9
void setConsoleLogLevel(std::string const &level_string)
Definition Logging.cpp:87
std::shared_ptr< spdlog::logger > console
Definition Logging.cpp:85

References console, BaseLib::MPI::OGS_COMM_WORLD, and setConsoleLogLevel().

Referenced by OGSSimulation::OGSSimulation(), main(), main(), PYBIND11_MODULE(), PYBIND11_MODULE(), and PYBIND11_MODULE().

◆ insertIfKeyUniqueElseError()

template<typename Map, typename Key, typename Value>
void BaseLib::insertIfKeyUniqueElseError ( Map & map,
Key const & key,
Value && value,
std::string const & error_message )

Inserts the given key with the given value into the map if an entry with the given key does not yet exist; otherwise an error_message is printed and the program is aborted.

Definition at line 98 of file Algorithm.h.

100{
101 auto const inserted = map.emplace(key, std::forward<Value>(value));
102 if (!inserted.second)
103 { // insertion failed, i.e., key already exists
104 OGS_FATAL("{} Key `{}' already exists.", error_message, key);
105 }
106}

References OGS_FATAL.

Referenced by ProcessLib::SecondaryVariableCollection::addNameMapping(), ProjectData::parseCurves(), ProjectData::parseLinearSolvers(), ProjectData::parseNonlinearSolvers(), GeoLib::IO::BoostXmlGmlInterface::readPoints(), GeoLib::IO::BoostXmlGmlInterface::readPolylines(), and GeoLib::IO::BoostXmlGmlInterface::readSurfaces().

◆ int2date()

std::string BaseLib::int2date ( int date)

Converts an integer to a string date "dd.mm.yyyy" Note: (Almost) no checks are performed if the int makes sense as a date.

Definition at line 31 of file DateTools.cpp.

32{
33 if (date > 10000000 && date < 22000000)
34 {
35 auto y = static_cast<int>(std::floor(date / 10000.0));
36 auto m = static_cast<int>(std::floor((date - (y * 10000)) / 100.0));
37 int d = date - (y * 10000) - (m * 100);
38 std::stringstream ss;
39 if (d < 10)
40 {
41 ss << "0";
42 }
43 ss << d << ".";
44 if (m < 10)
45 {
46 ss << "0";
47 }
48 ss << m << "." << y;
49 return ss.str();
50 }
51 return "";
52}

Referenced by DiagramList::readList().

◆ IsFileExisting()

bool BaseLib::IsFileExisting ( const std::string & strFilename)

◆ joinPaths()

◆ makeConfigTree()

ConfigTree BaseLib::makeConfigTree ( std::string const & filepath,
bool const be_ruthless,
std::string const & toplevel_tag,
std::stringstream & prj_stream )

Create a ConfigTree from an XML file.

Parameters
filepathsee ConfigTreeTopLevel::ConfigTreeTopLevel()
be_ruthlesssee ConfigTreeTopLevel::ConfigTreeTopLevel()
toplevel_tagname of the outermost tag in the XML file. The returned ConfigTree is rooted one level below that tag.
prj_streamcontent of the (pre-processed) prj file.

The parameter toplevel_tag is provided for compatibility with our existing configuration files whose toplevel tags are written in camel case, which conflicts with the naming rules of ConfigTree. Via that parameter the naming rules do not apply to the toplevel tag.

Unfortunately the XML parser shipped with boost::property_tree does not fully support the XML standard. Additionally there might be encoding issues. From their docs:

Please note that RapidXML does not understand the encoding specification. If you pass it a > character buffer, it assumes the data is already correctly encoded; if you pass it a filename, > it will read the file using the character conversion of the locale you give it (or the global > locale if you give it none). This means that, in order to parse a UTF-8-encoded XML file into > a wptree, you have to supply an alternate locale, either directly or by replacing the global one.

See also
http://www.boost.org/doc/libs/1_60_0/doc/html/property_tree/parsers.html

Definition at line 17 of file ConfigTreeUtil.cpp.

20{
22
23 // note: Trimming whitespace and ignoring comments is crucial in order
24 // for our configuration tree implementation to work!
25 try
26 {
27 read_xml(prj_stream, ptree,
28 boost::property_tree::xml_parser::no_comments |
29 boost::property_tree::xml_parser::trim_whitespace);
30 }
31 catch (boost::property_tree::xml_parser_error const& e)
32 {
33 OGS_FATAL("Error while parsing XML file `{:s}' at line {:d}: {:s}.",
34 e.filename(), e.line(), e.message());
35 }
36
37 DBUG("Project configuration from file '{:s}' read.", filepath);
38
39 if (auto opt_child = ptree.get_child_optional(toplevel_tag))
40 {
41 auto const callback =
43
44 return ConfigTree(std::move(*opt_child), filepath, callback, callback);
45 }
46 OGS_FATAL("Tag <{:s}> has not been found in file `{:s}'.", toplevel_tag,
47 filepath);
48}
void DBUG(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:22
static void onerror(std::string const &filename, std::string const &path, std::string const &message)
boost::property_tree::ptree PTree
The tree being wrapped by this class.
Definition ConfigTree.h:249
static void onwarning(std::string const &filename, std::string const &path, std::string const &message)

References DBUG(), OGS_FATAL, BaseLib::ConfigTree::onerror(), and BaseLib::ConfigTree::onwarning().

Referenced by Simulation::initializeDataStructures(), and makeConfigTreeFromFile().

◆ makeConfigTreeFromFile()

ConfigTree BaseLib::makeConfigTreeFromFile ( const std::string & filepath,
const bool be_ruthless,
const std::string & toplevel_tag )

Definition at line 50 of file ConfigTreeUtil.cpp.

53{
54 std::ifstream file(filepath);
55 if (file)
56 {
57 std::stringstream buffer;
58 buffer << file.rdbuf();
59
60 return makeConfigTree(filepath, be_ruthless, toplevel_tag, buffer);
61 }
62
63 OGS_FATAL("Could not read from file {:s}!", filepath);
64}
ConfigTree makeConfigTree(const std::string &filepath, const bool be_ruthless, const std::string &toplevel_tag, std::stringstream &prj_stream)

References makeConfigTree(), and OGS_FATAL.

Referenced by GeoLib::IO::BoostXmlGmlInterface::readFile().

◆ makeLogLevelArg()

TCLAP::ValueArg< std::string > BaseLib::makeLogLevelArg ( )

Definition at line 19 of file TCLAPArguments.cpp.

20{
21 static std::vector<std::string> allowed_log_levels{"none", "error", "warn",
22 "info", "debug", "all"};
23 static auto* allowed_log_levels_vals =
24 new TCLAP::ValuesConstraint<std::string>(allowed_log_levels);
25
26 return TCLAP::ValueArg<std::string>(
27 "l", "log-level", "the verbosity of logging messages", false,
28 defaultLogLevel(), allowed_log_levels_vals);
29}
std::string defaultLogLevel()

References defaultLogLevel().

Referenced by main(), main(), and parseCommandLineArguments().

◆ makeVectorUnique() [1/2]

◆ makeVectorUnique() [2/2]

template<typename T, class Compare>
void BaseLib::makeVectorUnique ( std::vector< T > & v,
Compare comp )

Make the entries of the std::vector v unique using the given binary function. The remaining entries will be sorted.

Definition at line 208 of file Algorithm.h.

209{
210 std::sort(v.begin(), v.end(), comp);
211 auto it = std::unique(v.begin(), v.end());
212 v.erase(it, v.end());
213}

◆ none_of()

template<typename List>
bool BaseLib::none_of ( List const & values)
constexpr

Checks if none of the elements in the given list are true.

Definition at line 343 of file Algorithm.h.

344{
345 return !any_of(values);
346}
constexpr bool any_of(List const &values)
Checks if any of the elements in the given list is true.
Definition Algorithm.h:311

References any_of().

◆ operator<<() [1/2]

template std::ostream & BaseLib::operator<< ( std::ostream & os,
const Histogram< double > & h )

◆ operator<<() [2/2]

template<typename T>
std::ostream & BaseLib::operator<< ( std::ostream & os,
const Histogram< T > & h )

Writes histogram to output stream.

Writes histogram properties in this order: number of bins, minimum, maximum, bin0 count, ..., binN-1 count.

Definition at line 70 of file Histogram.cpp.

71{
72 os << h.getNumberOfBins() << " " << h.getMinimum() << " " << h.getMaximum()
73 << " ";
74 std::copy(h.getBinCounts().begin(), h.getBinCounts().end(),
75 std::ostream_iterator<std::size_t>(os, " "));
76 return os << std::endl;
77}
const T & getMinimum() const
Definition Histogram.h:103
const unsigned int & getNumberOfBins() const
Definition Histogram.h:102
const std::vector< std::size_t > & getBinCounts() const
Definition Histogram.h:101
const T & getMaximum() const
Definition Histogram.h:104

References BaseLib::Histogram< T >::getBinCounts(), BaseLib::Histogram< T >::getMaximum(), BaseLib::Histogram< T >::getMinimum(), and BaseLib::Histogram< T >::getNumberOfBins().

◆ parseInteger()

std::expected< int, std::string > BaseLib::parseInteger ( std::string_view str)

Parses a trimmed string as an integer. Returns the value, or an error message string on invalid input.

Definition at line 126 of file StringTools.cpp.

127{
128 int result = 0;
129 auto const [ptr, ec] =
130 std::from_chars(str.data(), str.data() + str.size(), result);
131
132 if (ec == std::errc::invalid_argument)
133 {
134 return std::unexpected(
135 fmt::format("Could not parse '{}' to a valid integer.", str));
136 }
137 if (ec == std::errc::result_out_of_range)
138 {
139 return std::unexpected(fmt::format(
140 "Could not parse '{}'. The integer value exceeds the permitted "
141 "range.",
142 str));
143 }
144
145 std::size_t const chars_consumed = std::distance(str.data(), ptr);
146 if (chars_consumed != str.size())
147 {
148 auto const non_ws_it = std::find_if_not(
149 str.begin() + chars_consumed, str.end(),
150 [](unsigned char const c) { return std::isspace(c); });
151 if (non_ws_it != str.end())
152 {
153 return std::unexpected(fmt::format(
154 "Could not parse '{}'. Invalid character: '{}' at position {}.",
155 str, *non_ws_it, std::distance(str.begin(), non_ws_it)));
156 }
157 }
158
159 return result;
160}

Referenced by MaterialLib::splitMaterialIdString().

◆ patchStream()

void BaseLib::patchStream ( std::string const & patch_file,
std::stringstream & prj_stream,
bool after_includes = false )

Definition at line 171 of file PrjProcessing.cpp.

173{
174 // xmlReadFile(patch_file.c_str(), nullptr, 0); leads to malloc errors in
175 // xmlFreeDoc(doc) below
176 auto patch = xmlParseFile(patch_file.c_str());
177 if (patch == nullptr)
178 {
179 OGS_FATAL("Error reading XML diff file {:s}.", patch_file);
180 }
181
182 auto doc = xmlReadMemory(prj_stream.str().c_str(), prj_stream.str().size(),
183 nullptr, nullptr, 0);
184 if (doc == nullptr)
185 {
186 OGS_FATAL("Error reading project file from memory.");
187 }
188
189 auto node = xmlDocGetRootElement(patch);
190 int rc = 0;
191 for (node = node ? node->children : nullptr; node; node = node->next)
192 {
193 if (node->type != XML_ELEMENT_NODE)
194 {
195 continue;
196 }
197 bool node_after_includes = false;
198 xmlAttr* attribute = node->properties;
199 while (attribute)
200 {
201 // Check for after_includes-attribute
202 xmlChar* value =
203 xmlNodeListGetString(node->doc, attribute->children, 1);
204 if (xmlStrEqual(attribute->name, xmlCharStrdup("after_includes")) &&
205 xmlStrEqual(value, xmlCharStrdup("true")))
206 {
207 node_after_includes = true;
208 }
209
210 xmlFree(value);
211 attribute = attribute->next;
212 }
213
214 if (after_includes != node_after_includes)
215 {
216 continue;
217 }
218
219 if (xmlStrEqual(node->name, xmlCharStrdup("add")))
220 {
221 rc = xml_patch_add(doc, node);
222 }
223 else if (xmlStrEqual(node->name, xmlCharStrdup("replace")))
224 {
225 rc = xml_patch_replace(doc, node);
226 }
227 else if (xmlStrEqual(node->name, xmlCharStrdup("remove")))
228 {
229 rc = xml_patch_remove(doc, node);
230 }
231 else
232 {
233 OGS_FATAL(
234 "Error while patching prj file with patch file {:}. Only "
235 "'add', 'replace' and 'remove' elements are allowed! Got an "
236 "element '{:s}' on line {:d}.",
237 patch_file, reinterpret_cast<const char*>(node->name),
238 node->line);
239 }
240
241 if (rc)
242 {
243 OGS_FATAL(
244 "Error while patching prj file with patch file {:}. Error in "
245 "element '{:s}' on line {:d}.",
246 patch_file, reinterpret_cast<const char*>(node->name),
247 node->line);
248 }
249 }
250
251 xmlChar* xmlbuff;
252 int buffersize;
253 xmlDocDumpMemory(doc, &xmlbuff, &buffersize);
254 prj_stream.str(""); // Empty stream
255 prj_stream << xmlbuff;
256
257 xmlFree(xmlbuff);
258 xmlFreeDoc(doc);
259 xmlFreeDoc(patch);
260}

References OGS_FATAL.

Referenced by prepareProjectFile(), and readAndPatchPrj().

◆ prepareProjectFile()

void BaseLib::prepareProjectFile ( std::stringstream & prj_stream,
const std::string & filepath,
const std::vector< std::string > & patch_files,
bool write_prj,
const std::string & out_directory )

Applies includes and patch files to project file.

Parameters
prj_streamThe processed prj as a stringstream.
filepathThe prj file.
patch_filesOptional patch files.
write_prjWrite the processed project file to disk?
out_directoryThe directory to write the processed file to.

Definition at line 317 of file PrjProcessing.cpp.

321{
322 std::string prj_file = filepath;
323
324 std::vector<std::string> patch_files_copy = patch_files;
325 readAndPatchPrj(prj_stream, prj_file, patch_files_copy);
326 replaceIncludes(prj_stream,
327 std::filesystem::absolute(std::filesystem::path(prj_file))
328 .parent_path());
329 // re-apply xml patches to stream
330 for (const auto& patch_file : patch_files_copy)
331 {
332 patchStream(patch_file, prj_stream, true);
333 }
334
335 if (write_prj)
336 {
337 // The following two lines should set indenting to 4 spaces but it does
338 // not work. 2 spaces are default.
339 //
340 // xmlThrDefIndentTreeOutput(1);
341 // xmlThrDefTreeIndentString(" "); // 4 spaces indent
342 // XML_PARSE_NOBLANKS -> pretty-print
343 auto doc =
344 xmlReadMemory(prj_stream.str().c_str(), prj_stream.str().size(),
345 nullptr, nullptr, XML_PARSE_NOBLANKS);
346 auto prj_out = (std::filesystem::path(out_directory) /
347 std::filesystem::path(filepath).stem())
348 .string() +
349 "_processed.prj";
350 xmlSaveFormatFileEnc(prj_out.c_str(), doc, "utf-8", 1);
351 INFO("Processed project file written to {:s}.", prj_out);
352 xmlFreeDoc(doc);
353 }
354 xmlCleanupParser();
355}
void readAndPatchPrj(std::stringstream &prj_stream, std::string &prj_file, std::vector< std::string > &patch_files)
void patchStream(std::string const &patch_file, std::stringstream &prj_stream, bool after_includes=false)
void replaceIncludes(std::stringstream &prj_stream, std::filesystem::path const &prj_dir)

References INFO(), patchStream(), readAndPatchPrj(), and replaceIncludes().

Referenced by Simulation::initializeDataStructures().

◆ quicksort() [1/5]

template<typename It1, typename It2>
void BaseLib::quicksort ( It1 first1,
It1 last1,
It2 first2 )
Precondition
{first1 <= last1 and the second iterator can be incremented distance(first1, last1) times}

Definition at line 43 of file quicksort.h.

44{
45 using T1 = typename std::iterator_traits<It1>::value_type;
46 using T2 = typename std::iterator_traits<It2>::value_type;
47
48 quicksort(first1, last1, first2,
49 [](std::pair<T1, T2> const& a, std::pair<T1, T2> const& b)
50 { return a.first < b.first; });
51}
void quicksort(It1 first1, It1 last1, It2 first2, Comparator compare)
Definition quicksort.h:17

References quicksort().

◆ quicksort() [2/5]

template<typename It1, typename It2, typename Comparator>
void BaseLib::quicksort ( It1 first1,
It1 last1,
It2 first2,
Comparator compare )
Precondition
{first1 <= last1 and the second iterator can be incremented distance(first1, last1) times}

Definition at line 17 of file quicksort.h.

18{
19 using T1 = typename std::iterator_traits<It1>::value_type;
20 using T2 = typename std::iterator_traits<It2>::value_type;
21
22 std::vector<std::pair<T1, T2>> data;
23 data.reserve(std::distance(first1, last1));
24 std::transform(first1, last1, first2, std::back_inserter(data),
25 [](T1 const& t1, T2 const& t2)
26 { return std::make_pair(t1, t2); });
27
28 // Sort data using first element of the pair.
29 std::sort(begin(data), end(data), compare);
30
31 // Unzip sorted data.
32 for (auto const& pair : data)
33 {
34 *first1 = pair.first;
35 *first2 = pair.second;
36 ++first1;
37 ++first2;
38 }
39}

Referenced by MeshGeoToolsLib::MeshNodesAlongPolyline::MeshNodesAlongPolyline(), MathLib::PiecewiseLinearInterpolation::PiecewiseLinearInterpolation(), MathLib::PiecewiseLinearInterpolation::PiecewiseLinearInterpolation(), quicksort(), quicksort(), quicksort(), and GeoLib::Polygon::splitPolygonAtPoint().

◆ quicksort() [3/5]

template<typename T1, typename T2 = std::size_t>
void BaseLib::quicksort ( std::vector< T1 * > & array,
std::size_t beg,
std::size_t end,
std::vector< T2 > & perm )

Definition at line 74 of file quicksort.h.

76{
77 assert(beg <= end);
78 assert(end <= array.size());
79 assert(perm.size() == array.size());
80
81 // Zip input arrays.
82 std::vector<std::pair<T1*, T2>> data;
83 data.reserve(end - beg);
84 std::transform(array.begin() + beg, array.begin() + end, perm.begin() + beg,
85 std::back_inserter(data),
86 [](T1* const& t1, T2 const& t2)
87 { return std::make_pair(t1, t2); });
88
89 // Sort data using first element of the pair.
90 std::sort(data.begin(), data.end(),
91 [](std::pair<T1*, T2> const& a, std::pair<T1*, T2> const& b)
92 { return (*a.first < *b.first); });
93
94 // Unzip sorted data.
95 for (std::size_t i = 0; i < data.size(); i++)
96 {
97 array[beg + i] = data[i].first;
98 perm[beg + i] = data[i].second;
99 }
100}

◆ quicksort() [4/5]

template<typename T1, typename T2 = std::size_t>
void BaseLib::quicksort ( std::vector< T1 > & array,
std::size_t beg,
std::size_t end,
std::vector< T2 > & perm )

Definition at line 63 of file quicksort.h.

65{
66 assert(beg <= end);
67 assert(end <= array.size());
68 assert(perm.size() == array.size());
69
70 quicksort(array.data(), beg, end, perm.data());
71}

References quicksort().

◆ quicksort() [5/5]

template<typename T1, typename T2 = std::size_t>
void BaseLib::quicksort ( T1 * array,
std::size_t beg,
std::size_t end,
T2 * perm )
Precondition
{end<=array.size() and perm.size()==array.size()}

Definition at line 55 of file quicksort.h.

56{
57 assert(beg <= end);
58
59 quicksort(array + beg, array + end, perm + beg);
60}

References quicksort().

◆ randomString()

std::string BaseLib::randomString ( std::size_t const length)

Returns a random string of the given length containing just a-z,A-Z,0-9.

Definition at line 94 of file StringTools.cpp.

95{
96 static constexpr char charset[] =
97 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
98
99 static const auto seed = static_cast<std::mt19937::result_type>(
100 std::chrono::system_clock::now().time_since_epoch().count());
101 static std::mt19937 generator{seed};
102 static std::uniform_int_distribution<unsigned short> distribution(
103 0, sizeof(charset) - 2);
104
105 std::string s(length, 0);
106 std::generate_n(begin(s), length,
107 [&]() { return charset[distribution(generator)]; });
108
109 return s;
110}

Referenced by FileIO::createSurface().

◆ readAndPatchPrj()

void BaseLib::readAndPatchPrj ( std::stringstream & prj_stream,
std::string & prj_file,
std::vector< std::string > & patch_files )

Definition at line 264 of file PrjProcessing.cpp.

266{
267 // Extract base project file path if an xml (patch) file is given as prj
268 // file and it contains the base_file attribute.
269 if (BaseLib::getFileExtension(prj_file) == ".xml")
270 {
271 if (!patch_files.empty())
272 {
273 OGS_FATAL(
274 "It is not allowed to specify additional patch files "
275 "if a patch file was already specified as the "
276 "prj-file.");
277 }
278 auto patch = xmlReadFile(prj_file.c_str(), nullptr, 0);
279 auto node = xmlDocGetRootElement(patch);
280 xmlChar const base_file_string[] = "base_file";
281 auto base_file = xmlGetProp(node, base_file_string);
282 if (base_file == nullptr)
283 {
284 OGS_FATAL(
285 "Error reading base prj file (base_file attribute) in given "
286 "patch file {:s}.",
287 prj_file);
288 }
289 patch_files = {prj_file};
290 std::stringstream ss;
291 ss << base_file;
292 prj_file = BaseLib::joinPaths(BaseLib::extractPath(prj_file), ss.str());
293 }
294
295 // read base prj file into stream
296 if (std::ifstream file(prj_file); file)
297 {
298 prj_stream << file.rdbuf();
299 }
300 else
301 {
302 if (!BaseLib::IsFileExisting(prj_file))
303 {
304 ERR("File {:s} does not exist.", prj_file);
305 }
306 DBUG("Stream state flags: {:s}.", iostateToString(file.rdstate()));
307 OGS_FATAL("Could not open project file '{:s}' for reading.", prj_file);
308 }
309
310 // apply xml patches to stream
311 for (const auto& patch_file : patch_files)
312 {
313 patchStream(patch_file, prj_stream);
314 }
315}
void ERR(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:40
std::string extractPath(std::string const &pathname)
bool IsFileExisting(const std::string &strFilename)
Returns true if given file exists.
Definition FileTools.cpp:23
std::string joinPaths(std::string const &pathA, std::string const &pathB)
std::string iostateToString(std::ios_base::iostate const state)

References DBUG(), ERR(), extractPath(), getFileExtension(), IsFileExisting(), joinPaths(), OGS_FATAL, and patchStream().

Referenced by prepareProjectFile().

◆ readBinaryValue()

template<typename T>
T BaseLib::readBinaryValue ( std::istream & in)

Definition at line 258 of file FileTools.cpp.

259{
260 T v;
261 in.read(reinterpret_cast<char*>(&v), sizeof(T));
262 return v;
263}

Referenced by FileIO::Gocad::GocadSGridReader::readNodesBinary().

◆ readBinaryValue< double >()

template double BaseLib::readBinaryValue< double > ( std::istream & )

◆ readBinaryValue< float >()

template float BaseLib::readBinaryValue< float > ( std::istream & )

◆ readBinaryVector()

template<typename T>
std::vector< T > BaseLib::readBinaryVector ( std::string const & filename,
std::size_t const start_element,
std::size_t const num_elements )

Definition at line 270 of file FileTools.cpp.

273{
274 if (!IsFileExisting(filename))
275 {
276 OGS_FATAL("File {:s} not found", filename);
277 }
278
279 // Determine file size
280 std::uintmax_t file_size = std::filesystem::file_size(filename);
281 std::size_t total_elements = file_size / sizeof(T);
282
283 if (start_element >= total_elements)
284 {
285 OGS_FATAL("Start element is beyond file size");
286 }
287
288 // Calculate the number of elements to read
289 std::size_t const elements_to_read =
290 std::min(num_elements, total_elements - start_element);
291
292 // Calculate offset and size to map
293 std::size_t const offset = start_element * sizeof(T);
294 std::size_t const size_to_map = elements_to_read * sizeof(T);
295
296 // Create a file mapping
297 boost::interprocess::file_mapping file(filename.c_str(),
298 boost::interprocess::read_only);
299
300 // Map the specified region
301 boost::interprocess::mapped_region region(
302 file, boost::interprocess::read_only, offset, size_to_map);
303
304 // Get the address of the mapped region
305 auto* addr = region.get_address();
306
307 // Create vector and copy data
308 std::vector<T> result(elements_to_read);
309 std::memcpy(result.data(), addr, size_to_map);
310
311 if constexpr (std::endian::native != std::endian::little)
312 {
313 boost::endian::endian_reverse_inplace(result);
314 }
315
316 return result;
317}

References IsFileExisting(), and OGS_FATAL.

◆ readBinaryVector< double >()

template std::vector< double > BaseLib::readBinaryVector< double > ( std::string const & ,
std::size_t const ,
std::size_t const  )

◆ readBinaryVector< float >()

template std::vector< float > BaseLib::readBinaryVector< float > ( std::string const & ,
std::size_t const ,
std::size_t const  )

◆ readDoublesFromBinaryFile()

std::vector< double > BaseLib::readDoublesFromBinaryFile ( const std::string & filename,
const std::string & project_directory )

Definition at line 242 of file FileTools.cpp.

244{
245 std::string path_to_file = BaseLib::joinPaths(project_directory, filename);
246 std::string file_extension = BaseLib::getFileExtension(filename);
247 if (file_extension != ".bin")
248 {
249 OGS_FATAL(
250 "Currently only binary files with extension '.bin' supported. The "
251 "specified file has extension {:s}.",
252 file_extension)
253 }
254 return BaseLib::readBinaryVector<double>(path_to_file);
255}
template std::vector< double > readBinaryVector< double >(std::string const &, std::size_t const, std::size_t const)

References getFileExtension(), joinPaths(), OGS_FATAL, and readBinaryVector< double >().

Referenced by ProcessLib::createOutputConfig(), and MathLib::parsePiecewiseLinearCurveConfig().

◆ removeFile()

void BaseLib::removeFile ( std::string const & filename)

Removes a file. If a file does not exist nothing will happen, other errors lead to OGS_FATAL call.

Definition at line 203 of file FileTools.cpp.

204{
205 bool const success =
206 std::filesystem::remove(std::filesystem::path(filename));
207 if (success)
208 {
209 DBUG("Removed '{:s}'", filename);
210 }
211}

References DBUG().

Referenced by MainWindow::callGMSH(), consolidateGeometry(), main(), and removeFiles().

◆ removeFiles()

void BaseLib::removeFiles ( std::vector< std::string > const & files)

Remove files. If a file does not exist nothing will happen, other errors lead to OGS_FATAL call.

Definition at line 213 of file FileTools.cpp.

214{
215 for (auto const& file : files)
216 {
217 removeFile(file);
218 }
219}
void removeFile(std::string const &filename)

References removeFile().

Referenced by Simulation::initializeDataStructures().

◆ reorderVector()

template<typename ValueType, typename IndexType>
void BaseLib::reorderVector ( std::vector< ValueType > & v,
std::vector< IndexType > const & order )

Reorder a vector by a given index vector.

Note: It is good enough in performance for medium size vectors.

Definition at line 221 of file Algorithm.h.

223{
224 std::vector<ValueType> temp_v(v.size());
225 temp_v.swap(v);
226
227 for (std::size_t i = 0; i < order.size(); i++)
228 {
229 std::swap(v[i], temp_v[order[i]]);
230 }
231}

◆ replaceIncludes()

void BaseLib::replaceIncludes ( std::stringstream & prj_stream,
std::filesystem::path const & prj_dir )

Definition at line 141 of file PrjProcessing.cpp.

143{
144 // Parsing the XML triggers floating point exceptions. Because we are not
145 // debugging libxml2 (or other libraries) at this point, the floating point
146 // exceptions are temporarily disabled and are restored at the end of the
147 // function.
148 [[maybe_unused]] DisableFPE disable_fpe;
149
150 auto doc = xmlReadMemory(prj_stream.str().c_str(), prj_stream.str().size(),
151 nullptr, nullptr, 0);
152 if (doc == nullptr)
153 {
154 OGS_FATAL("Error reading project file from memory.");
155 }
156
157 auto root_node = xmlDocGetRootElement(doc);
158 traverseIncludes(doc, root_node, prj_dir);
159
160 xmlChar* xmlbuff;
161 int buffersize;
162 xmlDocDumpMemory(doc, &xmlbuff, &buffersize);
163 prj_stream.str(""); // Empty stream
164 prj_stream << xmlbuff;
165
166 xmlFree(xmlbuff);
167 xmlFreeDoc(doc);
168}
void traverseIncludes(xmlDoc *doc, xmlNode *node, std::filesystem::path const &prj_dir)

References OGS_FATAL, and traverseIncludes().

Referenced by prepareProjectFile().

◆ replaceString()

std::string BaseLib::replaceString ( const std::string & searchString,
const std::string & replaceString,
std::string stringToReplace )

Replaces a substring with another in a string

Parameters
searchStringSearch for this string
replaceStringReplace with this string
stringToReplaceSearch and replace in this string
Returns
The modified string

Definition at line 42 of file StringTools.cpp.

45{
46 boost::replace_all(stringToReplace, searchString, replaceString);
47 return stringToReplace;
48}
std::string replaceString(const std::string &searchString, const std::string &replaceString, std::string stringToReplace)

References replaceString().

Referenced by GeoLib::Station::createStation(), FileIO::FEFLOWMeshInterface::getIndexList(), FileIO::readDoubleFromStream(), DiagramList::readList(), and replaceString().

◆ setConsoleLogLevel()

void BaseLib::setConsoleLogLevel ( std::string const & level_string)

Definition at line 87 of file Logging.cpp.

88{
89 using namespace spdlog::level;
90 std::map<std::string, level_enum> string_to_log_level = {
91 {"none", off}, {"critical", critical}, {"error", err}, {"warn", warn},
92 {"info", info}, {"debug", debug}, {"all", trace}};
93
94 auto const level = string_to_log_level.find(level_string);
95 if (level == string_to_log_level.end())
96 {
97 ERR("'{:s}' is not a valid log level!", level_string);
98 OGS_FATAL("Wrong log level string.");
99 }
100 console->set_level(level->second);
101 spdlog::set_default_logger(console);
102}

References console, ERR(), and OGS_FATAL.

Referenced by initOGSLogger().

◆ simplify()

void BaseLib::simplify ( std::string & str)

Removes multiple whitespaces (or other characters) from within a string. Equivalent functionality to Qt::QString::simplify().

Definition at line 68 of file StringTools.cpp.

69{
70 trim(str);
71 str.erase(std::unique(str.begin(),
72 str.end(),
73 [](char a, char b) { return a == ' ' && b == ' '; }),
74 str.end());
75}

References trim().

Referenced by FileIO::TetGenInterface::getNFacets(), FileIO::TetGenInterface::parseSmeshFacets(), FileIO::TetGenInterface::readElementsFromStream(), and FileIO::TetGenInterface::readNodesFromStream().

◆ sizesToOffsets()

template<ranges::range R>
requires std::is_integral_v<ranges::range_value_t<R>>
std::vector< ranges::range_value_t< R > > BaseLib::sizesToOffsets ( R const & sizes)

Converts range of sizes to a vector of offsets. First offset is 0 and the resulting vector size is the size of the input range plus one.

Definition at line 301 of file Algorithm.h.

302{
303 return ranges::views::concat(
304 ranges::views::single(ranges::range_value_t<R>{0}),
305 ranges::views::partial_sum(sizes)) |
306 ranges::to<std::vector<ranges::range_value_t<R>>>();
307}

Referenced by BaseLib::MPI::allgatherv(), MeshLib::computeNumberOfRegularBaseNodesAtRank(), MeshLib::computeNumberOfRegularHigherOrderNodesAtRank(), MeshLib::computeRegularBaseNodeGlobalNodeIDsOfSubDomainPartition(), getMergedNodesVector(), MeshLib::IO::getPartitionInfo(), and MeshLib::IO::NodePartitionedMeshReader::newMesh().

◆ splitString() [1/2]

std::list< std::string > BaseLib::splitString ( const std::string & str,
char delim )

Splits a string into a list of strings.

Parameters
strString to be split
delimCharacter indicating that the string should be split
Returns
List of strings

Definition at line 30 of file StringTools.cpp.

31{
32 std::list<std::string> strList;
33 std::stringstream ss(str);
34 std::string item;
35 while (std::getline(ss, item, delim))
36 {
37 strList.push_back(item);
38 }
39 return strList;
40}

◆ splitString() [2/2]

std::vector< std::string > BaseLib::splitString ( std::string const & str)

Splits a string into a vector of strings. This method only works for string separation recognised by the std::stringstream iterator such as ' ' or '\t'.

Parameters
strString to be split
Returns
Vector of strings

Definition at line 20 of file StringTools.cpp.

21{
22 std::istringstream str_stream(str);
23 std::vector<std::string> items;
24 std::copy(std::istream_iterator<std::string>(str_stream),
25 std::istream_iterator<std::string>(),
26 std::back_inserter(items));
27 return items;
28}

Referenced by FileIO::SwmmInterface::addPointElevation(), FileIO::SwmmInterface::addRainGaugeTimeSeriesLocations(), GeoLib::Station::createStation(), FileIO::CsvInterface::findColumn(), FileIO::CsvInterface::getColumnNames(), FileIO::FEFLOWMeshInterface::getIndexList(), FileIO::TetGenInterface::getNFacets(), FileIO::Gocad::GocadAsciiReader::parseLine(), FileIO::Gocad::GocadAsciiReader::parseNodes(), FileIO::TetGenInterface::parseNodesFileHeader(), FileIO::Gocad::GocadAsciiReader::parseProperties(), FileIO::TetGenInterface::parseSmeshFacets(), FileIO::Gocad::GocadAsciiReader::parseSurface(), FileIO::Gocad::GocadAsciiReader::propertyCheck(), FileIO::GMSInterface::readBoreholesFromGMS(), FileIO::CsvInterface::readColumn(), FileIO::SwmmInterface::readCoordinates(), FileIO::Gocad::GocadAsciiReader::readData(), SensorData::readDataFromFile(), FileIO::FEFLOWMeshInterface::readElevation(), anonymous_namespace{NetCDFRasterReader.cpp}::readHeaderFromNetCDF(), FileIO::SwmmInterface::readLineElements(), FileIO::SwmmInterface::readLinksAsPolylines(), FileIO::SwmmInterface::readNodeData(), FileIO::CsvInterface::readPoints(), FileIO::CsvInterface::readPoints(), FileIO::SwmmInterface::readPollutants(), FileIO::SwmmInterface::readPolygons(), FileIO::SwmmInterface::readSubcatchments(), FileIO::split(), and MaterialLib::splitMaterialIdString().

◆ str2number()

◆ strDate2int()

int BaseLib::strDate2int ( const std::string & s)

Converts a string containing a date into a double. Note: It is not really checked if the date actually makes sense.

Parameters
sString containing the date, the expected format is "dd.mm.yyyy".
Returns
A number representing the date as dd.mm.yyyy.

Definition at line 91 of file DateTools.cpp.

92{
93 std::string str(s);
94 if (s.length() > 10)
95 {
96 str = s.substr(0, 10);
97 }
98 std::size_t sep(str.find('.', 0));
99 int d(atoi(str.substr(0, sep).c_str()));
100 std::size_t sep2(str.find('.', sep + 1));
101 int m(atoi(str.substr(sep + 1, sep2 - (sep + 1)).c_str()));
102 int y(atoi(str.substr(sep2 + 1, s.length() - (sep2 + 1)).c_str()));
103 return date2int(y, m, d);
104}
int date2int(int y, int m, int d)
Definition DateTools.cpp:15

References date2int().

Referenced by SensorData::readDataFromFile().

◆ substituteKeyword()

template<typename T>
bool BaseLib::substituteKeyword ( std::string & result,
std::string const & parenthesized_string,
std::string::size_type const begin,
std::string::size_type const end,
std::string const & keyword,
T & data )

Definition at line 62 of file FileTools.cpp.

67{
68 std::string precision_specification =
69 containsKeyword(parenthesized_string, keyword);
70
71 if (precision_specification.empty())
72 {
73 return false;
74 }
75
76 if constexpr (std::is_same_v<std::remove_cvref_t<T>, bool>)
77 {
78 if (keyword == "converged")
79 {
80 std::string r = data ? "" : "_not_converged";
81 result.replace(begin, end - begin + 1, r);
82 return true;
83 }
84 }
85
86 std::unordered_map<std::type_index, char> type_specification;
87 type_specification[std::type_index(typeid(int))] = 'd';
88 type_specification[std::type_index(typeid(double))] = 'f'; // default
89 type_specification[std::type_index(typeid(std::string))] = 's';
90
91 auto const& b = precision_specification.back();
92 // see https://fmt.dev/latest/syntax/#format-specification-mini-language
93 if (b == 'e' || b == 'E' || b == 'f' || b == 'F' || b == 'g' || b == 'G')
94 {
95 type_specification[std::type_index(typeid(double))] = b;
96 precision_specification.pop_back();
97 }
98
99 std::string const generated_fmt_string =
100 "{" + precision_specification +
101 type_specification[std::type_index(typeid(data))] + "}";
102 result.replace(
103 begin, end - begin + 1,
104 fmt::vformat(generated_fmt_string, fmt::make_format_args(data)));
105
106 return true;
107}
std::string containsKeyword(std::string const &str, std::string const &keyword)
Definition FileTools.cpp:51

References containsKeyword().

Referenced by constructFormattedFileName().

◆ swapEndianness() [1/2]

double BaseLib::swapEndianness ( double const & v)

Definition at line 143 of file FileTools.cpp.

144{
145 union
146 {
147 double v;
148 char c[sizeof(double)];
149 } a{}, b{};
150
151 a.v = v;
152 for (unsigned short i = 0; i < sizeof(double) / 2; i++)
153 {
154 b.c[i] = a.c[sizeof(double) / 2 - i - 1];
155 }
156
157 for (unsigned short i = sizeof(double) / 2; i < sizeof(double); i++)
158 {
159 b.c[i] = a.c[sizeof(double) + sizeof(double) / 2 - i - 1];
160 }
161
162 return b.v;
163}

Referenced by FileIO::Gocad::GocadSGridReader::readNodesBinary().

◆ swapEndianness() [2/2]

template<typename T>
T BaseLib::swapEndianness ( T const & v)

Definition at line 54 of file FileTools.h.

55{
56 union
57 {
58 T v;
59 char c[sizeof(T)];
60 } a{}, b{};
61
62 a.v = v;
63 for (unsigned short i = 0; i < sizeof(T); i++)
64 {
65 b.c[i] = a.c[sizeof(T) - i - 1];
66 }
67
68 return b.v;
69}

◆ to_underlying()

◆ traverseIncludes()

void BaseLib::traverseIncludes ( xmlDoc * doc,
xmlNode * node,
std::filesystem::path const & prj_dir )

Definition at line 56 of file PrjProcessing.cpp.

58{
59 xmlNode* cur_node = nullptr;
60 for (cur_node = node; cur_node; cur_node = cur_node->next)
61 {
62 if (cur_node->type != XML_ELEMENT_NODE)
63 {
64 continue;
65 }
66 if (xmlStrEqual(cur_node->name, xmlCharStrdup("include")))
67 {
68 auto include_file_char_pointer =
69 xmlGetProp(cur_node, xmlCharStrdup("file"));
70 if (include_file_char_pointer == nullptr)
71 {
73 "Error while processing includes in prj file. Error in "
74 "element '{:s}' on line {:d}: no file attribute given!",
75 reinterpret_cast<const char*>(cur_node->name),
76 cur_node->line);
77 }
78 auto filename_length = xmlStrlen(include_file_char_pointer);
79 std::string filename(
80 reinterpret_cast<char*>(include_file_char_pointer),
81 filename_length);
82 if (auto const filepath = std::filesystem::path(filename);
83 filepath.is_relative())
84 {
85 filename = (prj_dir / filepath).string();
86 }
87
88 if (!std::filesystem::exists(filename))
89 {
91 "Error while processing includes in prj file. Error in "
92 "element '{:s}' on line {:d}: Include file is not "
93 "existing: "
94 "{:s}!",
95 reinterpret_cast<const char*>(cur_node->name),
96 cur_node->line,
97 reinterpret_cast<const char*>(include_file_char_pointer));
98 }
99 INFO("Including {:s} into project file.", filename);
100
101 const std::ifstream input_stream(filename, std::ios_base::binary);
102 if (input_stream.fail())
103 {
104 OGS_FATAL("Failed to open file {}!", filename);
105 }
106 std::stringstream buffer;
107 buffer << input_stream.rdbuf();
108 const std::string xml = buffer.str();
109
110 // Replace lines containing <?xml ... ?>
111 std::regex xmlDeclaration("<\\?xml.*?>");
112 const std::string xml_filtered =
113 std::regex_replace(xml, xmlDeclaration, "");
114
115 xmlNodePtr pNewNode = nullptr;
116 xmlParseInNodeContext(cur_node->parent, xml_filtered.c_str(),
117 (int)xml_filtered.length(), 0, &pNewNode);
118 if (pNewNode != nullptr)
119 {
120 // add new xml node to parent
121 xmlNode* pChild = pNewNode;
122 while (pChild != nullptr)
123 {
124 xmlAddChild(cur_node->parent, xmlCopyNode(pChild, 1));
125 pChild = pChild->next;
126 }
127 xmlFreeNode(pNewNode);
128 }
129
130 // Cleanup and continue on next node
131 auto next_node = cur_node->next;
132 xmlUnlinkNode(cur_node);
133 xmlFreeNode(cur_node);
134 cur_node = next_node;
135 }
136 traverseIncludes(doc, cur_node->children, prj_dir);
137 }
138 xmlFreeNode(cur_node);
139}

References INFO(), OGS_FATAL, and traverseIncludes().

Referenced by replaceIncludes(), and traverseIncludes().

◆ trim()

void BaseLib::trim ( std::string & str,
char ch = ' ' )

Strip whitespace (or other characters) from the beginning and end of a string. Equivalent functionality to Qt::QString::trim().

Definition at line 50 of file StringTools.cpp.

51{
52 std::string::size_type pos = str.find_last_not_of(ch);
53 if (pos != std::string::npos)
54 {
55 str.erase(pos + 1);
56 pos = str.find_first_not_of(ch);
57 if (pos != std::string::npos)
58 {
59 str.erase(0, pos);
60 }
61 }
62 else
63 {
64 str.erase(str.begin(), str.end());
65 }
66}

Referenced by FileIO::FEFLOWMeshInterface::getIndexList(), getNumberOfThreadsFromEnv(), getValue(), getVariables(), MeshLib::IO::Legacy::MeshIO::loadMeshFromFile(), FileIO::Gocad::parseGocadPropertyMetaData(), FileIO::Gocad::GocadAsciiReader::parseHeader(), FileIO::FEFLOWMeshInterface::readELEMENTALSETS(), FileIO::FEFLOWMeshInterface::readElevation(), BaseLib::IO::readStringListFromFile(), FileIO::FEFLOWGeoInterface::readSuperMesh(), simplify(), MaterialLib::splitMaterialIdString(), and anonymous_namespace{FEFLOWGeoInterface.cpp}::xmlCharsToString().

◆ tryParseVector()

template<typename T>
std::optional< std::vector< T > > BaseLib::tryParseVector ( std::string const & raw,
std::size_t * bad_token_idx )

Tries to parse a whitespace-separated list of values from a string. Returns std::nullopt if parsing fails and sets the bad token index.

Definition at line 86 of file StringTools.h.

88{
89 std::istringstream iss{raw};
90
91 // Create a range that reads T values from the stream
92 auto values = ranges::istream_view<T>(iss);
93 std::vector<T> out = ranges::to<std::vector>(values);
94
95 // Check if we consumed the entire input
96 if (!iss.eof())
97 {
98 if (bad_token_idx)
99 {
100 *bad_token_idx = out.size() + 1;
101 }
102 return std::nullopt;
103 }
104 return out;
105}

Referenced by BaseLib::ConfigTree::getConfigParameterOptionalImpl(), and ParameterLib::getNamedOrCreateInlineParameter().

◆ type_name()

template<typename T>
const char * BaseLib::type_name ( )

◆ type_name< bool >()

template<>
const char * BaseLib::type_name< bool > ( )

Definition at line 37 of file TCLAPOutput.h.

38{
39 return "bool";
40}

◆ type_name< double >()

template<>
const char * BaseLib::type_name< double > ( )

Definition at line 27 of file TCLAPOutput.h.

28{
29 return "double";
30}

◆ type_name< float >()

template<>
const char * BaseLib::type_name< float > ( )

Definition at line 32 of file TCLAPOutput.h.

33{
34 return "float";
35}

◆ type_name< int >()

template<>
const char * BaseLib::type_name< int > ( )

Definition at line 22 of file TCLAPOutput.h.

23{
24 return "int";
25}

◆ type_name< long >()

template<>
const char * BaseLib::type_name< long > ( )

Definition at line 47 of file TCLAPOutput.h.

48{
49 return "long";
50}

◆ type_name< size_t >()

template<>
const char * BaseLib::type_name< size_t > ( )

Definition at line 42 of file TCLAPOutput.h.

43{
44 return "size_t";
45}

◆ type_name< std::string >()

template<>
const char * BaseLib::type_name< std::string > ( )

Definition at line 17 of file TCLAPOutput.h.

18{
19 return "string";
20}

◆ type_name< unsigned >()

template<>
const char * BaseLib::type_name< unsigned > ( )

Definition at line 52 of file TCLAPOutput.h.

53{
54 return "unsigned";
55}

◆ typeToString() [1/2]

template<typename T>
std::string BaseLib::typeToString ( )

Get a human-readable type name for error messages. Uses C++ ABI demangling (GCC/Clang) or UnDecorateSymbolName (MSVC) to convert RTTI symbols into readable type names. Falls back to typeid().name() if demangling fails.

Template overload for explicit type specification: typeToString<SomeType>()

Definition at line 30 of file DemangleTypeInfo.h.

31{
32 return demangle(typeid(T).name());
33}
std::string demangle(const char *mangled_name)

References demangle().

Referenced by ParameterLib::CoordinateSystem::CoordinateSystem(), ParameterLib::CoordinateSystem::CoordinateSystem(), ProcessLib::LIE::PostProcessTool::PostProcessTool(), BaseLib::MPI::allRanksThrowOrNone(), MeshLib::VtkMeshConverter::convertTypedArray(), createGenericIntegrationMethod(), MeshToolsLib::createSfcMeshProperties(), MaterialPropertyLib::Property::d2Value(), MaterialPropertyLib::Property::dValue(), MaterialPropertyLib::Property::dValue(), MeshLib::Properties::existsPropertyVector(), MeshLib::Properties::existsPropertyVector(), MeshLib::Properties::getPropertyVector(), MaterialPropertyLib::Property::initialValue(), ProcessLib::Graph::detail::isEvalOrderCorrectRT(), anonymous_namespace{BoundaryElementsAlongPolyline.cpp}::modifyEdgeNodeOrdering(), MeshLib::VtkMappedMeshSource::RequestData(), transfer(), MaterialPropertyLib::Property::value(), MaterialPropertyLib::Property::value(), MaterialPropertyLib::Property::value(), and MeshToolsLib::MeshInformation::writePropertyVectorInformation().

◆ typeToString() [2/2]

template<typename T>
std::string BaseLib::typeToString ( T && )

Template overload for type deduction from values: typeToString(some_value) This allows demangling without explicit decltype() in the call.

Definition at line 39 of file DemangleTypeInfo.h.

40{
41 return demangle(typeid(std::remove_cvref_t<T>).name());
42}

References demangle().

◆ uniquePushBack()

template<typename Container>
void BaseLib::uniquePushBack ( Container & container,
typename Container::value_type const & element )

Definition at line 234 of file Algorithm.h.

236{
237 if (std::find(container.begin(), container.end(), element) ==
238 container.end())
239 {
240 container.push_back(element);
241 }
242}

Referenced by GeoLib::EarClippingTriangulation::clipEars().

◆ writeValueBinary()

template<typename T>
void BaseLib::writeValueBinary ( std::ostream & out,
T const & val )

write value as binary into the given output stream

Template Parameters
Tdata type of the value
Parameters
outoutput stream, have to be opened in binary mode
valvalue

Definition at line 328 of file FileTools.cpp.

329{
330 out.write(reinterpret_cast<const char*>(&val), sizeof(T));
331}

Referenced by ApplicationUtils::writeProperties().

◆ writeValueBinary< std::size_t >()

template void BaseLib::writeValueBinary< std::size_t > ( std::ostream & ,
std::size_t const &  )

◆ xmlDate2int()

int BaseLib::xmlDate2int ( const std::string & s)

Converts a string containing a date into a double. Note: It is not really checked if the date actually makes sense.

Parameters
sString containing the date, the expected format is conform to the xml date type, i.e. "yyyy-mm-dd".
Returns
A number representing the date as yyyymmdd.

Definition at line 106 of file DateTools.cpp.

107{
108 if (s.length() == 10)
109 {
110 int d = atoi(s.substr(8, 2).c_str());
111 if (d < 1 || d > 31)
112 {
113 WARN("xmlDate2double(): day not in [1:31].");
114 }
115 int m = atoi(s.substr(5, 2).c_str());
116 if (m < 1 || m > 12)
117 {
118 WARN("xmlDate2double(): month not in [1:12].");
119 }
120 int y = atoi(s.substr(0, 4).c_str());
121 return date2int(y, m, d);
122 }
123 return 0;
124}

References date2int(), and WARN().

Referenced by GeoLib::StationBorehole::createStation().

Variable Documentation

◆ console

BASELIB_EXPORT std::shared_ptr< spdlog::logger > BaseLib::console