OGS
BaseLib Namespace Reference

Detailed Description

Basic algorithms and helper functions provided for all other libraries.

Namespaces

 IO
 

Classes

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

Functions

template<typename T >
std::vector< T > excludeObjectCopy (std::vector< T > const &src_vec, std::vector< std::size_t > const &exclude_positions)
 
template<typename T >
void excludeObjectCopy (std::vector< T > const &src_vec, std::vector< std::size_t > const &exclude_positions, std::vector< T > &dest_vec)
 
template<typename InputIt , typename Predicate >
std::iterator_traits< InputIt >::reference findElementOrError (InputIt begin, InputIt end, Predicate predicate, std::string const &error="")
 
template<typename Map , typename Key , typename Value >
void insertIfTypeIndexKeyUniqueElseError (Map &map, Key const &key, Value &&value, std::string const &error_message)
 
template<typename Map , typename Key , typename Value >
void insertIfKeyUniqueElseError (Map &map, Key const &key, Value &&value, std::string const &error_message)
 
template<typename Map , typename Key , typename Value >
void insertIfKeyValueUniqueElseError (Map &map, Key const &key, Value &&value, std::string const &error_message)
 
template<typename Map , typename Key >
Map::mapped_type & getOrError (Map &map, Key const &key, std::string const &error_message)
 
template<typename Map , typename Key >
Map::mapped_type const & getOrError (Map const &map, Key const &key, std::string const &error_message)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts. More...
 
template<typename Container , typename Predicate >
Container::value_type const & getIfOrError (Container const &container, Predicate &&predicate, std::string const &error_message)
 
template<typename T >
void makeVectorUnique (std::vector< T > &v)
 
template<typename T , class Compare >
void makeVectorUnique (std::vector< T > &v, Compare comp)
 
template<typename ValueType , typename IndexType >
void reorderVector (std::vector< ValueType > &v, std::vector< IndexType > const &order)
 
template<typename Container >
void uniquePushBack (Container &container, typename Container::value_type const &element)
 
template<typename Container >
bool contains (Container const &container, typename Container::value_type const &element)
 
template<typename Container , typename Predicate >
bool containsIf (Container const &container, Predicate &&predicate)
 
template<typename Container >
std::optional< typename Container::value_type > findFirstNotEqualElement (Container const &container, typename Container::value_type const &element)
 
template<typename Container >
std::size_t findIndex (Container const &container, typename Container::value_type const &element)
 
template<typename T1 , typename T2 >
void cleanupVectorElements (std::vector< T1 * > const &items, std::vector< T2 * > const &dependent_items)
 
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. More...
 
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. More...
 
template<typename T >
void traverse_recursive (boost::property_tree::ptree &parent, boost::property_tree::ptree::path_type const &child_path, boost::property_tree::ptree &child, fs::path const &bench_dir, T &method)
 
template<typename T >
void traverse (boost::property_tree::ptree &parent, const fs::path bench_dir, T &method)
 
void replaceIncludes ([[maybe_unused]] boost::property_tree::ptree const &parent, [[maybe_unused]] boost::property_tree::ptree::path_type const &child_path, boost::property_tree::ptree &child, fs::path const &bench_dir)
 
void patchStream (std::string patch_file, std::stringstream &prj_stream)
 
void readAndPatchPrj (std::stringstream &prj_stream, std::string &prj_file, std::vector< std::string > patch_files)
 
ConfigTreeTopLevel makeConfigTree (const std::string &filepath, const bool be_ruthless, const std::string &toplevel_tag, const std::vector< std::string > &patch_files)
 
template<typename E >
constexpr auto to_underlying (E e) noexcept
 Converts an enumeration to its underlying type. More...
 
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. More...
 
bool IsFileExisting (const std::string &strFilename)
 Returns true if given file exists. More...
 
std::tuple< std::string, std::string::size_type, std::string::size_type > getParenthesizedString (std::string const &in, char const open_char, char const close_char, std::string::size_type pos)
 
std::string containsKeyword (std::string const &str, std::string const &keyword)
 
template<typename T >
bool substituteKeyword (std::string &result, std::string &parenthesized_string, std::string::size_type begin, std::string::size_type end, std::string const &keyword, T &data)
 
