OGS
BaseLib Namespace Reference

Namespaces

namespace  detail
 
namespace  IO
 
namespace  TMP
 

Classes

class  ConfigTree
 
class  CPUTime
 Count CPU time. More...
 
class  GradualSubdivision
 
class  GradualSubdivisionFixedNum
 
class  Histogram
 
class  ISubdivision
 
class  MemWatch
 
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  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<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 >
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 >
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)
 
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 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)
 
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.
 
std::vector< int > splitMaterialIdString (std::string const &material_id_string)
 
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 292 of file Algorithm.h.

293{
294 // std::all_of is not constexpr enough in some STLs
295 for (auto& value : values)
296 {
297 if (!static_cast<bool>(value))
298 {
299 return false;
300 }
301 }
302
303 return true;
304}

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

277{
278 // std::any_of is not constexpr enough in some STLs
279 for (auto& value : values)
280 {
281 if (static_cast<bool>(value))
282 {
283 return true;
284 }
285 }
286
287 return false;
288}

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

487{
488 conf.checkAndInvalidate();
489}

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

492{
493 if (conf)
494 {
495 conf->checkAndInvalidate();
496 }
497}

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

500{
501 if (conf)
502 {
503 conf->checkAndInvalidate();
504 }
505}

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

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

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

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

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

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

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

177{
178 auto const filename_path = std::filesystem::path(filename);
179 return (filename_path.parent_path() / filename_path.stem()).string();
180}

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

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

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

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

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

183{
184 return std::filesystem::path(pathname).filename().string();
185}

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

215{
216 return std::filesystem::path(pathname).parent_path().string();
217}

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

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

References OGS_FATAL.

Referenced by MaterialPropertyLib::Phase::component(), MeshLib::findMeshByName(), MaterialLib::Solids::MFront::MFrontGeneric< DisplacementDim, Gradients, TDynForces, ExtStateVars >::initializeInternalStateVariables(), 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 222 of file Algorithm.h.

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

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

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

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

◆ format()

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

Definition at line 86 of file StringTools.cpp.

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

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

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

References OGS_FATAL.

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

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

Definition at line 113 of file Algorithm.h.

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

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

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

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

226{
228 {
229 OGS_FATAL("The project directory has not yet been set.");
230 }
231 return project_directory;
232}
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 121 of file StringTools.cpp.

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

Referenced by 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 198 of file FileTools.cpp.

199{
200 return boost::iequals(extension, getFileExtension(filename));
201}
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 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 99 of file Algorithm.h.

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

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 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:255

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]

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

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

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

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

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

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

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

329{
330 std::string prj_file = filepath;
331
332 std::vector<std::string> patch_files_copy = patch_files;
333 readAndPatchPrj(prj_stream, prj_file, patch_files_copy);
334 replaceIncludes(prj_stream,
335 std::filesystem::absolute(std::filesystem::path(prj_file))
336 .parent_path());
337 // re-apply xml patches to stream
338 for (const auto& patch_file : patch_files_copy)
339 {
340 patchStream(patch_file, prj_stream, true);
341 }
342
343 if (write_prj)
344 {
345 // The following two lines should set indenting to 4 spaces but it does
346 // not work. 2 spaces are default.
347 //
348 // xmlThrDefIndentTreeOutput(1);
349 // xmlThrDefTreeIndentString(" "); // 4 spaces indent
350 // XML_PARSE_NOBLANKS -> pretty-print
351 auto doc =
352 xmlReadMemory(prj_stream.str().c_str(), prj_stream.str().size(),
353 nullptr, nullptr, XML_PARSE_NOBLANKS);
354 auto prj_out = (std::filesystem::path(out_directory) /
355 std::filesystem::path(filepath).stem())
356 .string() +
357 "_processed.prj";
358 xmlSaveFormatFileEnc(prj_out.c_str(), doc, "utf-8", 1);
359 INFO("Processed project file written to {:s}.", prj_out);
360 xmlFreeDoc(doc);
361 }
362 xmlCleanupParser();
363}
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(), 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 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 103 of file StringTools.cpp.

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

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

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

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

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

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

