Loading [MathJax]/extensions/tex2jax.js
OGS
BaseLib Namespace Reference

Namespaces

namespace  detail
 
namespace  IO
 
namespace  MPI
 
namespace  TMP
 

Classes

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

Functions

template<typename T >
std::vector< T > excludeObjectCopy (std::vector< T > const &src_vec, std::vector< std::size_t > const &exclude_positions)
 
template<typename T >
void excludeObjectCopy (std::vector< T > const &src_vec, std::vector< std::size_t > const &exclude_positions, std::vector< T > &dest_vec)
 
template<ranges::input_range Range>
ranges::range_reference_t< RangefindElementOrError (Range &range, std::predicate< ranges::range_reference_t< Range > > auto &&predicate, std::invocable auto error_callback)
 
template<typename Map , typename Key , typename Value >
void insertIfKeyUniqueElseError (Map &map, Key const &key, Value &&value, std::string const &error_message)
 
template<typename Map , typename Key >
OGS_NO_DANGLING Map::mapped_type & getOrError (Map &map, Key const &key, std::string const &error_message)
 
template<typename Map , typename Key >
OGS_NO_DANGLING Map::mapped_type const & getOrError (Map const &map, Key const &key, std::string const &error_message)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
template<typename Container , typename Predicate >
OGS_NO_DANGLING Container::value_type const & getIfOrError (Container const &container, Predicate &&predicate, std::string const &error_message)
 
template<typename T >
void makeVectorUnique (std::vector< T > &v)
 
template<typename T , class Compare >
void makeVectorUnique (std::vector< T > &v, Compare comp)
 
template<typename ValueType , typename IndexType >
void reorderVector (std::vector< ValueType > &v, std::vector< IndexType > const &order)
 
template<typename Container >
void uniquePushBack (Container &container, typename Container::value_type const &element)
 
template<typename Container >
std::optional< typename Container::value_type > findFirstNotEqualElement (Container const &container, typename Container::value_type const &element)
 
template<typename Container >
std::size_t findIndex (Container const &container, typename Container::value_type const &element)
 
template<typename T >
void cleanupVectorElements (std::vector< T * > &items)
 
template<typename T1 , typename... Args>
void cleanupVectorElements (std::vector< T1 * > &dependent_items, Args &&... args)
 
template<ranges::range R>
requires std::is_integral_v<ranges::range_value_t<R>>
std::vector< ranges::range_value_t< R > > sizesToOffsets (R const &sizes)
 
template<typename List >
constexpr bool any_of (List const &values)
 Checks if any of the elements in the given list is true.
 
template<typename List >
constexpr bool all_of (List const &values)
 Checks if all of the elements in the given list are true.
 
template<typename List >
constexpr bool none_of (List const &values)
 Checks if none of the elements in the given list are true.
 
void checkAndInvalidate (ConfigTree &conf)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
void checkAndInvalidate (ConfigTree *const conf)
 
void checkAndInvalidate (std::unique_ptr< ConfigTree > const &conf)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
 
ConfigTree makeConfigTree (const std::string &filepath, const bool be_ruthless, const std::string &toplevel_tag, std::stringstream &prj_stream)
 
ConfigTree makeConfigTreeFromFile (const std::string &filepath, const bool be_ruthless, const std::string &toplevel_tag)
 
template<typename E >
constexpr auto to_underlying (E e) noexcept
 Converts an enumeration to its underlying type.
 
int date2int (int y, int m, int d)
 
std::string int2date (int date)
 
std::string date2string (double ddate)
 
int strDate2int (const std::string &s)
 
int xmlDate2int (const std::string &s)
 
std::string formatDate (std::chrono::time_point< std::chrono::system_clock > const &time)
 
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, bool const converged)
 
double swapEndianness (double const &v)
 
std::string dropFileExtension (std::string const &filename)
 
std::string extractBaseName (std::string const &pathname)
 
std::string extractBaseNameWithoutExtension (std::string const &pathname)
 
std::string getFileExtension (const std::string &path)
 
bool hasFileExtension (std::string const &extension, std::string const &filename)
 
std::string extractPath (std::string const &pathname)
 
std::string joinPaths (std::string const &pathA, std::string const &pathB)
 
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)
 
bool createOutputDirectory (std::string const &dir)
 
std::vector< double > readDoublesFromBinaryFile (const std::string &filename)
 
template<typename T >
readBinaryValue (std::istream &in)
 
template float readBinaryValue< float > (std::istream &)
 
template double readBinaryValue< double > (std::istream &)
 