std::string constructFormattedFileName (std::string const &format_specification, std::string const &mesh_name, int const timestep, double const t, int const iteration)
 
double swapEndianness (double const &v)
 
std::string dropFileExtension (std::string const &filename)
 
std::string extractBaseName (std::string const &pathname)
 
std::string extractBaseNameWithoutExtension (std::string const &pathname)
 
std::string getFileExtension (const std::string &path)
 
bool hasFileExtension (std::string const &extension, std::string const &filename)
 
std::string copyPathToFileName (const std::string &file_name, const std::string &source)
 
std::string extractPath (std::string const &pathname)
 
std::string joinPaths (std::string const &pathA, std::string const &pathB)
 
std::string const & getProjectDirectory ()
 Returns the directory where the prj file resides. More...
 
void setProjectDirectory (std::string const &dir)
 Sets the project directory. More...
 
void removeFile (std::string const &filename)
 
void removeFiles (std::vector< std::string > const &files)
 
template<typename T >
void writeValueBinary (std::ostream &out, T const &val)
 write value as binary into the given output stream More...
 
template<typename T >
swapEndianness (T const &v)
 
template<typename T >
readBinaryValue (std::istream &in)
 
template<typename T >
std::vector< T > readBinaryArray (std::string const &filename, std::size_t const n)
 
template<typename T >
std::ostream & operator<< (std::ostream &os, const Histogram< T > &h)
 
void setConsoleLogLevel (std::string const &level_string)
 
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. More...
 
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. More...
 
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

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

471 {
472  conf.checkAndInvalidate();
473 }

Referenced by BaseLib::ConfigTreeTopLevel::checkAndInvalidate().

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

476 {
477  if (conf)
478  {
479  conf->checkAndInvalidate();
480  }
481 }

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

484 {
485  if (conf)
486  {
487  conf->checkAndInvalidate();
488  }
489 }

◆ cleanupVectorElements()

template<typename T1 , typename T2 >
void BaseLib::cleanupVectorElements ( std::vector< T1 * > const &  items,
std::vector< T2 * > const &  dependent_items 
)

Util function to cleanup vectors

Definition at line 300 of file Algorithm.h.

302 {
303  for (auto dependent_item : dependent_items)
304  {
305  delete dependent_item;
306  }
307  for (auto item : items)
308  {
309  delete item;
310  }
311 }

Referenced by FileIO::SwmmInterface::convertSwmmInputToGeometry(), FileIO::Gocad::GocadAsciiReader::createMesh(), FileIO::GMSInterface::readGMS3DMMesh(), FileIO::TetGenInterface::readTetGenMesh(), and MeshLib::MeshRevision::simplifyMesh().

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

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

References getParenthesizedString(), and substituteKeyword().

Referenced by ProcessLib::Output::OutputFile::constructFilename(), and anonymous_namespace{Output.cpp}::constructPVDName().

◆ contains()

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

Definition at line 256 of file Algorithm.h.

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

Referenced by ProcessLib::LIE::duGlobalEnrichments(), and MaterialLib::Solids::MFront::getEquivalentPlasticStrainOffset().

◆ containsIf()

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

Definition at line 264 of file Algorithm.h.

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

Referenced by ProjectData::parseProcesses().

◆ containsKeyword()

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

Definition at line 71 of file FileTools.cpp.

72 {
73  auto const position = str.find(keyword);
74  if (position != std::string::npos)
75  {
76  return str.substr(0, position);
77  }
78  return "";
79 }

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

198 {
199  auto filePath = fs::path(file_name);
200  if (filePath.has_parent_path())
201  {
202  return filePath.string();
203  }
204  return (fs::path(source) /= filePath).string();
205 }

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

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

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(char const *fmt, Args const &... args)
Definition: Logging.h:37

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

170 {
171  auto const filename_path = fs::path(filename);
172  return (filename_path.parent_path() / filename_path.stem()).string();
173 }

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

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

References MathLib::LinAlg::copy().

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

◆ excludeObjectCopy() [2/2]

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

Definition at line 61 of file Algorithm.h.

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

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

