OGS
BaseLib Namespace Reference

Detailed Description

Basic algorithms and helper functions provided for all other libraries.

Namespaces

namespace  IO
 
namespace  TMP
 

Classes

class  ConfigTree
 
class  CPUTime
 Count CPU time. More...
 
struct  DynamicSpan
 
class  GradualSubdivision
 
class  GradualSubdivisionFixedNum
 
class  Histogram
 
class  ISubdivision
 
class  MemWatch
 
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...
 
class  TCLAPCustomOutput
 
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<typename InputIt , typename Predicate >
std::iterator_traits< InputIt >::reference findElementOrError (InputIt begin, InputIt end, Predicate predicate, std::string const &error="")
 
template<typename Map , typename Key , typename Value >
void insertIfTypeIndexKeyUniqueElseError (Map &map, Key const &key, Value &&value, std::string const &error_message)
 
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 , typename Value >
void insertIfKeyValueUniqueElseError (Map &map, Key const &key, Value &&value, std::string const &error_message)
 
template<typename Map , typename Key >
Map::mapped_type & getOrError (Map &map, Key const &key, std::string const &error_message)
 
template<typename Map , typename Key >
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 >
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 >
bool contains (Container const &container, typename Container::value_type const &element)
 
template<typename Container , typename Predicate >
bool containsIf (Container const &container, Predicate &&predicate)
 
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<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)
 
template<typename T >
 DynamicSpan (T *, std::size_t) -> DynamicSpan< T >
 
bool isProjectDirectorySet ()
 Returns true if the project directory is set.
 
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 &parenthesized_string, std::string::size_type begin, std::string::size_type 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)
 
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 copyPathToFileName (const std::string &file_name, const std::string &source)
 
std::string extractPath (std::string const &pathname)
 
std::string joinPaths (std::string const &pathA, std::string const &pathB)
 
std::string const & getProjectDirectory ()
 Returns the directory where the prj file resides.
 
void setProjectDirectory (std::string const &dir)
 Sets the project directory.
 
void unsetProjectDirectory ()
 Unsets the project directory.
 
void removeFile (std::string const &filename)
 
void removeFiles (std::vector< std::string > const &files)
 
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 > readBinaryArray (std::string const &filename, std::size_t const n)
 
template std::vector< float > readBinaryArray< float > (std::string 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)
 
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)
 
TimeInterval createTimeInterval (ConfigTree const &config)
 

Variables

std::shared_ptr< spdlog::logger > console = spdlog::stdout_color_mt("ogs")
 

Function Documentation

◆ all_of()

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

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

Definition at line 341 of file Algorithm.h.

342{
343 // std::all_of is not constexpr enough in some STLs
344 for (auto& value : values)
345 {
346 if (!static_cast<bool>(value))
347 {
348 return false;
349 }
350 }
351
352 return true;
353}

◆ any_of()

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

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

Definition at line 325 of file Algorithm.h.

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

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

476{
477 conf.checkAndInvalidate();
478}

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

481{
482 if (conf)
483 {
484 conf->checkAndInvalidate();
485 }
486}

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

489{
490 if (conf)
491 {
492 conf->checkAndInvalidate();
493 }
494}

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

318{
319 cleanupVectorElements(dependent_items);
320 cleanupVectorElements(std::forward<Args>(args)...);
321}
void cleanupVectorElements(std::vector< T * > &items)
Definition: Algorithm.h:300

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 
)

Definition at line 120 of file FileTools.cpp.

125{
126 char const open_char = '{';
127 char const close_char = '}';
128 std::string::size_type begin = 0;
129 std::string::size_type end = std::string::npos;
130 std::string result = format_specification;
131
132 while (begin != std::string::npos)
133 {
134 auto length_before_substitution = result.length();
135 // find next parenthesized string
136 std::string str = "";
137 std::tie(str, begin, end) =
138 getParenthesizedString(result, open_char, close_char, begin);
139 if (!substituteKeyword(result, str, begin, end, "timestep", timestep) &&
140 !substituteKeyword(result, str, begin, end, "time", t) &&
141 !substituteKeyword(result, str, begin, end, "iteration", iteration))
142 {
143 substituteKeyword(result, str, begin, end, "meshname", mesh_name);
144 }
145 begin = end - (length_before_substitution - result.length());
146 }
147
148 return result;
149}
bool substituteKeyword(std::string &result, std::string &parenthesized_string, std::string::size_type begin, std::string::size_type end, std::string const &keyword, T &data)
Definition: FileTools.cpp:86
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:53

References getParenthesizedString(), and substituteKeyword().

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

◆ contains()

template<typename Container >
bool BaseLib::contains ( Container const &  container,
typename Container::value_type const &  element 
)

Definition at line 256 of file Algorithm.h.

258{
259 return std::find(container.begin(), container.end(), element) !=
260 container.end();
261}

Referenced by ProcessLib::LIE::duGlobalEnrichments(), and ProcessLib::DeactivatedSubdomain::isDeactivated().

◆ containsIf()

template<typename Container , typename Predicate >
bool BaseLib::containsIf ( Container const &  container,
Predicate &&  predicate 
)

Definition at line 264 of file Algorithm.h.

265{
266 return std::find_if(container.begin(), container.end(), predicate) !=
267 container.end();
268}

