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
struct  TimeInterval
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<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 getNumberOfAssemblyThreads ()
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.
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)
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 > ()
TimeInterval createTimeInterval (ConfigTree const &config)

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 302 of file Algorithm.h.

303{
304 // std::all_of is not constexpr enough in some STLs
305 for (auto& value : values)
306 {
307 if (!static_cast<bool>(value))
308 {
309 return false;
310 }
311 }
312
313 return true;
314}

◆ 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 286 of file Algorithm.h.

287{
288 // std::any_of is not constexpr enough in some STLs
289 for (auto& value : values)
290 {
291 if (static_cast<bool>(value))
292 {
293 return true;
294 }
295 }
296
297 return false;
298}

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 509 of file ConfigTree.cpp.

510{
511 conf.checkAndInvalidate();
512}

◆ 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 514 of file ConfigTree.cpp.

515{
516 if (conf)
517 {
518 conf->checkAndInvalidate();
519 }
520}

◆ 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 522 of file ConfigTree.cpp.

523{
524 if (conf)
525 {
526 conf->checkAndInvalidate();
527 }
528}

◆ 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 266 of file Algorithm.h.

267{
268 cleanupVectorElements(dependent_items);
269 cleanupVectorElements(std::forward<Args>(args)...);
270}
void cleanupVectorElements(std::vector< T * > &items)
Definition Algorithm.h:249

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

◆ createTimeInterval()

TimeInterval BaseLib::createTimeInterval ( ConfigTree const & config)
Input File Parameter
prj__time_loop__processes__process__time_interval
Input File Parameter
prj__time_loop__processes__process__time_interval__start
Input File Parameter
prj__time_loop__processes__process__time_interval__end

Definition at line 12 of file TimeInterval.cpp.

13{
15 auto const& time_interval_config = config.getConfigSubtree("time_interval");
16
17 const auto start_time =
19 time_interval_config.getConfigParameter<double>("start");
20
21 const auto end_time =
23 time_interval_config.getConfigParameter<double>("end");
24
25 return {start_time, end_time};
26}

References BaseLib::ConfigTree::getConfigParameter(), and BaseLib::ConfigTree::getConfigSubtree().

Referenced by ProcessLib::parseDirichletBoundaryConditionWithinTimeIntervalConfig().

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

◆ 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 19 of file DemangleTypeInfo.cpp.

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

Referenced by 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 35 of file Algorithm.h.

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

Referenced by MeshLib::PropertyVector< PROP_VAL_TYPE >::clone(), MeshLib::PropertyVector< T * >::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 63 of file Algorithm.h.

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

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 74 of file Algorithm.h.

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

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(), ChemistryLib::PhreeqcIOData::PhreeqcIO::operator>>, and MaterialPropertyLib::Medium::phase().

◆ findFirstNotEqualElement()

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

Definition at line 220 of file Algorithm.h.

222{
223 auto const it =
224 std::find_if_not(container.begin(), container.end(),
225 [&element](typename Container::value_type const& e)
226 { return e == element; });
227 return it == container.end() ? std::nullopt : std::make_optional(*it);
228}

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 236 of file Algorithm.h.

238{
239 auto const it = std::find(container.begin(), container.end(), element);
240 if (it == container.end())
241 {
242 return std::numeric_limits<std::size_t>::max();
243 }
244 return std::distance(container.begin(), it);
245}

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

◆ format()

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

Definition at line 75 of file StringTools.cpp.

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

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

◆ 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 156 of file Algorithm.h.

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

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 14 of file OgsAsmThreads.cpp.

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

References OGS_FATAL, and trim().

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

◆ 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 111 of file Algorithm.h.

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

References OGS_FATAL, and OGS_NO_DANGLING.

Referenced by ProcessLib::HeatTransportBHE::BHE::createBuildingPowerCurvesStruct(), ProcessLib::HeatTransportBHE::BHE::createCoolingVariant(), MaterialPropertyLib::createCurve(), ProcessLib::HeatTransportBHE::BHE::createFlowAndTemperatureControl(), ProcessLib::createPerProcessData(), 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 132 of file Algorithm.h.

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

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 110 of file StringTools.cpp.

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

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

◆ 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 56 of file Logging.cpp.