176 {
177  return fs::path(pathname).filename().string();
178 }

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

208 {
209  return fs::path(pathname).parent_path().string();
210 }

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

◆ findElementOrError()

template<typename InputIt , typename Predicate >
std::iterator_traits<InputIt>::reference BaseLib::findElementOrError ( InputIt  begin,
InputIt  end,
Predicate  predicate,
std::string const &  error = "" 
)

Definition at line 69 of file Algorithm.h.

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

References OGS_FATAL.

Referenced by MaterialPropertyLib::Phase::component(), ParameterLib::createParameter(), ProcessLib::SurfaceFluxData::createSurfaceFluxData(), ProcessLib::Output::doOutputAlways(), anonymous_namespace{ProcessVariable.cpp}::findMeshInConfig(), ProjectData::parseProcessVariables(), 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 271 of file Algorithm.h.

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

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

◆ findIndex()

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

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

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

Definition at line 287 of file Algorithm.h.

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

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

◆ format()

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

Definition at line 85 of file StringTools.cpp.

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

Referenced by MeshLib::IO::getPropertyDataTypeSize(), main(), substituteKeyword(), and MeshLib::IO::write_xdmf().

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

◆ getFileExtension()

◆ getIfOrError()

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

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

Definition at line 192 of file Algorithm.h.

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

References OGS_FATAL.

Referenced by ProcessLib::createPerProcessData().

◆ getOrError() [1/2]

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

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

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

Definition at line 147 of file Algorithm.h.

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

References OGS_FATAL.

Referenced by MaterialPropertyLib::createCurve(), ProcessLib::HeatTransportBHE::BHE::createFlowAndTemperatureControl(), ProcessLib::createPerProcessData(), ProjectData::parseNonlinearSolvers(), and ProcessLib::parseTimeIntervalOrCurve().

◆ getOrError() [2/2]

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

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

Definition at line 168 of file Algorithm.h.

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

References OGS_FATAL.

◆ getParenthesizedString()

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

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

Definition at line 49 of file FileTools.cpp.

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

Referenced by constructFormattedFileName().

◆ getProjectDirectory()

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

Returns the directory where the prj file resides.

Definition at line 217 of file FileTools.cpp.

218 {
220  {
221  OGS_FATAL("The project directory has not yet been set.");
222  }
223  return project_directory;
224 }
std::string project_directory
The directory where the prj file resides.
Definition: FileTools.cpp:27
bool project_directory_is_set
Whether the project directory has already been set.
Definition: FileTools.cpp:30

References OGS_FATAL, anonymous_namespace{FileTools.cpp}::project_directory, and anonymous_namespace{FileTools.cpp}::project_directory_is_set.

Referenced by ChemistryLib::createChemicalSolverInterface< ChemicalSolver::Phreeqc >(), ProcessLib::ComponentTransport::createLookupTable(), MaterialLib::Solids::MFront::createMFront(), and main().

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

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

Referenced by GeoLib::GEOObjects::isUniquePointVecName(), MeshLib::RasterDataToMesh::projectToElements(), and MeshLib::RasterDataToMesh::projectToNodes().

◆ hasFileExtension()

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

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

Definition at line 191 of file FileTools.cpp.

192 {
193  return boost::iequals(extension, getFileExtension(filename));
194 }
std::string getFileExtension(const std::string &path)
Definition: FileTools.cpp:186

References getFileExtension().

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

◆ insertIfKeyUniqueElseError()

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

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

Definition at line 106 of file Algorithm.h.

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

References OGS_FATAL.

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

◆ insertIfKeyValueUniqueElseError()

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

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

Definition at line 121 of file Algorithm.h.

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

References OGS_FATAL.

◆ insertIfTypeIndexKeyUniqueElseError()

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

Inserts the given key with the given value into the map if an entry with the given key does not yet exist; otherwise an error_message is printed and the program is aborted. Note: The type of key must be std::type_index.

Definition at line 88 of file Algorithm.h.

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

References OGS_FATAL.

◆ int2date()

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

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

Definition at line 42 of file DateTools.cpp.

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

Referenced by DiagramList::readList().

◆ IsFileExisting()

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

◆ isProjectDirectorySet()