Referenced by ProjectData::parseProcesses().

◆ containsKeyword()

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

Definition at line 75 of file FileTools.cpp.

76{
77 auto const position = str.find(keyword);
78 if (position != std::string::npos)
79 {
80 return str.substr(0, position);
81 }
82 return "";
83}

Referenced by substituteKeyword().

◆ copyPathToFileName()

std::string BaseLib::copyPathToFileName ( const std::string &  file_name,
const std::string &  source 
)

Checks if file_name already contains a qualified path and if not copies the path from source.

Definition at line 200 of file FileTools.cpp.

202{
203 auto filePath = std::filesystem::path(file_name);
204 if (filePath.has_parent_path())
205 {
206 return filePath.string();
207 }
208 return (std::filesystem::path(source) /= filePath).string();
209}

Referenced by ProjectData::ProjectData(), anonymous_namespace{ProjectData.cpp}::readMeshes(), anonymous_namespace{ProjectData.cpp}::readSingleMesh(), and GeoLib::IO::XmlStnInterface::readStations().

◆ 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 23 of file TimeInterval.cpp.

24{
26 auto const& time_interval_config = config.getConfigSubtree("time_interval");
27
28 const auto start_time =
30 time_interval_config.getConfigParameter<double>("start");
31
32 const auto end_time =
34 time_interval_config.getConfigParameter<double>("end");
35
36 return {start_time, end_time};
37}

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

Referenced by ProcessLib::createDirichletBoundaryConditionWithinTimeInterval().

◆ 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 26 of file DateTools.cpp.

27{
28 if ((y < 1000 || y > 9999) || (m < 1 || m > 12) || (d < 1 || d > 31))
29 {
30 WARN("date2int(): Input not in expected range.");
31 return 0;
32 }
33
34 int ddate(0);
35 ddate = y * 10000;
36 ddate += (m * 100);
37 ddate += d;
38
39 return ddate;
40}
void WARN(fmt::format_string< Args... > fmt, Args &&... args)
Definition: Logging.h:40

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 65 of file DateTools.cpp.

66{
67 if (ddate < 10000101 || ddate > 99991231)
68 {
69 WARN("date2String(): Input not in expected format.");
70 return "0.0.0000";
71 }
72
73 auto rest(static_cast<int>(ddate));
74 auto y = static_cast<int>(std::floor(rest / 10000.0));
75 rest = rest % (y * 10000);
76 auto m = static_cast<int>(std::floor(rest / 100.0));
77 if (m < 1 || m > 12)
78 {
79 WARN("date2String(): month not in [1:12].");
80 }
81 rest = rest % (m * 100);
82 int d = rest;
83 if (d < 1 || d > 31)
84 {
85 WARN("date2String(): day not in [1:31].");
86 }
87
88 std::string day = std::to_string(d);
89 if (d < 10)
90 {
91 day = "0" + day;
92 }
93 std::string month = std::to_string(m);
94 if (m < 10)
95 {
96 month = "0" + month;
97 }
98 std::string s = std::to_string(y) + "-" + month + "-" + day;
99 return s;
100}

References WARN().

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

◆ dropFileExtension()

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

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

Definition at line 173 of file FileTools.cpp.

174{
175 auto const filename_path = std::filesystem::path(filename);
176 return (filename_path.parent_path() / filename_path.stem()).string();
177}

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

◆ DynamicSpan()

template<typename T >
BaseLib::DynamicSpan ( T *  ,
std::size_t   
) -> DynamicSpan< T >

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

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

Referenced by MeshLib::PropertyVector< PROP_VAL_TYPE >::clone(), MeshLib::PropertyVector< T * >::clone(), and excludeObjectCopy().

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

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

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 179 of file FileTools.cpp.

180{
181 return std::filesystem::path(pathname).filename().string();
182}

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 211 of file FileTools.cpp.

212{
213 return std::filesystem::path(pathname).parent_path().string();
214}

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<typename InputIt , typename Predicate >
std::iterator_traits< InputIt >::reference BaseLib::findElementOrError ( InputIt  begin,
InputIt  end,
Predicate  predicate,
std::string const &  error = "" 
)

Definition at line 69 of file Algorithm.h.

72{
73 auto it = std::find_if(begin, end, predicate);
74 if (it == end)
75 {
76 OGS_FATAL("Element not found in the input range; {:s}", error);
77 }
78 return *it;
79}
#define OGS_FATAL(...)
Definition: Error.h:26

References OGS_FATAL.

Referenced by MaterialPropertyLib::Phase::component(), ParameterLib::createParameter(), ProcessLib::SurfaceFluxData::createSurfaceFluxData(), anonymous_namespace{ProcessVariable.cpp}::findMeshInConfig(), ProjectData::parseProcessVariables(), MaterialPropertyLib::Medium::phase(), and ProcessLib::Output::prepareSubmesh().

◆ findFirstNotEqualElement()

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

Definition at line 271 of file Algorithm.h.

273{
274 auto const it =
275 std::find_if_not(container.begin(), container.end(),
276 [&element](typename Container::value_type const& e)
277 { return e == element; });
278 return it == container.end() ? std::nullopt : std::make_optional(*it);
279}

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