template<typename T >
std::vector< T > readBinaryVector (std::string const &filename, std::size_t const start_element, std::size_t const num_elements)
 
template std::vector< float > readBinaryVector< float > (std::string const &, std::size_t const, std::size_t const)
 
template std::vector< double > readBinaryVector< double > (std::string const &, std::size_t const, std::size_t const)
 
template<typename T >
void writeValueBinary (std::ostream &out, T const &val)
 write value as binary into the given output stream
 
template void writeValueBinary< std::size_t > (std::ostream &, std::size_t const &)
 
template<typename T >
swapEndianness (T const &v)
 
template<typename T >
std::ostream & operator<< (std::ostream &os, const Histogram< T > &h)
 
template std::ostream & operator<< (std::ostream &os, const Histogram< double > &h)
 
void setConsoleLogLevel (std::string const &level_string)
 
void initOGSLogger (std::string const &log_level)
 
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 >
bool BaseLib::all_of ( List const & values)
constexpr

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

Definition at line 309 of file Algorithm.h.

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

◆ any_of()

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

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

Definition at line 293 of file Algorithm.h.

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

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

274{
275 cleanupVectorElements(dependent_items);
276 cleanupVectorElements(std::forward<Args>(args)...);
277}
void cleanupVectorElements(std::vector< T * > &items)
Definition Algorithm.h:256

References cleanupVectorElements().

◆ constructFormattedFileName()

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

Definition at line 134 of file FileTools.cpp.

140{
141 char const open_char = '{';
142 char const close_char = '}';
143 std::string::size_type begin = 0;
144 std::string::size_type end = std::string::npos;
145 std::string result = format_specification;
146
147 while (begin != std::string::npos)
148 {
149 auto length_before_substitution = result.length();
150 // find next parenthesized string
151 std::string str = "";
152 std::tie(str, begin, end) =
153 getParenthesizedString(result, open_char, close_char, begin);
154 if (!substituteKeyword(result, str, begin, end, "timestep", timestep) &&
155 !substituteKeyword(result, str, begin, end, "time", t) &&
156 !substituteKeyword(result, str, begin, end, "iteration",
157 iteration) &&
158 !substituteKeyword(result, str, begin, end, "converged", converged))
159 {
160 substituteKeyword(result, str, begin, end, "meshname", mesh_name);
161 }
162 begin = end - (length_before_substitution - result.length());
163 }
164
165 return result;
166}
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:54
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:87

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

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

Referenced by substituteKeyword().

◆ createOutputDirectory()

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

Definition at line 273 of file FileTools.cpp.

274{
275 if (dir.empty())
276 {
277 return false;
278 }
279
280 std::error_code mkdir_err;
281 if (std::filesystem::create_directories(dir, mkdir_err))
282 {
283 INFO("Output directory {:s} created.", dir);
284 }
285 else if (mkdir_err.value() != 0)
286 {
287 WARN("Could not create output directory {:s}. Error code {:d}, {:s}",
288 dir, mkdir_err.value(), mkdir_err.message());
289 return false;
290 }
291 return true;
292}
void INFO(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:35
void WARN(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:40

References INFO(), and WARN().

Referenced by initOGS(), and main().

◆ createTimeInterval()

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

Definition at line 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}

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

191{
192 auto const filename_path = std::filesystem::path(filename);
193 return (filename_path.parent_path() / filename_path.stem()).string();
194}

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

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

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

◆ excludeObjectCopy() [2/2]

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

Definition at line 70 of file Algorithm.h.

73{
74 dest_vec = excludeObjectCopy(src_vec, exclude_positions);
75}
std::vector< T > excludeObjectCopy(std::vector< T > const &src_vec, std::vector< std::size_t > const &exclude_positions)
Definition Algorithm.h:42

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

197{
198 return std::filesystem::path(pathname).filename().string();
199}

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

218{
219 return std::filesystem::path(pathname).parent_path().string();
220}

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

85{
86 auto it =
87 ranges::find_if(range, std::forward<decltype(predicate)>(predicate));
88 if (it == ranges::end(range))
89 {
90 error_callback();
92 "Element not found in the input range. The user provided error "
93 "callback is meant not to return. That has not happened.");
94 }
95 return *it;
96}
#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 227 of file Algorithm.h.

229{
230 auto const it =
231 std::find_if_not(container.begin(), container.end(),
232 [&element](typename Container::value_type const& e)
233 { return e == element; });
234 return it == container.end() ? std::nullopt : std::make_optional(*it);
235}

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