bool BaseLib::isProjectDirectorySet ( )

Returns true if the project directory is set.

Definition at line 35 of file FileTools.cpp.

36 {
38 }

References anonymous_namespace{FileTools.cpp}::project_directory_is_set.

◆ joinPaths()

◆ makeConfigTree()

ConfigTreeTopLevel BaseLib::makeConfigTree ( std::string const &  filepath,
bool const  be_ruthless,
std::string const &  toplevel_tag,
const std::vector< std::string > &  patch_files = {} 
)

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.
patch_filesoptional vector of strings with patch file paths.

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

246 {
247  std::string prj_file = filepath;
248  std::stringstream prj_stream;
249  readAndPatchPrj(prj_stream, prj_file, patch_files);
250 
251  ConfigTree::PTree ptree;
252 
253  // note: Trimming whitespace and ignoring comments is crucial in order
254  // for our configuration tree implementation to work!
255  try
256  {
257  read_xml(prj_stream, ptree,
258  boost::property_tree::xml_parser::no_comments |
259  boost::property_tree::xml_parser::trim_whitespace);
260 
261  if (toplevel_tag == "OpenGeoSysProject")
262  {
263  traverse(ptree, fs::path(prj_file).parent_path(), replaceIncludes);
264  }
265  }
266  catch (boost::property_tree::xml_parser_error const& e)
267  {
268  OGS_FATAL("Error while parsing XML file `{:s}' at line {:d}: {:s}.",
269  e.filename(), e.line(), e.message());
270  }
271 
272  DBUG("Project configuration from file '{:s}' read.", filepath);
273 
274  if (auto child = ptree.get_child_optional(toplevel_tag))
275  {
276  return ConfigTreeTopLevel(filepath, be_ruthless, std::move(*child));
277  }
278  OGS_FATAL("Tag <{:s}> has not been found in file `{:s}'.", toplevel_tag,
279  filepath);
280 }
void DBUG(char const *fmt, Args const &... args)
Definition: Logging.h:27
void replaceIncludes([[maybe_unused]] boost::property_tree::ptree const &parent, [[maybe_unused]] boost::property_tree::ptree::path_type const &child_path, boost::property_tree::ptree &child, fs::path const &bench_dir)
void traverse(boost::property_tree::ptree &parent, const fs::path bench_dir, T &method)
void readAndPatchPrj(std::stringstream &prj_stream, std::string &prj_file, std::vector< std::string > patch_files)

References DBUG(), OGS_FATAL, readAndPatchPrj(), replaceIncludes(), and traverse().

Referenced by main(), and GeoLib::IO::BoostXmlGmlInterface::readFile().

◆ makeVectorUnique() [1/2]

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

◆ makeVectorUnique() [2/2]

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

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

Definition at line 219 of file Algorithm.h.

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

◆ operator<<()

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 203 of file Histogram.h.

204 {
205  os << h.getNumberOfBins() << " " << h.getMinimum() << " " << h.getMaximum()
206  << " ";
207  std::copy(h.getBinCounts().begin(), h.getBinCounts().end(),
208  std::ostream_iterator<T>(os, " "));
209  return os << std::endl;
210 }

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

◆ patchStream()

void BaseLib::patchStream ( std::string  patch_file,
std::stringstream &  prj_stream 
)

Definition at line 119 of file ConfigTreeUtil.cpp.