57{
58 if (!console)
59 {
60#ifdef USE_PETSC
61 console = spdlog::stdout_color_mt("ogs");
62#else // USE_PETSC
63 console = spdlog::stdout_color_st("ogs");
64#endif // USE_PETSC
65 // Default pattern and error handler both for MPI and non-MPI builds.
66 spdlog::set_pattern("%^%l:%$ %v");
67 spdlog::set_error_handler(error_handler);
68
69#ifdef USE_PETSC
70 int mpi_init;
71 MPI_Initialized(&mpi_init);
72 if (mpi_init == 1)
73 {
74 MPI_Comm_rank(BaseLib::MPI::OGS_COMM_WORLD, &mpi_rank);
75 spdlog::set_pattern(fmt::format("[{}] %^%l:%$ %v", mpi_rank));
76 spdlog::set_error_handler(mpi_error_handler);
77 }
78#endif // USE_PETSC
79 }
81}
MPI_Comm OGS_COMM_WORLD
Definition MPI.cpp:9
void setConsoleLogLevel(std::string const &level_string)
Definition Logging.cpp:39
std::shared_ptr< spdlog::logger > console
Definition Logging.cpp:37

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

Referenced by OGSSimulation::OGSSimulation(), main(), main(), PYBIND11_MODULE(), 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 97 of file Algorithm.h.

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

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 else
63 {
64 OGS_FATAL("Could not read from file {:s}!", filepath);
65 }
66}
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 11 of file TCLAPArguments.cpp.

12{
13 static std::vector<std::string> allowed_log_levels{"none", "error", "warn",
14 "info", "debug", "all"};
15 static auto* allowed_log_levels_vals =
16 new TCLAP::ValuesConstraint<std::string>(allowed_log_levels);
17
18 return TCLAP::ValueArg<std::string>(
19 "l", "log-level", "the verbosity of logging messages", false,
20#ifdef NDEBUG
21 "info",
22#else
23 "all",
24#endif
25 allowed_log_levels_vals);
26}

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 183 of file Algorithm.h.

184{
185 std::sort(v.begin(), v.end(), comp);
186 auto it = std::unique(v.begin(), v.end());
187 v.erase(it, v.end());
188}

◆ 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 318 of file Algorithm.h.

319{
320 return !any_of(values);
321}
constexpr bool any_of(List const &values)
Checks if any of the elements in the given list is true.
Definition Algorithm.h:286

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

◆ 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 92 of file StringTools.cpp.

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

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 196 of file Algorithm.h.

198{
199 std::vector<ValueType> temp_v(v.size());
200 temp_v.swap(v);
201
202 for (std::size_t i = 0; i < order.size(); i++)
203 {
204 std::swap(v[i], temp_v[order[i]]);
205 }
206}

◆ 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 40 of file StringTools.cpp.

43{
44 boost::replace_all(stringToReplace, searchString, replaceString);
45 return stringToReplace;
46}
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 39 of file Logging.cpp.

40{
41 using namespace spdlog::level;
42 std::map<std::string, level_enum> string_to_log_level = {
43 {"none", off}, {"critical", critical}, {"error", err}, {"warn", warn},
44 {"info", info}, {"debug", debug}, {"all", trace}};
45
46 auto const level = string_to_log_level.find(level_string);
47 if (level == string_to_log_level.end())
48 {
49 ERR("'{:s}' is not a valid log level!", level_string);
50 OGS_FATAL("Wrong log level string.");
51 }
52 console->set_level(level->second);
53 spdlog::set_default_logger(console);
54}

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 66 of file StringTools.cpp.

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

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 276 of file Algorithm.h.

277{
278 return ranges::views::concat(
279 ranges::views::single(ranges::range_value_t<R>{0}),
280 ranges::views::partial_sum(sizes)) |
281 ranges::to<std::vector<ranges::range_value_t<R>>>();
282}

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 28 of file StringTools.cpp.

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

◆ 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 18 of file StringTools.cpp.

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

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 48 of file StringTools.cpp.

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

Referenced by FileIO::FEFLOWMeshInterface::getIndexList(), getNumberOfAssemblyThreads(), 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(), and simplify().

◆ 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 85 of file StringTools.h.

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

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

◆ 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 209 of file Algorithm.h.

211{
212 if (std::find(container.begin(), container.end(), element) ==
213 container.end())
214 {
215 container.push_back(element);
216 }
217}

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