245{
246 auto const it = std::find(container.begin(), container.end(), element);
247 if (it == container.end())
248 {
249 return std::numeric_limits<std::size_t>::max();
250 }
251 return std::distance(container.begin(), it);
252}

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 >
OGS_NO_DANGLING Container::value_type const & BaseLib::getIfOrError ( Container const & container,
Predicate && predicate,
std::string const & error_message )

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

Definition at line 163 of file Algorithm.h.

167{
168 auto it = std::find_if(begin(container), end(container), predicate);
169 if (it == end(container))
170 {
171 OGS_FATAL("Could not find element matching the predicate: {:s}",
172 error_message);
173 }
174 return *it;
175}

References OGS_FATAL.

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

◆ getOrError() [1/2]

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

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

Definition at line 118 of file Algorithm.h.

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

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 >
OGS_NO_DANGLING Map::mapped_type const & BaseLib::getOrError ( Map const & map,
Key const & key,
std::string const & error_message )

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

Definition at line 139 of file Algorithm.h.

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

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

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

Referenced by constructFormattedFileName().

◆ getProjectDirectory()

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

Returns the directory where the prj file resides.

Definition at line 228 of file FileTools.cpp.

229{
231 {
232 OGS_FATAL("The project directory has not yet been set.");
233 }
234 return project_directory;
235}
std::string project_directory
The directory where the prj file resides.
Definition FileTools.cpp:32
bool project_directory_is_set
Whether the project directory has already been set.
Definition FileTools.cpp:35

References OGS_FATAL.

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

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

213{
214 return boost::iequals(extension, getFileExtension(filename));
215}
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 104 of file Algorithm.h.

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

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

41{
43}

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

191{
192 std::sort(v.begin(), v.end(), comp);
193 auto it = std::unique(v.begin(), v.end());
194 v.erase(it, v.end());
195}

◆ none_of()

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

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

Definition at line 325 of file Algorithm.h.

326{
327 return !any_of(values);
328}
constexpr bool any_of(List const &values)
Checks if any of the elements in the given list is true.
Definition Algorithm.h:293

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

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

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

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

◆ quicksort() [3/5]

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

Definition at line 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 271 of file PrjProcessing.cpp.

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

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

Referenced by prepareProjectFile().

◆ readBinaryValue()

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

Definition at line 310 of file FileTools.cpp.

311{
312 T v;
313 in.read(reinterpret_cast<char*>(&v), sizeof(T));
314 return v;
315}

◆ readBinaryValue< double >()

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

◆ readBinaryValue< float >()

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

◆ readBinaryVector()

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

Definition at line 322 of file FileTools.cpp.

325{
326 if (!IsFileExisting(filename))
327 {
328 OGS_FATAL("File {:s} not found", filename);
329 }
330
331 // Determine file size
332 std::uintmax_t file_size = std::filesystem::file_size(filename);
333 std::size_t total_elements = file_size / sizeof(T);
334
335 if (start_element >= total_elements)
336 {
337 OGS_FATAL("Start element is beyond file size");
338 }
339
340 // Calculate the number of elements to read
341 std::size_t const elements_to_read =
342 std::min(num_elements, total_elements - start_element);
343
344 // Calculate offset and size to map
345 std::size_t const offset = start_element * sizeof(T);
346 std::size_t const size_to_map = elements_to_read * sizeof(T);
347
348 // Create a file mapping
349 boost::interprocess::file_mapping file(filename.c_str(),
350 boost::interprocess::read_only);
351
352 // Map the specified region
353 boost::interprocess::mapped_region region(
354 file, boost::interprocess::read_only, offset, size_to_map);
355
356 // Get the address of the mapped region
357 auto* addr = region.get_address();
358
359 // Create vector and copy data
360 std::vector<T> result(elements_to_read);
361 std::memcpy(result.data(), addr, size_to_map);
362
363 if constexpr (std::endian::native != std::endian::little)
364 {
365 boost::endian::endian_reverse_inplace(result);
366 }
367
368 return result;
369}

References IsFileExisting(), and OGS_FATAL.

◆ readBinaryVector< double >()

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

◆ readBinaryVector< float >()

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

◆ readDoublesFromBinaryFile()

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

Definition at line 294 of file FileTools.cpp.