289{
290 auto const it = std::find(container.begin(), container.end(), element);
291 if (it == container.end())
292 {
293 return std::numeric_limits<std::size_t>::max();
294 }
295 return std::distance(container.begin(), it);
296}

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

◆ format()

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

Definition at line 84 of file StringTools.cpp.

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

◆ 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 137 of file DateTools.cpp.

139{
140 auto const time_t = std::chrono::system_clock::to_time_t(time);
141 char time_str[100];
142 if (std::strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S%z",
143 std::localtime(&time_t)))
144 {
145 return time_str;
146 }
147 return "FAILED FORMATTING THE GIVEN TIME POINT.";
148}

Referenced by executeSimulation(), initOGS(), and main().

◆ getFileExtension()

◆ getIfOrError()

template<typename Container , typename Predicate >
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 192 of file Algorithm.h.

196{
197 auto it = std::find_if(begin(container), end(container), predicate);
198 if (it == end(container))
199 {
200 OGS_FATAL("Could not find element matching the predicate: {:s}",
201 error_message);
202 }
203 return *it;
204}

References OGS_FATAL.

Referenced by ProcessLib::createPerProcessData().

◆ getOrError() [1/2]

template<typename Map , typename Key >
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.

Remarks
Use as:
get_or_error<Value>(some_map, some_key, "error
message")

Definition at line 147 of file Algorithm.h.

149{
150 auto it = map.find(key);
151 if (it == map.end())
152 {
153 if constexpr (std::is_convertible<Key, std::string>::value)
154 {
155 OGS_FATAL("{:s} Key `{:s}' does not exist.", error_message, key);
156 }
157 else
158 {
159 OGS_FATAL("{:s} Key `{:s}' does not exist.", error_message,
160 std::to_string(key));
161 }
162 }
163
164 return it->second;
165}

References OGS_FATAL.

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

170{
171 auto it = map.find(key);
172 if (it == map.end())
173 {
174 if constexpr (std::is_convertible<Key, std::string>::value)
175 {
176 OGS_FATAL("{:s} Key `{:s}' does not exist.", error_message, key);
177 }
178 else
179 {
180 OGS_FATAL("{:s} Key `{:s}' does not exist.", error_message,
181 std::to_string(key));
182 }
183 }
184
185 return it->second;
186}

References OGS_FATAL.

◆ 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 53 of file FileTools.cpp.

57{
58 auto const pos_curly_brace_open = in.find_first_of(open_char, pos);
59 if (pos_curly_brace_open == std::string::npos)
60 {
61 return std::make_tuple("", std::string::npos, std::string::npos);
62 }
63 auto const pos_curly_brace_close =
64 in.find_first_of(close_char, pos_curly_brace_open);
65 if (pos_curly_brace_close == std::string::npos)
66 {
67 return std::make_tuple("", std::string::npos, std::string::npos);
68 }
69 return std::make_tuple(
70 in.substr(pos_curly_brace_open + 1,
71 pos_curly_brace_close - (pos_curly_brace_open + 1)),
72 pos_curly_brace_open, pos_curly_brace_close);
73}

Referenced by constructFormattedFileName().

◆ getProjectDirectory()

std::string const & BaseLib::getProjectDirectory ( )

Returns the directory where the prj file resides.

Definition at line 222 of file FileTools.cpp.

223{
225 {
226 OGS_FATAL("The project directory has not yet been set.");
227 }
228 return project_directory;
229}
std::string project_directory
The directory where the prj file resides.
Definition: FileTools.cpp:31
bool project_directory_is_set
Whether the project directory has already been set.
Definition: FileTools.cpp:34

References OGS_FATAL.

Referenced by ChemistryLib::createChemicalSolverInterface< ChemicalSolver::Phreeqc >(), ProcessLib::ComponentTransport::createLookupTable(), MaterialLib::Solids::MFront::createMFrontConfig(), Simulation::initializeDataStructures(), and parseCommandLineArguments().

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

121{
122 std::string result_name = input_name;
123 std::size_t count = 1;
124 while (std::find(existing_names.cbegin(),
125 existing_names.cend(),
126 result_name) != existing_names.end())
127 {
128 count++;
129 result_name = input_name + "-" + std::to_string(count);
130 }
131 return result_name;
132}

Referenced by GeoLib::GEOObjects::isUniquePointVecName(), MeshLib::RasterDataToMesh::projectToElements(), and MeshLib::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 195 of file FileTools.cpp.

196{
197 return boost::iequals(extension, getFileExtension(filename));
198}
std::string getFileExtension(const std::string &path)
Definition: FileTools.cpp:190

References getFileExtension().

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

◆ initOGSLogger()

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

Definition at line 54 of file Logging.cpp.

55{
57 spdlog::set_pattern("%^%l:%$ %v");
58 spdlog::set_error_handler(
59 [](const std::string& msg)
60 {
61 std::cerr << "spdlog error: " << msg << std::endl;
62 OGS_FATAL("spdlog logger error occurred.");
63 });
64}
void setConsoleLogLevel(std::string const &level_string)
Definition: Logging.cpp:37

References OGS_FATAL, and setConsoleLogLevel().

Referenced by initOGS(), and main().

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

108{
109 auto const inserted = map.emplace(key, std::forward<Value>(value));
110 if (!inserted.second)
111 { // insertion failed, i.e., key already exists
112 OGS_FATAL("{} Key `{}' already exists.", error_message, key);
113 }
114}

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

◆ insertIfKeyValueUniqueElseError()

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

Inserts the given key with the given value into the map if neither an entry with the given key nor an entry with the given value already exists; otherwise an error_message is printed and the program is aborted.

Definition at line 121 of file Algorithm.h.

123{
124 auto value_compare = [&value](typename Map::value_type const& elem)
125 { return value == elem.second; };
126
127 if (std::find_if(map.cbegin(), map.cend(), value_compare) != map.cend())
128 {
129 OGS_FATAL("{:s} Value `{:s}' already exists.", error_message,
130 std::to_string(value));
131 }
132
133 auto const inserted = map.emplace(key, std::forward<Value>(value));
134 if (!inserted.second)
135 { // insertion failed, i.e., key already exists
136 OGS_FATAL("{:s} Key `{:s}' already exists.", error_message,
137 std::to_string(key));
138 }
139}

References OGS_FATAL.

◆ insertIfTypeIndexKeyUniqueElseError()

template<typename Map , typename Key , typename Value >
void BaseLib::insertIfTypeIndexKeyUniqueElseError ( 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. Note: The type of key must be std::type_index.

Definition at line 88 of file Algorithm.h.

91{
92 auto const inserted = map.emplace(key, std::forward<Value>(value));
93 if (!inserted.second)
94 { // insertion failed, i.e., key already exists
95 OGS_FATAL("{:s} Key `{:s}' already exists.", error_message,
96 std::to_string(key.hash_code()));
97 }
98}

References OGS_FATAL.

◆ 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 42 of file DateTools.cpp.

43{
44 if (date > 10000000 && date < 22000000)
45 {
46 auto y = static_cast<int>(std::floor(date / 10000.0));
47 auto m = static_cast<int>(std::floor((date - (y * 10000)) / 100.0));
48 int d = date - (y * 10000) - (m * 100);
49 std::stringstream ss;
50 if (d < 10)
51 {
52 ss << "0";
53 }
54 ss << d << ".";
55 if (m < 10)
56 {
57 ss << "0";
58 }
59 ss << m << "." << y;
60 return ss.str();
61 }
62 return "";
63}

Referenced by DiagramList::readList().

◆ IsFileExisting()

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

◆ isProjectDirectorySet()

bool BaseLib::isProjectDirectorySet ( )

Returns true if the project directory is set.

Definition at line 39 of file FileTools.cpp.

40{
42}

◆ 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 24 of file ConfigTreeUtil.cpp.

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

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 57 of file ConfigTreeUtil.cpp.

60{
61 std::ifstream file(filepath);
62 if (file)
63 {
64 std::stringstream buffer;
65 buffer << file.rdbuf();
66
67 return makeConfigTree(filepath, be_ruthless, toplevel_tag, buffer);
68 }
69 else
70 {
71 OGS_FATAL("Could not read from file {:s}!", filepath);
72 }
73}
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().

◆ makeVectorUnique() [1/2]

template<typename T >
void BaseLib::makeVectorUnique ( std::vector< T > &  v)

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

220{
221 std::sort(v.begin(), v.end(), comp);
222 auto it = std::unique(v.begin(), v.end());
223 v.erase(it, v.end());
224}

◆ none_of()

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

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

Definition at line 357 of file Algorithm.h.

358{
359 return !any_of(values);
360}
constexpr bool any_of(List const &values)
Checks if any of the elements in the given list is true.
Definition: Algorithm.h:325

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 77 of file Histogram.cpp.

78{
79 os << h.getNumberOfBins() << " " << h.getMinimum() << " " << h.getMaximum()
80 << " ";
81 std::copy(h.getBinCounts().begin(), h.getBinCounts().end(),
82 std::ostream_iterator<std::size_t>(os, " "));
83 return os << std::endl;
84}
const T & getMinimum() const
Definition: Histogram.h:112
const unsigned int & getNumberOfBins() const
Definition: Histogram.h:111
const std::vector< std::size_t > & getBinCounts() const
Definition: Histogram.h:110
const T & getMaximum() const
Definition: Histogram.h:113

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 141 of file PrjProcessing.cpp.

143{
144 auto patch = xmlParseFile(patch_file.c_str());
145 if (patch == nullptr)
146 {
147 OGS_FATAL("Error reading XML diff file {:s}.", patch_file);
148 }
149
150 auto doc =
151 xmlParseMemory(prj_stream.str().c_str(), prj_stream.str().size());
152 if (doc == nullptr)
153 {
154 OGS_FATAL("Error reading project file from memory.");
155 }
156
157 auto node = xmlDocGetRootElement(patch);
158 int rc = 0;
159 for (node = node ? node->children : nullptr; node; node = node->next)
160 {
161 if (node->type != XML_ELEMENT_NODE)
162 {
163 continue;
164 }
165 bool node_after_includes = false;
166 xmlAttr* attribute = node->properties;
167 while (attribute)
168 {
169 // Check for after_includes-attribute
170 xmlChar* value =
171 xmlNodeListGetString(node->doc, attribute->children, 1);
172 if (xmlStrEqual(attribute->name, xmlCharStrdup("after_includes")) &&
173 xmlStrEqual(value, xmlCharStrdup("true")))
174 {
175 node_after_includes = true;
176 }
177
178 xmlFree(value);
179 attribute = attribute->next;
180 }
181
182 if (after_includes != node_after_includes)
183 {
184 continue;
185 }
186
187 if (xmlStrEqual(node->name, xmlCharStrdup("add")))
188 {
189 rc = xml_patch_add(doc, node);
190 }
191 else if (xmlStrEqual(node->name, xmlCharStrdup("replace")))
192 {
193 rc = xml_patch_replace(doc, node);
194 }
195 else if (xmlStrEqual(node->name, xmlCharStrdup("remove")))
196 {
197 rc = xml_patch_remove(doc, node);
198 }
199 else
200 {
201 OGS_FATAL(
202 "Error while patching prj file with patch file {:}. Only "
203 "'add', 'replace' and 'remove' elements are allowed! Got an "
204 "element '{:s}' on line {:d}.",
205 patch_file, node->name, node->line);
206 }
207
208 if (rc)
209 {
210 OGS_FATAL(
211 "Error while patching prj file with patch file {:}. Error in "
212 "element '{:s}' on line {:d}.",
213 patch_file, node->name, node->line);
214 }
215 }
216
217 xmlChar* xmlbuff;
218 int buffersize;
219 xmlDocDumpMemory(doc, &xmlbuff, &buffersize);
220 prj_stream.str(""); // Empty stream
221 prj_stream << xmlbuff;
222
223 xmlFree(xmlbuff);
224 xmlFreeDoc(doc);
225 xmlFreeDoc(patch);
226}

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 283 of file PrjProcessing.cpp.

287{
288 std::string prj_file = filepath;
289
290 std::vector<std::string> patch_files_copy = patch_files;
291 readAndPatchPrj(prj_stream, prj_file, patch_files_copy);
292 replaceIncludes(prj_stream,
293 std::filesystem::absolute(std::filesystem::path(prj_file))
294 .parent_path());
295 // re-apply xml patches to stream
296 for (const auto& patch_file : patch_files_copy)
297 {
298 patchStream(patch_file, prj_stream, true);
299 }
300
301 if (write_prj)
302 {
303 // pretty-print
304 xmlKeepBlanksDefault(0);
305
306 // The following two lines should set indenting to 4 spaces but it does
307 // not work. 2 spaces are default.
308 //
309 // xmlThrDefIndentTreeOutput(1);
310 // xmlThrDefTreeIndentString(" "); // 4 spaces indent
311 auto doc =
312 xmlParseMemory(prj_stream.str().c_str(), prj_stream.str().size());
313 auto prj_out = (std::filesystem::path(out_directory) /
314 std::filesystem::path(filepath).stem())
315 .string() +
316 "_processed.prj";
317 xmlSaveFormatFileEnc(prj_out.c_str(), doc, "utf-8", 1);
318 INFO("Processed project file written to {:s}.", prj_out);
319 xmlFreeDoc(doc);
320 }
321 xmlCleanupParser();
322}
void INFO(fmt::format_string< Args... > fmt, Args &&... args)
Definition: Logging.h:35
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 52 of file quicksort.h.

53{
54 using T1 = typename std::iterator_traits<It1>::value_type;
55 using T2 = typename std::iterator_traits<It2>::value_type;
56
57 quicksort(first1, last1, first2,
58 [](std::pair<T1, T2> const& a, std::pair<T1, T2> const& b)
59 { return a.first < b.first; });
60}
void quicksort(It1 first1, It1 last1, It2 first2, Comparator compare)
Definition: quicksort.h:26

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 26 of file quicksort.h.

27{
28 using T1 = typename std::iterator_traits<It1>::value_type;
29 using T2 = typename std::iterator_traits<It2>::value_type;
30
31 std::vector<std::pair<T1, T2>> data;
32 data.reserve(std::distance(first1, last1));
33 std::transform(first1, last1, first2, std::back_inserter(data),
34 [](T1 const& t1, T2 const& t2)
35 { return std::make_pair(t1, t2); });
36
37 // Sort data using first element of the pair.
38 std::sort(begin(data), end(data), compare);
39
40 // Unzip sorted data.
41 for (auto const& pair : data)
42 {
43 *first1 = pair.first;
44 *first2 = pair.second;
45 ++first1;
46 ++first2;
47 }
48}

Referenced by 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 83 of file quicksort.h.

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

◆ 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 72 of file quicksort.h.

74{
75 assert(beg <= end);
76 assert(end <= array.size());
77 assert(perm.size() == array.size());
78
79 quicksort(array.data(), beg, end, perm.data());
80}

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

65{
66 assert(beg <= end);
67
68 quicksort(array + beg, array + end, perm + beg);
69}

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

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

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 230 of file PrjProcessing.cpp.

232{
233 // Extract base project file path if an xml (patch) file is given as prj
234 // file and it contains the base_file attribute.
235 if (BaseLib::getFileExtension(prj_file) == ".xml")
236 {
237 if (!patch_files.empty())
238 {
239 OGS_FATAL(
240 "It is not allowed to specify additional patch files "
241 "if a patch file was already specified as the "
242 "prj-file.");
243 }
244 auto patch = xmlParseFile(prj_file.c_str());
245 auto node = xmlDocGetRootElement(patch);
246 xmlChar const base_file_string[] = "base_file";
247 auto base_file = xmlGetProp(node, base_file_string);
248 if (base_file == nullptr)
249 {
250 OGS_FATAL(
251 "Error reading base prj file (base_file attribute) in given "
252 "patch file {:s}.",
253 prj_file);
254 }
255 patch_files = {prj_file};
256 std::stringstream ss;
257 ss << base_file;
258 prj_file = BaseLib::joinPaths(BaseLib::extractPath(prj_file), ss.str());
259 }
260
261 // read base prj file into stream
262 if (std::ifstream file(prj_file); file)
263 {
264 prj_stream << file.rdbuf();
265 }
266 else
267 {
268 if (!BaseLib::IsFileExisting(prj_file))
269 {
270 ERR("File {:s} does not exist.", prj_file);
271 }
272 DBUG("Stream state flags: {:b}.", file.rdstate());
273 OGS_FATAL("Could not open project file '{:s}' for reading.", prj_file);
274 }
275
276 // apply xml patches to stream
277 for (const auto& patch_file : patch_files)
278 {
279 patchStream(patch_file, prj_stream);
280 }
281}
void ERR(fmt::format_string< Args... > fmt, Args &&... args)
Definition: Logging.h:45
std::string extractPath(std::string const &pathname)
Definition: FileTools.cpp:211
bool IsFileExisting(const std::string &strFilename)
Returns true if given file exists.
Definition: FileTools.cpp:47
std::string joinPaths(std::string const &pathA, std::string const &pathB)
Definition: FileTools.cpp:216

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

Referenced by prepareProjectFile().

◆ readBinaryArray()

template<typename T >
std::vector< T > BaseLib::readBinaryArray ( std::string const &  filename,
std::size_t const  n 
)

Definition at line 280 of file FileTools.cpp.

281{
282 std::ifstream in(filename.c_str());
283 if (!in)
284 {
285 ERR("readBinaryArray(): Error while reading from file '{:s}'.",
286 filename);
287 ERR("Could not open file '{:s}' for input.", filename);
288 in.close();
289 return std::vector<T>();
290 }
291
292 std::vector<T> result;
293 result.reserve(n);
294
295 for (std::size_t p = 0; in && !in.eof() && p < n; ++p)
296 {
297 result.push_back(BaseLib::readBinaryValue<T>(in));
298 }
299
300 if (result.size() == n)
301 {
302 return result;
303 }
304
305 ERR("readBinaryArray(): Error while reading from file '{:s}'.", filename);
306 ERR("Read different number of values. Expected {:d}, got {:d}.",
307 n,
308 result.size());
309
310 if (!in.eof())
311 {
312 ERR("EOF reached.\n");
313 }
314
315 return std::vector<T>();
316}

References ERR().

◆ readBinaryArray< float >()

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

◆ readBinaryValue()

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

Definition at line 268 of file FileTools.cpp.

269{
270 T v;
271 in.read(reinterpret_cast<char*>(&v), sizeof(T));
272 return v;
273}

◆ readBinaryValue< double >()

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

◆ readBinaryValue< float >()

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

◆ 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 249 of file FileTools.cpp.

250{
251 bool const success =
252 std::filesystem::remove(std::filesystem::path(filename));
253 if (success)
254 {
255 DBUG("Removed '{:s}'", filename);
256 }
257}

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 259 of file FileTools.cpp.

260{
261 for (auto const& file : files)
262 {
263 removeFile(file);
264 }
265}
void removeFile(std::string const &filename)
Definition: FileTools.cpp:249

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

234{
235 std::vector<ValueType> temp_v(v.size());
236 temp_v.swap(v);
237
238 for (std::size_t i = 0; i < order.size(); i++)
239 {
240 std::swap(v[i], temp_v[order[i]]);
241 }
242}

Referenced by MaterialLib::PorousMedium::createPorousMediaProperties(), and ProcessLib::TwoPhaseFlowWithPrho::createTwoPhaseFlowPrhoMaterialProperties().

◆ replaceIncludes()

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

Definition at line 111 of file PrjProcessing.cpp.

113{
114 // Parsing the XML triggers floating point exceptions. Because we are not
115 // debugging libxml2 (or other libraries) at this point, the floating point
116 // exceptions are temporarily disabled and are restored at the end of the
117 // function.
118 [[maybe_unused]] DisableFPE disable_fpe;
119
120 auto doc =
121 xmlParseMemory(prj_stream.str().c_str(), prj_stream.str().size());
122 if (doc == nullptr)
123 {
124 OGS_FATAL("Error reading project file from memory.");
125 }
126
127 auto root_node = xmlDocGetRootElement(doc);
128 traverseIncludes(doc, root_node, prj_dir);
129
130 xmlChar* xmlbuff;
131 int buffersize;
132 xmlDocDumpMemory(doc, &xmlbuff, &buffersize);
133 prj_stream.str(""); // Empty stream
134 prj_stream << xmlbuff;
135
136 xmlFree(xmlbuff);
137 xmlFreeDoc(doc);
138}

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

52{
53 boost::replace_all(stringToReplace, searchString, replaceString);
54 return stringToReplace;
55}

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

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

References console, ERR(), and OGS_FATAL.

Referenced by initOGSLogger(), and main().

◆ setProjectDirectory()

void BaseLib::setProjectDirectory ( std::string const &  dir)

Sets the project directory.

Definition at line 231 of file FileTools.cpp.

232{
234 {
235 OGS_FATAL("The project directory has already been set.");
236 }
237 // TODO Remove these global vars. They are a possible source of errors when
238 // invoking OGS from Python multiple times within a single session.
239 project_directory = dir;
241}

References OGS_FATAL.

Referenced by parseCommandLineArguments().

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

76{
77 trim(str);
78 str.erase(std::unique(str.begin(),
79 str.end(),
80 [](char a, char b) { return a == ' ' && b == ' '; }),
81 str.end());
82}
void trim(std::string &str, char ch)
Definition: StringTools.cpp:57

References trim().

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

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

38{
39 std::list<std::string> strList;
40 std::stringstream ss(str);
41 std::string item;
42 while (getline(ss, item, delim))
43 {
44 strList.push_back(item);
45 }
46 return strList;
47}

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

28{
29 std::istringstream str_stream(str);
30 std::vector<std::string> items;
31 std::copy(std::istream_iterator<std::string>(str_stream),
32 std::istream_iterator<std::string>(),
33 std::back_inserter(items));
34 return items;
35}

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(), FileIO::SwmmInterface::readLineElements(), FileIO::SwmmInterface::readLinksAsPolylines(), FileIO::SwmmInterface::readNodeData(), FileIO::PetrelInterface::readPetrelWellTrace(), FileIO::PetrelInterface::readPetrelWellTraceData(), FileIO::CsvInterface::readPoints(), FileIO::SwmmInterface::readPollutants(), FileIO::SwmmInterface::readPolygons(), FileIO::SwmmInterface::readSubcatchments(), and splitMaterialIdString().

◆ str2number()

template<typename T >
T BaseLib::str2number ( const std::string &  str)

Converts a string into a number (double, float, int, ...) Example: std::size_t number (str2number<std::size_t> (str));

Parameters
strstring to be converted
Returns
the number

Definition at line 60 of file StringTools.h.

61{
62 std::stringstream strs(str, std::stringstream::in | std::stringstream::out);
63 T v;
64 strs >> v;
65 return v;
66}

◆ 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 102 of file DateTools.cpp.

103{
104 std::string str(s);
105 if (s.length() > 10)
106 {
107 str = s.substr(0, 10);
108 }
109 std::size_t sep(str.find('.', 0));
110 int d(atoi(str.substr(0, sep).c_str()));
111 std::size_t sep2(str.find('.', sep + 1));
112 int m(atoi(str.substr(sep + 1, sep2 - (sep + 1)).c_str()));
113 int y(atoi(str.substr(sep2 + 1, s.length() - (sep2 + 1)).c_str()));
114 return date2int(y, m, d);
115}

References date2int().

Referenced by SensorData::readDataFromFile().

◆ substituteKeyword()

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

Definition at line 86 of file FileTools.cpp.

89{
90 std::string precision_specification =
91 containsKeyword(parenthesized_string, keyword);
92
93 if (precision_specification.empty())
94 {
95 return false;
96 }
97
98 std::unordered_map<std::type_index, char> type_specification;
99 type_specification[std::type_index(typeid(int))] = 'd';
100 type_specification[std::type_index(typeid(double))] = 'f'; // default
101 type_specification[std::type_index(typeid(std::string))] = 's';
102
103 auto const& b = precision_specification.back();
104 // see https://fmt.dev/latest/syntax.html#formatspec
105 if (b == 'e' || b == 'E' || b == 'f' || b == 'F' || b == 'g' || b == 'G')
106 {
107 type_specification[std::type_index(typeid(double))] = b;
108 precision_specification.pop_back();
109 }
110
111 std::string const generated_fmt_string =
112 "{" + precision_specification +
113 type_specification[std::type_index(typeid(data))] + "}";
114 result = result.substr(0, begin) +
115 fmt::vformat(generated_fmt_string, fmt::make_format_args(data)) +
116 result.substr(end + 1, result.length() - (end + 1));
117 return true;
118}
std::string containsKeyword(std::string const &str, std::string const &keyword)
Definition: FileTools.cpp:75

References containsKeyword().

Referenced by constructFormattedFileName().

◆ swapEndianness() [1/2]

double BaseLib::swapEndianness ( double const &  v)

Definition at line 151 of file FileTools.cpp.

152{
153 union
154 {
155 double v;
156 char c[sizeof(double)];
157 } a{}, b{};
158
159 a.v = v;
160 for (unsigned short i = 0; i < sizeof(double) / 2; i++)
161 {
162 b.c[i] = a.c[sizeof(double) / 2 - i - 1];
163 }
164
165 for (unsigned short i = sizeof(double) / 2; i < sizeof(double); i++)
166 {
167 b.c[i] = a.c[sizeof(double) + sizeof(double) / 2 - i - 1];
168 }
169
170 return b.v;
171}

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

◆ swapEndianness() [2/2]

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

Definition at line 66 of file FileTools.h.

67{
68 union
69 {
70 T v;
71 char c[sizeof(T)];
72 } a, b;
73
74 a.v = v;
75 for (unsigned short i = 0; i < sizeof(T); i++)
76 {
77 b.c[i] = a.c[sizeof(T) - i - 1];
78 }
79
80 return b.v;
81}

◆ to_underlying()

template<typename E >
constexpr auto BaseLib::to_underlying ( e)
constexprnoexcept

◆ traverseIncludes()

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

Definition at line 29 of file PrjProcessing.cpp.

31{
32 xmlNode* cur_node = nullptr;
33 for (cur_node = node; cur_node; cur_node = cur_node->next)
34 {
35 if (cur_node->type != XML_ELEMENT_NODE)
36 {
37 continue;
38 }
39 if (xmlStrEqual(cur_node->name, xmlCharStrdup("include")))
40 {
41 auto include_file_char_pointer =
42 xmlGetProp(cur_node, xmlCharStrdup("file"));
43 if (include_file_char_pointer == nullptr)
44 {
46 "Error while processing includes in prj file. Error in "
47 "element '{:s}' on line {:d}: no file attribute given!",
48 cur_node->name, cur_node->line);
49 }
50 auto filename_length = xmlStrlen(include_file_char_pointer);
51 std::string filename(
52 reinterpret_cast<char*>(include_file_char_pointer),
53 filename_length);
54 if (auto const filepath = std::filesystem::path(filename);
55 filepath.is_relative())
56 {
57 filename = (prj_dir / filepath).string();
58 }
59
60 if (!std::filesystem::exists(filename))
61 {
63 "Error while processing includes in prj file. Error in "
64 "element '{:s}' on line {:d}: Include file is not "
65 "existing: "
66 "{:s}!",
67 cur_node->name, cur_node->line, include_file_char_pointer);
68 }
69 INFO("Including {:s} into project file.", filename);
70
71 const std::ifstream input_stream(filename, std::ios_base::binary);
72 if (input_stream.fail())
73 {
74 OGS_FATAL("Failed to open file {}!", filename);
75 }
76 std::stringstream buffer;
77 buffer << input_stream.rdbuf();
78 const std::string xml = buffer.str();
79
80 // Replace lines containing <?xml ... ?>
81 std::regex xmlDeclaration("<\\?xml.*?>");
82 const std::string xml_filtered =
83 std::regex_replace(xml, xmlDeclaration, "");
84
85 xmlNodePtr pNewNode = nullptr;
86 xmlParseInNodeContext(cur_node->parent, xml_filtered.c_str(),
87 (int)xml_filtered.length(), 0, &pNewNode);
88 if (pNewNode != nullptr)
89 {
90 // add new xml node to parent
91 xmlNode* pChild = pNewNode;
92 while (pChild != nullptr)
93 {
94 xmlAddChild(cur_node->parent, xmlCopyNode(pChild, 1));
95 pChild = pChild->next;
96 }
97 xmlFreeNode(pNewNode);
98 }
99
100 // Cleanup and continue on next node
101 auto next_node = cur_node->next;
102 xmlUnlinkNode(cur_node);
103 xmlFreeNode(cur_node);
104 cur_node = next_node;
105 }
106 traverseIncludes(doc, cur_node->children, prj_dir);
107 }
108 xmlFreeNode(cur_node);
109}
void traverseIncludes(xmlDoc *doc, xmlNode *node, std::filesystem::path const &prj_dir)

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