120 {
121  auto patch = xmlParseFile(patch_file.c_str());
122  if (patch == NULL)
123  {
124  OGS_FATAL("Error reading XML diff file {:s}.", patch_file);
125  }
126 
127  auto doc =
128  xmlParseMemory(prj_stream.str().c_str(), prj_stream.str().size());
129  if (doc == NULL)
130  {
131  OGS_FATAL("Error reading project file from memory.");
132  }
133 
134  auto node = xmlDocGetRootElement(patch);
135  int rc = 0;
136  for (node = node ? node->children : NULL; node; node = node->next)
137  {
138  if (node->type != XML_ELEMENT_NODE)
139  {
140  continue;
141  }
142 
143  if (!strcmp(reinterpret_cast<const char*>(node->name), "add"))
144  {
145  rc = xml_patch_add(doc, node);
146  }
147  else if (!strcmp(reinterpret_cast<const char*>(node->name), "replace"))
148  {
149  rc = xml_patch_replace(doc, node);
150  }
151  else if (!strcmp(reinterpret_cast<const char*>(node->name), "remove"))
152  {
153  rc = xml_patch_remove(doc, node);
154  }
155  else
156  {
157  OGS_FATAL(
158  "Error while patching prj file with patch file {:}. Only "
159  "'add', 'replace' and 'remove' elements are allowed! Got an "
160  "element '{:s}' on line {:d}.",
161  patch_file, node->name, node->line);
162  }
163 
164  if (rc)
165  {
166  OGS_FATAL(
167  "Error while patching prj file with patch file {:}. Error in "
168  "element '{:s}' on line {:d}.",
169  patch_file, node->name, node->line);
170  }
171  }
172 
173  xmlChar* xmlbuff;
174  int buffersize;
175  xmlDocDumpMemory(doc, &xmlbuff, &buffersize);
176  prj_stream.str(""); // Empty stream
177  prj_stream << xmlbuff;
178 
179  xmlFree(xmlbuff);
180  xmlFreeDoc(doc);
181  xmlFreeDoc(patch);
182 }

References OGS_FATAL.

Referenced by readAndPatchPrj().

◆ 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(std::vector< T1 * > &array, std::size_t beg, std::size_t end, std::vector< T2 > &perm)
Definition: quicksort.h:83

References quicksort().

◆ quicksort() [2/5]

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

Definition at line 26 of file quicksort.h.

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

Referenced by quicksort(), and GeoLib::Polygon::splitPolygonAtPoint().

◆ quicksort() [3/5]

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

Definition at line 83 of file quicksort.h.

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

◆ quicksort() [4/5]

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

Definition at line 72 of file quicksort.h.

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

References quicksort().

◆ quicksort() [5/5]

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

Definition at line 64 of file quicksort.h.

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

References quicksort().

◆ randomString()

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

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

Definition at line 102 of file StringTools.cpp.

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

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

188 {
189  // Extract base project file path if an xml (patch) file is given as prj
190  // file and it contains the base_file attribute.
191  if (BaseLib::getFileExtension(prj_file) == ".xml")
192  {
193  if (!patch_files.empty())
194  {
195  OGS_FATAL(
196  "It is not allowed to specify additional patch files "
197  "if a patch file was already specified as the "
198  "prj-file.");
199  }
200  auto patch = xmlParseFile(prj_file.c_str());
201  auto node = xmlDocGetRootElement(patch);
202  auto base_file = xmlGetProp(node, (const xmlChar*)"base_file");
203  if (base_file == nullptr)
204  {
205  OGS_FATAL(
206  "Error reading base prj file (base_file attribute) in given "
207  "patch file {:s}.",
208  prj_file);
209  }
210  patch_files = {prj_file};
211  std::stringstream ss;
212  ss << base_file;
213  prj_file = BaseLib::joinPaths(BaseLib::extractPath(prj_file), ss.str());
214  }
215 
216  // read base prj file into stream
217  if (std::ifstream file(prj_file); file)
218  {
219  prj_stream << file.rdbuf();
220  }
221  else
222  {
223  if (!BaseLib::IsFileExisting(prj_file))
224  {
225  ERR("File {:s} does not exist.", prj_file);
226  }
227  DBUG("Stream state flags: {:b}.", file.rdstate());
228  OGS_FATAL("Could not open project file '{:s}' for reading.", prj_file);
229  }
230 
231  // apply xml patches to stream
232  if (!patch_files.empty())
233  {
234  for (const auto& patch_file : patch_files)
235  {
236  patchStream(patch_file, prj_stream);
237  }
238  xmlCleanupParser();
239  }
240 }
void ERR(char const *fmt, Args const &... args)
Definition: Logging.h:42
void patchStream(std::string patch_file, std::stringstream &prj_stream)
std::string extractPath(std::string const &pathname)
Definition: FileTools.cpp:207
bool IsFileExisting(const std::string &strFilename)
Returns true if given file exists.
Definition: FileTools.cpp:43
std::string joinPaths(std::string const &pathA, std::string const &pathB)
Definition: FileTools.cpp:212

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