295{
296 auto prj_dir = BaseLib::getProjectDirectory();
297 std::string path_to_file = BaseLib::joinPaths(prj_dir, filename);
298 std::string file_extension = BaseLib::getFileExtension(filename);
299 if (file_extension != ".bin")
300 {
301 OGS_FATAL(
302 "Currently only binary files with extension '.bin' supported. The "
303 "specified file has extension {:s}.",
304 file_extension)
305 }
306 return BaseLib::readBinaryVector<double>(path_to_file);
307}
std::string const & getProjectDirectory()
Returns the directory where the prj file resides.
template std::vector< double > readBinaryVector< double >(std::string const &, std::size_t const, std::size_t const)

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

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

◆ removeFile()

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

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

Definition at line 255 of file FileTools.cpp.

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

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

266{
267 for (auto const& file : files)
268 {
269 removeFile(file);
270 }
271}
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 203 of file Algorithm.h.

205{
206 std::vector<ValueType> temp_v(v.size());
207 temp_v.swap(v);
208
209 for (std::size_t i = 0; i < order.size(); i++)
210 {
211 std::swap(v[i], temp_v[order[i]]);
212 }
213}

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

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

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(), main(), and main().

◆ setProjectDirectory()

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

Sets the project directory.

Definition at line 237 of file FileTools.cpp.

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

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

◆ sizesToOffsets()

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

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

Definition at line 283 of file Algorithm.h.

284{
285 return ranges::views::concat(
286 ranges::views::single(ranges::range_value_t<R>{0}),
287 ranges::views::partial_sum(sizes)) |
288 ranges::to<std::vector<ranges::range_value_t<R>>>();
289}

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

◆ splitString() [1/2]

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

Splits a string into a list of strings.

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

Definition at line 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 MaterialLib::splitMaterialIdString().

◆ str2number()

◆ strDate2int()

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

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

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

Definition at line 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 87 of file FileTools.cpp.

92{
93 std::string precision_specification =
94 containsKeyword(parenthesized_string, keyword);
95
96 if (precision_specification.empty())
97 {
98 return false;
99 }
100
101 if constexpr (std::is_same_v<std::remove_cvref_t<T>, bool>)
102 {
103 if (keyword == "converged")
104 {
105 std::string r = data ? "" : "_not_converged";
106 result.replace(begin, end - begin + 1, r);
107 return true;
108 }
109 }
110
111 std::unordered_map<std::type_index, char> type_specification;
112 type_specification[std::type_index(typeid(int))] = 'd';
113 type_specification[std::type_index(typeid(double))] = 'f'; // default
114 type_specification[std::type_index(typeid(std::string))] = 's';
115
116 auto const& b = precision_specification.back();
117 // see https://fmt.dev/latest/syntax/#format-specification-mini-language
118 if (b == 'e' || b == 'E' || b == 'f' || b == 'F' || b == 'g' || b == 'G')
119 {
120 type_specification[std::type_index(typeid(double))] = b;
121 precision_specification.pop_back();
122 }
123
124 std::string const generated_fmt_string =
125 "{" + precision_specification +
126 type_specification[std::type_index(typeid(data))] + "}";
127 result.replace(
128 begin, end - begin + 1,
129 fmt::vformat(generated_fmt_string, fmt::make_format_args(data)));
130
131 return true;
132}
std::string containsKeyword(std::string const &str, std::string const &keyword)
Definition FileTools.cpp:76

References containsKeyword().

Referenced by constructFormattedFileName().

◆ swapEndianness() [1/2]

double BaseLib::swapEndianness ( double const & v)

Definition at line 168 of file FileTools.cpp.

169{
170 union
171 {
172 double v;
173 char c[sizeof(double)];
174 } a{}, b{};
175
176 a.v = v;
177 for (unsigned short i = 0; i < sizeof(double) / 2; i++)
178 {
179 b.c[i] = a.c[sizeof(double) / 2 - i - 1];
180 }
181
182 for (unsigned short i = sizeof(double) / 2; i < sizeof(double); i++)
183 {
184 b.c[i] = a.c[sizeof(double) + sizeof(double) / 2 - i - 1];
185 }
186
187 return b.v;
188}

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

◆ swapEndianness() [2/2]

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

Definition at line 69 of file FileTools.h.

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

◆ to_underlying()

◆ traverseIncludes()

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

Definition at line 63 of file PrjProcessing.cpp.

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

218{
219 if (std::find(container.begin(), container.end(), element) ==
220 container.end())
221 {
222 container.push_back(element);
223 }
224}

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

◆ unsetProjectDirectory()

void BaseLib::unsetProjectDirectory ( )

Unsets the project directory.

Definition at line 249 of file FileTools.cpp.

250{
251 project_directory.clear();
253}

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

381{
382 out.write(reinterpret_cast<const char*>(&val), sizeof(T));
383}

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