58{
59 std::string::size_type pos = str.find_last_not_of(ch);
60 if (pos != std::string::npos)
61 {
62 str.erase(pos + 1);
63 pos = str.find_first_not_of(ch);
64 if (pos != std::string::npos)
65 {
66 str.erase(0, pos);
67 }
68 }
69 else
70 {
71 str.erase(str.begin(), str.end());
72 }
73}

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

◆ uniquePushBack()

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

Definition at line 245 of file Algorithm.h.

247{
248 if (std::find(container.begin(), container.end(), element) ==
249 container.end())
250 {
251 container.push_back(element);
252 }
253}

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

◆ unsetProjectDirectory()

void BaseLib::unsetProjectDirectory ( )

Unsets the project directory.

Definition at line 243 of file FileTools.cpp.

244{
245 project_directory.clear();
247}

Referenced by finalize().

◆ 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 323 of file FileTools.cpp.

324{
325 out.write(reinterpret_cast<const char*>(&val), sizeof(T));
326}

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 117 of file DateTools.cpp.

118{
119 if (s.length() == 10)
120 {
121 int d = atoi(s.substr(8, 2).c_str());
122 if (d < 1 || d > 31)
123 {
124 WARN("xmlDate2double(): day not in [1:31].");
125 }
126 int m = atoi(s.substr(5, 2).c_str());
127 if (m < 1 || m > 12)
128 {
129 WARN("xmlDate2double(): month not in [1:12].");
130 }
131 int y = atoi(s.substr(0, 4).c_str());
132 return date2int(y, m, d);
133 }
134 return 0;
135}
int date2int(int y, int m, int d)
Definition: DateTools.cpp:26

References date2int(), and WARN().

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

Variable Documentation

◆ console

BASELIB_EXPORT std::shared_ptr< spdlog::logger > BaseLib::console = spdlog::stdout_color_mt("ogs")

Definition at line 32 of file Logging.cpp.

Referenced by CRITICAL(), DBUG(), ERR(), INFO(), setConsoleLogLevel(), and WARN().