Referenced by makeConfigTree().

◆ readBinaryArray()

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

Definition at line 97 of file FileTools.h.

98 {
99  std::ifstream in(filename.c_str());
100  if (!in)
101  {
102  ERR("readBinaryArray(): Error while reading from file '{:s}'.",
103  filename);
104  ERR("Could not open file '{:s}' for input.", filename);
105  in.close();
106  return std::vector<T>();
107  }
108 
109  std::vector<T> result;
110  result.reserve(n);
111 
112  for (std::size_t p = 0; in && !in.eof() && p < n; ++p)
113  {
114  result.push_back(BaseLib::readBinaryValue<T>(in));
115  }
116 
117  if (result.size() == n)
118  {
119  return result;
120  }
121 
122  ERR("readBinaryArray(): Error while reading from file '{:s}'.", filename);
123  ERR("Read different number of values. Expected {:d}, got {:d}.",
124  n,
125  result.size());
126 
127  if (!in.eof())
128  {
129  ERR("EOF reached.\n");
130  }
131 
132  return std::vector<T>();
133 }
static const double p

References ERR().

◆ readBinaryValue()

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

Definition at line 89 of file FileTools.h.

90 {
91  T v;
92  in.read(reinterpret_cast<char*>(&v), sizeof(T));
93  return v;
94 }

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

237 {
238  bool const success = fs::remove(fs::path(filename));
239  if (success)
240  {
241  DBUG("Removed '{:s}'", filename);
242  }
243 }

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

246 {
247  for (auto const& file : files)
248  {
249  removeFile(file);
250  }
251 }
void removeFile(std::string const &filename)
Definition: FileTools.cpp:236

References removeFile().

Referenced by main().

◆ reorderVector()

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

Reorder a vector by a given index vector.

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

Definition at line 232 of file Algorithm.h.

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

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

◆ replaceIncludes()

void BaseLib::replaceIncludes ( [[maybe_unused] ] boost::property_tree::ptree const &  parent,
[[maybe_unused] ] boost::property_tree::ptree::path_type const &  child_path,
boost::property_tree::ptree &  child,
fs::path const &  bench_dir 
)

Definition at line 79 of file ConfigTreeUtil.cpp.

84 {
85  using boost::property_tree::ptree;
86  for (auto& [key, tree] : child)
87  {
88  if (key == "include")
89  {
90  auto filename = tree.get<std::string>("<xmlattr>.file");
91  if (auto const filepath = fs::path(filename);
92  filepath.is_relative())
93  {
94  filename = (bench_dir / filepath).string();
95  }
96  INFO("Including {:s} into project file.", filename);
97 
98  ptree include_tree;
99  read_xml(filename, include_tree,
100  boost::property_tree::xml_parser::no_comments |
101  boost::property_tree::xml_parser::trim_whitespace);
102 
103  // Can only insert subtree at child
104  auto& tmp_tree = child.put_child("include", include_tree);
105 
106  // Move subtree above child
107  std::move(tmp_tree.begin(), tmp_tree.end(), back_inserter(child));
108 
109  // Erase child
110  child.erase("include");
111 
112  // There can only be one include under a parent element!
113  break;
114  }
115  }
116 }
void INFO(char const *fmt, Args const &... args)
Definition: Logging.h:32

References INFO().

Referenced by makeConfigTree().

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

53 {
54  boost::replace_all(stringToReplace, searchString, replaceString);
55  return stringToReplace;
56 }
std::string replaceString(const std::string &searchString, const std::string &replaceString, std::string stringToReplace)
Definition: StringTools.cpp:50

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

◆ setConsoleLogLevel()

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

Definition at line 34 of file Logging.cpp.

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

References console, ERR(), and OGS_FATAL.

Referenced by main().

◆ setProjectDirectory()

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

Sets the project directory.

Definition at line 226 of file FileTools.cpp.

227 {
229  {
230  OGS_FATAL("The project directory has already been set.");
231  }
232  project_directory = dir;
234 }