272{
273 T v;
274 in.read(reinterpret_cast<char*>(&v), sizeof(T));
275 return v;
276}

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

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

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

263{
264 for (auto const& file : files)
265 {
266 removeFile(file);
267 }
268}
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 198 of file Algorithm.h.

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

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

151{
152 // Parsing the XML triggers floating point exceptions. Because we are not
153 // debugging libxml2 (or other libraries) at this point, the floating point
154 // exceptions are temporarily disabled and are restored at the end of the
155 // function.
156 [[maybe_unused]] DisableFPE disable_fpe;
157
158 auto doc = xmlReadMemory(prj_stream.str().c_str(), prj_stream.str().size(),
159 nullptr, nullptr, 0);
160 if (doc == nullptr)
161 {
162 OGS_FATAL("Error reading project file from memory.");
163 }
164
165 auto root_node = xmlDocGetRootElement(doc);
166 traverseIncludes(doc, root_node, prj_dir);
167
168 xmlChar* xmlbuff;
169 int buffersize;
170 xmlDocDumpMemory(doc, &xmlbuff, &buffersize);
171 prj_stream.str(""); // Empty stream
172 prj_stream << xmlbuff;
173
174 xmlFree(xmlbuff);
175 xmlFreeDoc(doc);
176}

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

54{
55 boost::replace_all(stringToReplace, searchString, replaceString);
56 return stringToReplace;
57}

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

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

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

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

References trim().

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

◆ splitMaterialIdString()

std::vector< int > BaseLib::splitMaterialIdString ( std::string const & material_id_string)

Parses a comma separated list of integers. Such lists occur in the medium definition in the OGS prj file. Error messages in this function refer to this specific purpose.

Definition at line 136 of file StringTools.cpp.

137{
138 auto const material_ids_strings =
139 BaseLib::splitString(material_id_string, ',');
140
141 std::vector<int> material_ids;
142 for (auto& mid_str : material_ids_strings)
143 {
144 std::size_t num_chars_processed = 0;
145 int material_id;
146 try
147 {
148 material_id = std::stoi(mid_str, &num_chars_processed);
149 }
150 catch (std::invalid_argument&)
151 {
152 OGS_FATAL(
153 "Could not parse material ID from '{}' to a valid "
154 "integer.",
155 mid_str);
156 }
157 catch (std::out_of_range&)
158 {
159 OGS_FATAL(
160 "Could not parse material ID from '{}'. The integer value "
161 "of the given string exceeds the permitted range.",
162 mid_str);
163 }
164
165 if (num_chars_processed != mid_str.size())
166 {
167 // Not the whole string has been parsed. Check the rest.
168 if (auto const it = std::find_if_not(
169 begin(mid_str) + num_chars_processed, end(mid_str),
170 [](unsigned char const c) { return std::isspace(c); });
171 it != end(mid_str))
172 {
173 OGS_FATAL(
174 "Could not parse material ID from '{}'. Please "
175 "separate multiple material IDs by comma only. "
176 "Invalid character: '{}' at position {}.",
177 mid_str, *it, distance(begin(mid_str), it));
178 }
179 }
180
181 material_ids.push_back(material_id);
182 };
183
184 return material_ids;
185}
std::vector< std::string > splitString(std::string const &str)

References OGS_FATAL, and splitString().

Referenced by ProjectData::parseMedia(), and parseOutputMeshConfig().

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

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

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

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

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 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 const & parenthesized_string,
std::string::size_type const begin,
std::string::size_type const end,
std::string const & keyword,
T & data )

Definition at line 86 of file FileTools.cpp.

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

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

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 e)
constexprnoexcept

◆ traverseIncludes()

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

Definition at line 64 of file PrjProcessing.cpp.

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

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

Referenced by FileIO::FEFLOWMeshInterface::getIndexList(), anonymous_namespace{ParallelVectorMatrixAssembler.cpp}::getNumberOfThreads(), 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 211 of file Algorithm.h.

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

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

◆ unsetProjectDirectory()

void BaseLib::unsetProjectDirectory ( )

Unsets the project directory.

Definition at line 246 of file FileTools.cpp.

247{
248 project_directory.clear();
250}

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

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

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