References OGS_FATAL, anonymous_namespace{FileTools.cpp}::project_directory, and anonymous_namespace{FileTools.cpp}::project_directory_is_set.

Referenced by main().

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

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

References trim().

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

◆ splitString() [1/2]

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

Splits a string into a list of strings.

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

Definition at line 38 of file StringTools.cpp.

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

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

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

References MathLib::LinAlg::copy().

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

◆ str2number()

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

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

Parameters
strstring to be converted
Returns
the number

Definition at line 59 of file StringTools.h.

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

◆ 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 }
int date2int(int y, int m, int d)
Definition: DateTools.cpp:26

References date2int().

Referenced by SensorData::readDataFromFile().

◆ substituteKeyword()

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

Definition at line 82 of file FileTools.cpp.

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

References containsKeyword(), and format().

Referenced by constructFormattedFileName().

◆ swapEndianness() [1/2]

double BaseLib::swapEndianness ( double const &  v)

Definition at line 147 of file FileTools.cpp.

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

References MaterialPropertyLib::c.

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 }

References MaterialPropertyLib::c.

◆ to_underlying()

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

Converts an enumeration to its underlying type.

Parameters
eEnumeration value to convert
Returns
The integer value of the underlying type of Enum, converted from e.

https://en.cppreference.com/w/cpp/utility/to_underlying Implementation from Scott Meyers : Modern effective c++ , Item 10 Scoped enums

Definition at line 30 of file cpp23.h.

31 {
32  return static_cast<std::underlying_type_t<E>>(e);
33 }

Referenced by MeshLib::IO::cellTypeOGS2XDMF(), MeshLib::IO::elemOGSTypeToXDMFType(), MeshLib::IO::getPropertyDataTypeSize(), MeshLib::IO::getPropertyDataTypeString(), MeshLib::IO::meshPropertyDatatypeSize(), and MeshLib::IO::meshPropertyDatatypeString().

◆ traverse()

template<typename T >
void BaseLib::traverse ( boost::property_tree::ptree &  parent,
const fs::path  bench_dir,
T &  method 
)

Definition at line 73 of file ConfigTreeUtil.cpp.

75 {
76  traverse_recursive(parent, "", parent, bench_dir, method);
77 }
void traverse_recursive(boost::property_tree::ptree &parent, boost::property_tree::ptree::path_type const &child_path, boost::property_tree::ptree &child, fs::path const &bench_dir, T &method)

References traverse_recursive().

Referenced by makeConfigTree().

◆ traverse_recursive()

template<typename T >
void BaseLib::traverse_recursive ( boost::property_tree::ptree &  parent,
boost::property_tree::ptree::path_type const &  child_path,
boost::property_tree::ptree &  child,
fs::path const &  bench_dir,
T &  method 
)

Definition at line 55 of file ConfigTreeUtil.cpp.

61 {
62  using boost::property_tree::ptree;
63 
64  method(parent, child_path, child, bench_dir);
65  for (auto& [key, tree] : child)
66  {
67  ptree::path_type const cur_path = child_path / ptree::path_type(key);
68  traverse_recursive(child, cur_path, tree, bench_dir, method);
69  }
70 }

Referenced by traverse().

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

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

Referenced by FileIO::FEFLOWMeshInterface::getIndexList(), getValue(), getVariables(), MeshLib::IO::Legacy::MeshIO::loadMeshFromFile(), FileIO::Gocad::parseGocadPropertyMetaData(), FileIO::Gocad::GocadAsciiReader::parseHeader(), FileIO::Gocad::parseName(), FileIO::FEFLOWMeshInterface::readELEMENTALSETS(), FileIO::FEFLOWMeshInterface::readElevation(), BaseLib::IO::readStringListFromFile(), FileIO::FEFLOWGeoInterface::readSuperMesh(), and simplify().

◆ uniquePushBack()

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

Definition at line 245 of file Algorithm.h.

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

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

◆ 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 63 of file FileTools.h.

64 {
65  out.write(reinterpret_cast<const char*>(&val), sizeof(T));
66 }

Referenced by ApplicationUtils::writeProperties().

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

References date2int(), and WARN().

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

Variable Documentation

◆ console

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

Definition at line 29 of file Logging.cpp.

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