OGS 6.2.0-405-gb717f6088
BaseLib Namespace Reference

Detailed Description

Build information.

Functionality to build different search length algorithm objects from given config.

Definition of the quicksort function.

File: TimeInterval.cpp

Created on November 27, 2018, 5:06 PM

File: TimeInterval.h

Created on November 26, 2018, 4:44 PM

Basic algorithms and helper functions provided for all other libraries.

File: DirichletBoundaryConditionWithinTimeInterval.h

Created on November 26, 2018, 4:59 PM

File: DeactivatedSubdomain.h

Created on November 29, 2018, 10:50 AM

Namespaces

 anonymous_namespace{FileTools.cpp}
 
 BuildInfo
 
 detail
 
 IO
 

Classes

class  ConfigTree
 
class  ConfigTreeTopLevel
 
struct  Counter
 
class  CPUTime
 Count CPU time. More...
 
class  FileFinder
 
class  GradualSubdivision
 
class  GradualSubdivisionFixedNum
 
class  Histogram
 
class  ISubdivision
 
class  LogogCustomCout
 Custom target for logog output. More...
 
class  LogogSimpleFormatter
 LogogSimpleFormatter strips file name and line number from logog output. See http://johnwbyrd.github.com/logog/customformatting.html for details. More...
 
class  MemWatch
 
class  Range
 Wraps a pair of iterators for use as a range in range-based for-loops. More...
 
class  RunTime
 Count the running time. More...
 
class  TCLAPCustomOutput
 
class  TemplateLogogFormatterSuppressedGCC
 TemplateLogogFormatterSuppressedGCC strips topics given as a template parameter from logog::FormatterGCC. See http://johnwbyrd.github.com/logog/customformatting.html for details. More...
 
class  TimeInterval
 
class  UniformSubdivision
 

Functions

template<typename T >
std::vector< T > excludeObjectCopy (std::vector< T > const &src_vec, std::vector< std::size_t > const &exclude_positions)
 
template<typename T >
void excludeObjectCopy (std::vector< T > const &src_vec, std::vector< std::size_t > const &exclude_positions, std::vector< T > &dest_vec)
 
template<typename InputIt , typename Predicate >
std::iterator_traits< InputIt >::reference findElementOrError (InputIt begin, InputIt end, Predicate predicate, std::string const &error="")
 
template<typename Map , typename Key , typename Value >
void insertIfTypeIndexKeyUniqueElseError (Map &map, Key const &key, Value &&value, std::string const &error_message)
 
template<typename Map , typename Key , typename Value >
void insertIfKeyUniqueElseError (Map &map, Key const &key, Value &&value, std::string const &error_message)
 
template<typename Map , typename Key , typename Value >
void insertIfKeyValueUniqueElseError (Map &map, Key const &key, Value &&value, std::string const &error_message)
 
template<typename Map , typename Key >
Map::mapped_type & getOrError (Map &map, Key const &key, std::string const &error_message)
 
template<typename Map , typename Key >
Map::mapped_type const & getOrError (Map const &map, Key const &key, std::string const &error_message)
 
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 >
boost::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)
 
void checkAndInvalidate (ConfigTree &conf)
 
void checkAndInvalidate (ConfigTree *const conf)
 
void checkAndInvalidate (std::unique_ptr< ConfigTree > const &conf)
 
ConfigTreeTopLevel makeConfigTree (const std::string &filepath, const bool be_ruthless, const std::string &toplevel_tag)
 
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 IsFileExisting (const std::string &strFilename)
 Returns true if given file exists. From http://www.techbytes.ca/techbyte103.html. More...
 
double swapEndianness (double const &v)
 
void truncateFile (std::string const &filename)
 truncate a file More...
 
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 appendPathSeparator (std::string const &path)
 
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 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 Object , typename MethodClass , typename ReturnType , typename... Args>
std::enable_if< std::is_same< MethodClass, typename std::remove_cv< typename std::remove_pointer< typename std::decay< Object >::type >::type >::type >::value, std::function< ReturnType(Args...)> >::type easyBind (ReturnType(MethodClass::*method)(Args...), Object &&obj)
 
template<typename Object >
detail::FunctionTraits< Object >::FunctionType easyBind (Object &&obj)
 
template<typename T >
std::ostream & operator<< (std::ostream &os, const Histogram< T > &h)
 
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 padLeft (std::string const &str, int maxlen, char ch)
 
std::string const & tostring (std::string const &value)
 
std::string format (const char *format_string,...)
 returns printf-like formatted string More...
 
template<typename T >
str2number (const std::string &str)
 
template<typename T >
std::string tostring (T const &value)
 Method for handling conversion to string uniformly across all types and std::string; see std::string overload below. More...
 
std::unique_ptr< TimeIntervalcreateTimeInterval (BaseLib::ConfigTree const &config)
 

Variables

static const char pathSeparator
 

Function Documentation

◆ appendPathSeparator()

std::string BaseLib::appendPathSeparator ( std::string const &  path)

Appends a platform-dependent path separator (/ or ) if missing

Definition at line 186 of file FileTools.cpp.

References BaseLib::anonymous_namespace{FileTools.cpp}::findLastPathSeparator(), and pathSeparator.

Referenced by joinPaths(), and readBinaryArray().

187 {
188  if (findLastPathSeparator(path) == path.length() - 1)
189  {
190  return path;
191  }
192  return path + pathSeparator;
193 }
static const char pathSeparator
Definition: FileTools.cpp:148
static std::string::size_type findLastPathSeparator(std::string const &path)
Definition: FileTools.cpp:82

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

References BaseLib::ConfigTree::checkAndInvalidate().

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

450 {
451  conf.checkAndInvalidate();
452 }

◆ checkAndInvalidate() [2/3]

void BaseLib::checkAndInvalidate ( ConfigTree *const  conf)

Check if conf has been read entirely and invalidate it.

This method can savely be called on nullptr's.

See also
ConfigTree::checkAndInvalidate()

Definition at line 454 of file ConfigTree.cpp.

References BaseLib::ConfigTree::checkAndInvalidate().

455 {
456  if (conf)
457  {
458  conf->checkAndInvalidate();
459  }
460 }

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

463 {
464  if (conf)
465  {
466  conf->checkAndInvalidate();
467  }
468 }

◆ contains()

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

Definition at line 224 of file Algorithm.h.

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

226 {
227  return std::find(container.begin(), container.end(), element) !=
228  container.end();
229 }

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

References extractPath(), BaseLib::anonymous_namespace{FileTools.cpp}::findLastPathSeparator(), and pathSeparator.

Referenced by ProcessLib::SurfaceFluxData::createSurfaceFluxData(), ProjectData::ProjectData(), GeoLib::IO::XmlStnInterface::rapidReadStations(), readBinaryArray(), anonymous_namespace{ProjectData.cpp}::readMeshes(), anonymous_namespace{ProjectData.cpp}::readSingleMesh(), GeoLib::IO::RapidStnInterface::readStations(), and GeoLib::IO::XmlStnInterface::readStations().

157 {
158  // check if file_name already contains a full path
159  auto const pos = findLastPathSeparator(file_name);
160  if (pos != std::string::npos)
161  {
162  return file_name;
163  }
164 
165  if (source.empty())
166  {
167  return file_name;
168  }
169  if (source.back() != pathSeparator)
170  {
171  return BaseLib::extractPath(source + pathSeparator).append(file_name);
172  }
173  return BaseLib::extractPath(source).append(file_name);
174 }
static const char pathSeparator
Definition: FileTools.cpp:148
std::string extractPath(std::string const &pathname)
Definition: FileTools.cpp:176
static std::string::size_type findLastPathSeparator(std::string const &path)
Definition: FileTools.cpp:82

◆ createTimeInterval()

std::unique_ptr< TimeInterval > BaseLib::createTimeInterval ( BaseLib::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 20 of file TimeInterval.cpp.

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

Referenced by ProcessLib::createDeactivatedSubdomain(), and ProcessLib::createDirichletBoundaryConditionWithinTimeInterval().

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 std::make_unique<BaseLib::TimeInterval>(start_time, end_time);
35 }

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

Referenced by strDate2int(), and xmlDate2int().

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 }

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

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

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  WARN("date2String(): month not in [1:12].");
79  rest = rest % (m * 100);
80  int d = rest;
81  if (d < 1 || d > 31)
82  WARN("date2String(): day not in [1:31].");
83 
84  std::string day = std::to_string(d);
85  if (d < 10)
86  {
87  day = "0" + day;
88  }
89  std::string month = std::to_string(m);
90  if (m < 10)
91  {
92  month = "0" + month;
93  }
94  std::string s = std::to_string(y) + "-" + month + "-" + day;
95  return s;
96 }

◆ dropFileExtension()

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

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

Definition at line 97 of file FileTools.cpp.

References BaseLib::anonymous_namespace{FileTools.cpp}::findLastDot(), and BaseLib::anonymous_namespace{FileTools.cpp}::findLastPathSeparator().

Referenced by extractBaseNameWithoutExtension(), VtkRaster::findWorldFile(), main(), readBinaryArray(), MeshLib::IO::readMeshFromFile(), ProcessLib::SurfaceFluxData::save(), writeCsvOutput(), and writeMeshOutput().

98 {
99  // Look for dots in filename.
100  auto const p = findLastDot(filename);
101  if (p == std::string::npos)
102  {
103  return filename;
104  }
105 
106  // Check position of the last path separator.
107  auto const s = findLastPathSeparator(filename);
108  if (s != std::string::npos && p < s)
109  {
110  return filename;
111  }
112 
113  return filename.substr(0, p);
114 }
static std::string::size_type findLastDot(std::string const &path)
Definition: FileTools.cpp:91
static const double p
static std::string::size_type findLastPathSeparator(std::string const &path)
Definition: FileTools.cpp:82

◆ easyBind() [1/2]

template<typename Object , typename MethodClass , typename ReturnType , typename... Args>
std::enable_if< std::is_same< MethodClass, typename std::remove_cv< typename std::remove_pointer< typename std::decay< Object >::type >::type >::type >::value, std::function< ReturnType(Args...)> >::type BaseLib::easyBind ( ReturnType(MethodClass::*)(Args...)  method,
Object &&  obj 
)

Convenience wrapper for std::bind().

This function binds the member function pointer member of class Object to the instance obj of this class and wraps the result in a std::function with matching signature.

The result of this function can be used, e.g., to deduce the signature of the method (which is not possible with the result of std::bind).

Example:

using std::placeholders;
Object some_object;
auto f_bind = std::function<ReturnType(Arg1, Arg2, Arg3>(
std::bind(&Object::methodWithThreeArguments,
std::ref(some_object), _1, _2, _3));
auto f_easy = easyBind(&Object::methodWithThreeArguments, some_object);

In the example the expressions creating f_bind and f_easy are equivalent.

Note
There is one difference between the behaviour of std::bind and the one of easyBind: In easyBind obj is never copied, instead it will be referenced. This is in contrast to the behaviour of std::bind, and has been chosen in order to prevent accidental copies.

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 180 of file Functional.h.

References BaseLib::detail::easyBind_inner().

Referenced by easyBind(), ProcessLib::Process::finishNamedFunctionsInitialization(), ProcessLib::CachedSecondaryVariable::getExtrapolator(), ProcessLib::CachedSecondaryVariable::getNamedFunctions(), ProcessLib::SmallDeformation::SmallDeformationProcess< DisplacementDim >::initializeConcreteProcess(), and ProcessLib::TES::TESProcess::initializeSecondaryVariables().

181 {
182  return detail::easyBind_inner(
183  method, std::forward<Object>(obj),
184  std::make_integer_sequence<int, sizeof...(Args)>{});
185 }
std::function< ReturnType(Args...)> easyBind_inner(ReturnType(MethodClass::*method)(Args...), Object &&obj, std::integer_sequence< int, Indices... >)
Definition: Functional.h:101

◆ easyBind() [2/2]

template<typename Object >
detail::FunctionTraits<Object>::FunctionType BaseLib::easyBind ( Object &&  obj)

Wraps a callable object in a std::function.

This method is provided for convenience since it automatically deduces the correct type of std::function.

Definition at line 207 of file Functional.h.

References easyBind().

208 {
209  return BaseLib::easyBind(&std::decay<Object>::type::operator(),
210  std::forward<Object>(obj));
211 }
std::enable_if< std::is_same< MethodClass, typename std::remove_cv< typename std::remove_pointer< typename std::decay< Object >::type >::type >::type >::value, std::function< ReturnType(Args...)> >::type easyBind(ReturnType(MethodClass::*method)(Args...), Object &&obj)
Definition: Functional.h:180

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

References MathLib::LinAlg::copy().

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

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

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

References excludeObjectCopy().

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

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

References BaseLib::anonymous_namespace{FileTools.cpp}::findLastPathSeparator().

Referenced by OGSFileConverter::convertGLI2GML(), extractBaseNameWithoutExtension(), OGSFileConverter::fileExists(), getFileExtension(), anonymous_namespace{postLIE.cpp}::postPVD(), MeshLib::IO::NodePartitionedMeshReader::readASCII(), MeshLib::IO::NodePartitionedMeshReader::readBinary(), readBinaryArray(), FileIO::Legacy::readGLIFileV4(), and MeshLib::IO::VtuInterface::readVTUFile().

117 {
118  auto const p = findLastPathSeparator(pathname);
119  if (p == std::string::npos)
120  {
121  return pathname;
122  }
123  return pathname.substr(p + 1);
124 }
static const double p
static std::string::size_type findLastPathSeparator(std::string const &path)
Definition: FileTools.cpp:82

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

References BaseLib::anonymous_namespace{FileTools.cpp}::findLastPathSeparator().

Referenced by copyPathToFileName(), main(), anonymous_namespace{postLIE.cpp}::postPVD(), readBinaryArray(), FileIO::Legacy::readGLIFileV4(), MeshLib::IO::VtuInterface::readVTUFile(), FileIO::Legacy::writeAllDataToGLIFileV4(), and FileIO::Legacy::writeGLIFileV4().

177 {
178  auto const pos = findLastPathSeparator(pathname);
179  if (pos == std::string::npos)
180  {
181  return "";
182  }
183  return pathname.substr(0, pos + 1);
184 }
static std::string::size_type findLastPathSeparator(std::string const &path)
Definition: FileTools.cpp:82

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

References OGS_FATAL.

Referenced by MaterialPropertyLib::Phase::component(), ParameterLib::createParameter(), ProcessLib::Output::doOutputAlways(), anonymous_namespace{ProcessVariable.cpp}::findMeshInConfig(), ChemistryLib::operator>>(), ProjectData::parseProcessVariables(), and MaterialPropertyLib::Medium::phase().

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

◆ findFirstNotEqualElement()

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

Definition at line 232 of file Algorithm.h.

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

234 {
235  auto const it =
236  std::find_if_not(container.begin(), container.end(),
237  [&element](typename Container::value_type const& e) {
238  return e == element;
239  });
240  return it == container.end() ? boost::none : boost::make_optional(*it);
241 }

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

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

251 {
252  auto const it = std::find(container.begin(), container.end(), element);
253  if (it == container.end())
254  {
255  return std::numeric_limits<std::size_t>::max();
256  }
257  return std::distance(container.begin(), it);
258 }

◆ format()

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

returns printf-like formatted string

Definition at line 97 of file StringTools.cpp.

Referenced by tostring().

98 {
99  va_list args;
100  va_start(args, format_str);
101  // get the number of chars to write
102  va_list args_tmp;
103  va_copy(args_tmp, args);
104  int char_length = std::vsnprintf(nullptr, 0, format_str, args_tmp);
105  va_end(args_tmp);
106  // allocate buffer and store formatted output there
107  std::vector<char> buffer(char_length + 1); // note +1 for null terminator
108  vsnprintf(buffer.data(), buffer.size(), format_str, args);
109  va_end(args);
110 
111  return std::string(buffer.data());
112 }

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

Referenced by main().

131 {
132  auto const time_t = std::chrono::system_clock::to_time_t(time);
133  char time_str[100];
134  if (std::strftime(time_str, sizeof(time_str), "%Y-%m-%d %H:%M:%S%z",
135  std::localtime(&time_t))) {
136  return time_str;
137  }
138  return "FAILED FORMATTING THE GIVEN TIME POINT.";
139 }

◆ getFileExtension()

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

Extract extension from filename

Definition at line 132 of file FileTools.cpp.

References extractBaseName(), and BaseLib::anonymous_namespace{FileTools.cpp}::findLastDot().

Referenced by VtkVisImageItem::callVTKWriter(), VtkVisPointSetItem::callVTKWriter(), hasFileExtension(), FileIO::SwmmInterface::isSwmmInputFile(), main(), readBinaryArray(), FileIO::readGeometryFromFile(), FileIO::AsciiRasterInterface::readRaster(), FileIO::TetGenInterface::readTetGenGeometry(), MeshLib::IO::VtuInterface::readVTUFile(), writeCsvOutput(), FileIO::writeGeometryToFile(), and writeMeshOutput().

133 {
134  const std::string str = extractBaseName(path);
135  auto const p = findLastDot(str);
136  if (p == std::string::npos)
137  {
138  return std::string();
139  }
140  return str.substr(p + 1);
141 }
std::string extractBaseName(std::string const &pathname)
Definition: FileTools.cpp:116
static std::string::size_type findLastDot(std::string const &path)
Definition: FileTools.cpp:91
static const double p

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

References OGS_FATAL, and tostring().

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

149 {
150  auto it = map.find(key);
151  if (it == map.end())
152  {
153  OGS_FATAL("%s Key `%s' does not exist.", error_message.c_str(),
154  tostring(key).c_str());
155  }
156 
157  return it->second;
158 }
std::string const & tostring(std::string const &value)
Definition: StringTools.cpp:92
#define OGS_FATAL(fmt,...)
Definition: Error.h:63

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

References OGS_FATAL, and tostring().

163 {
164  auto it = map.find(key);
165  if (it == map.end())
166  {
167  OGS_FATAL("%s Key `%s' does not exist.", error_message.c_str(),
168  tostring(key).c_str());
169  }
170 
171  return it->second;
172 }
std::string const & tostring(std::string const &value)
Definition: StringTools.cpp:92
#define OGS_FATAL(fmt,...)
Definition: Error.h:63

◆ getProjectDirectory()

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

Returns the directory where the prj file resides.

Definition at line 214 of file FileTools.cpp.

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

Referenced by ChemistryLib::createPhreeqcIO(), main(), and readBinaryArray().

215 {
217  {
218  OGS_FATAL("The project directory has not yet been set.");
219  }
220  return project_directory;
221 }
static bool project_directory_is_set
Whether the project directory has already been set.
Definition: FileTools.cpp:28
#define OGS_FATAL(fmt,...)
Definition: Error.h:63
static std::string project_directory
The directory where the prj file resides.
Definition: FileTools.cpp:25

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

References getFileExtension().

Referenced by main(), readBinaryArray(), MeshLib::IO::readMeshFromFileSerial(), and MeshLib::IO::writeMeshToFile().

144 {
145  return boost::iequals(extension, getFileExtension(filename));
146 }
std::string getFileExtension(const std::string &path)
Definition: FileTools.cpp:132

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

References OGS_FATAL, and tostring().

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

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("%s Key `%s' already exists.", error_message.c_str(),
111  tostring(key).c_str());
112  }
113 }
std::string const & tostring(std::string const &value)
Definition: StringTools.cpp:92
#define OGS_FATAL(fmt,...)
Definition: Error.h:63

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

References OGS_FATAL, and tostring().

122 {
123  auto value_compare = [&value](typename Map::value_type const& elem) {
124  return value == elem.second;
125  };
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.c_str(),
130  tostring(value).c_str());
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.c_str(),
137  tostring(key).c_str());
138  }
139 }
std::string const & tostring(std::string const &value)
Definition: StringTools.cpp:92
#define OGS_FATAL(fmt,...)
Definition: Error.h:63

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

References OGS_FATAL, and tostring().

89 {
90  auto const inserted = map.emplace(key, std::forward<Value>(value));
91  if (!inserted.second)
92  { // insertion failed, i.e., key already exists
93  OGS_FATAL("%s Key `%s' already exists.", error_message.c_str(),
94  tostring(key.hash_code()).c_str());
95  }
96 }
std::string const & tostring(std::string const &value)
Definition: StringTools.cpp:92
#define OGS_FATAL(fmt,...)
Definition: Error.h:63

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

Referenced by DiagramList::readList().

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 }

◆ IsFileExisting()

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

Returns true if given file exists. From http://www.techbytes.ca/techbyte103.html.

Returns true if given file exists. From http://www.techbytes.ca/techbyte103.html

Parameters
strFilenamethe file name

Definition at line 36 of file FileTools.cpp.

Referenced by ChemistryLib::createPhreeqcIO(), anonymous_namespace{TestDefinition.cpp}::findVtkdiff(), VtkRaster::findWorldFile(), MeshLib::IO::NodePartitionedMeshReader::read(), and MeshLib::IO::VtuInterface::readVTUFile().

37 {
38  struct stat buffer {};
39  return (stat (strFilename.c_str(), &buffer) == 0);
40 }

◆ joinPaths()

std::string BaseLib::joinPaths ( std::string const &  pathA,
std::string const &  pathB 
)

Concat two paths. Does not check for validity.

Definition at line 195 of file FileTools.cpp.

References appendPathSeparator(), and pathSeparator.

Referenced by ProcessLib::Output::addProcess(), ChemistryLib::createPhreeqcIO(), ProcessLib::Output::doOutputNonlinearIteration(), anonymous_namespace{TestDefinition.cpp}::findVtkdiff(), main(), anonymous_namespace{postLIE.cpp}::postPVD(), readBinaryArray(), MeshLib::IO::VtuInterface::readVTUFile(), and ApplicationsLib::TestDefinition::TestDefinition().

196 {
197  if (pathA.empty())
198  {
199  return pathB;
200  }
201 
202  if (pathB.empty())
203  {
204  return pathA;
205  }
206 
207  if (pathB.front() == pathSeparator) {
208  auto const tmpB = pathB.substr(1);
209  return appendPathSeparator(pathA) + tmpB;
210  }
211  return appendPathSeparator(pathA) + pathB;
212 }
static const char pathSeparator
Definition: FileTools.cpp:148
std::string appendPathSeparator(std::string const &path)
Definition: FileTools.cpp:186

◆ makeConfigTree()

ConfigTreeTopLevel BaseLib::makeConfigTree ( std::string const &  filepath,
bool const  be_ruthless,
std::string const &  toplevel_tag 
)

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.

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

References BaseLib::ConfigTreeTopLevel::ConfigTreeTopLevel(), and OGS_FATAL.

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

52 {
53  ConfigTree::PTree ptree;
54 
55  // note: Trimming whitespace and ignoring comments is crucial in order
56  // for our configuration tree implementation to work!
57  try
58  {
59  read_xml(filepath, ptree,
60  boost::property_tree::xml_parser::no_comments |
61  boost::property_tree::xml_parser::trim_whitespace);
62  }
63  catch (boost::property_tree::xml_parser_error const& e)
64  {
65  OGS_FATAL("Error while parsing XML file `%s' at line %lu: %s.",
66  e.filename().c_str(), e.line(), e.message().c_str());
67  }
68 
69  DBUG("Project configuration from file '%s' read.", filepath.c_str());
70 
71  if (auto child = ptree.get_child_optional(toplevel_tag)) {
72  return ConfigTreeTopLevel(filepath, be_ruthless, std::move(*child));
73  }
74  OGS_FATAL("Tag <%s> has not been found in file `%s'.", toplevel_tag.c_str(),
75  filepath.c_str());
76 }
#define OGS_FATAL(fmt,...)
Definition: Error.h:63

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

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

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

References MathLib::LinAlg::copy().

Referenced by ChemistryLib::EquilibriumPhase::EquilibriumPhase().

197 {
198  os << h.getNumberOfBins() << " "
199  << h.getMinimum() << " "
200  << h.getMaximum() << " ";
201  std::copy(h.getBinCounts().begin(), h.getBinCounts().end(),
202  std::ostream_iterator<T>(os, " "));
203  return os << std::endl;
204 }
void copy(MatrixOrVector const &x, MatrixOrVector &y)
Copies x to y.
Definition: LinAlg.h:36

◆ padLeft()

std::string BaseLib::padLeft ( std::string const &  str,
int  maxlen,
char  ch = ' ' 
)

Returns the string which is right aligned with padding on the left.

Definition at line 85 of file StringTools.cpp.

Referenced by str2number().

86 {
87  std::stringstream ss(str);
88  ss << std::right << std::setw(maxlen) << std::setfill(ch) << str;
89  return ss.str();
90 }

◆ quicksort() [1/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 25 of file quicksort.h.

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

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

◆ quicksort() [2/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 51 of file quicksort.h.

References quicksort().

52 {
53  using T1 = typename std::iterator_traits<It1>::value_type;
54  using T2 = typename std::iterator_traits<It2>::value_type;
55 
56  quicksort(first1, last1, first2,
57  [](std::pair<T1, T2> const& a, std::pair<T1, T2> const& b) {
58  return a.first < b.first;
59  });
60 }
void quicksort(std::vector< T1 *> &array, std::size_t beg, std::size_t end, std::vector< T2 > &perm)
Definition: quicksort.h:82

◆ quicksort() [3/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.

References quicksort().

65 {
66  assert(beg <= end);
67 
68  quicksort(array + beg, array + end, perm + beg);
69 }
void quicksort(std::vector< T1 *> &array, std::size_t beg, std::size_t end, std::vector< T2 > &perm)
Definition: quicksort.h:82

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

References quicksort().

73 {
74  assert (beg<=end);
75  assert (end<=array.size());
76  assert (perm.size()==array.size());
77 
78  quicksort(array.data(), beg, end, perm.data());
79 }
void quicksort(std::vector< T1 *> &array, std::size_t beg, std::size_t end, std::vector< T2 > &perm)
Definition: quicksort.h:82

◆ quicksort() [5/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 82 of file quicksort.h.

83 {
84  assert (beg<=end);
85  assert (end<=array.size());
86  assert (perm.size()==array.size());
87 
88  // Zip input arrays.
89  std::vector<std::pair<T1*, T2>> data;
90  data.reserve(end-beg);
91  std::transform(array.begin()+beg, array.begin()+end, perm.begin()+beg,
92  std::back_inserter(data),
93  [](T1* const& t1, T2 const& t2)
94  {
95  return std::make_pair(t1, t2);
96  });
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  {
102  return (*a.first < *b.first);
103  });
104 
105  // Unzip sorted data.
106  for (std::size_t i = 0; i < data.size(); i++)
107  {
108  array[beg+i] = data[i].first;
109  perm[beg+i] = data[i].second;
110  }
111 }

◆ readBinaryArray()

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

Definition at line 74 of file FileTools.h.

References appendPathSeparator(), copyPathToFileName(), dropFileExtension(), extractBaseName(), extractBaseNameWithoutExtension(), extractPath(), getFileExtension(), getProjectDirectory(), hasFileExtension(), joinPaths(), removeFiles(), setProjectDirectory(), and truncateFile().

75 {
76  std::ifstream in(filename.c_str());
77  if (!in) {
78  ERR("readBinaryArray(): Error while reading from file '%s'.",
79  filename.c_str());
80  ERR("Could not open file '%s' for input.", filename.c_str());
81  in.close();
82  return std::vector<T>();
83  }
84 
85  std::vector<T> result;
86  result.reserve(n);
87 
88  for (std::size_t p = 0; in && !in.eof() && p < n; ++p)
89  {
90  result.push_back(BaseLib::readBinaryValue<T>(in));
91  }
92 
93  if (result.size() == n)
94  {
95  return result;
96  }
97 
98  ERR("readBinaryArray(): Error while reading from file '%s'.",
99  filename.c_str());
100  ERR("Read different number of values. Expected %d, got %d.", n, result.size());
101 
102  if (!in.eof())
103  ERR("EOF reached.\n");
104 
105  return std::vector<T>();
106 }
static const double p

◆ readBinaryValue()

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

Definition at line 66 of file FileTools.h.

67 {
68  T v;
69  in.read(reinterpret_cast<char*>(&v), sizeof(T));
70  return v;
71 }

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

References OGS_FATAL.

Referenced by main(), and readBinaryArray().

234 {
235  for (auto const& file : files)
236  {
237  int const success = std::remove(file.c_str());
238  if (success == 0)
239  {
240  DBUG("Removed '%s'", file.c_str());
241  }
242  else
243  {
244  if (errno == ENOENT) // File does not exists
245  {
246  continue;
247  }
248  ERR("Removing file '%s' failed with error %d.", file.c_str(),
249  errno);
250  std::perror("Error: ");
251  OGS_FATAL("Unrecoverable error happened while removing a file.");
252  }
253  }
254 }
#define OGS_FATAL(fmt,...)
Definition: Error.h:63

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

Referenced by ProcessLib::LiquidFlow::createLiquidFlowMaterialProperties(), MaterialLib::PorousMedium::createPorousMediaProperties(), ProcessLib::RichardsComponentTransport::createPorousMediaProperties(), ProcessLib::RichardsFlow::createRichardsFlowMaterialProperties(), MaterialLib::TwoPhaseFlowWithPP::createTwoPhaseFlowMaterialProperties(), ProcessLib::TwoPhaseFlowWithPrho::createTwoPhaseFlowPrhoMaterialProperties(), and ProcessLib::TwoPhaseFlowWithPP::createTwoPhaseFlowWithPPMaterialProperties().

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

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

Referenced by GeoLib::StationBorehole::addLayer(), GeoLib::StationBorehole::createStation(), GeoLib::Station::createStation(), FileIO::FEFLOWMeshInterface::getIndexList(), FileIO::AsciiRasterInterface::getRasterFromASCFile(), FileIO::AsciiRasterInterface::getRasterFromSurferFile(), FileIO::AsciiRasterInterface::readASCHeader(), and DiagramList::readList().

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

◆ setProjectDirectory()

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

Sets the project directory.

Definition at line 223 of file FileTools.cpp.

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

Referenced by main(), and readBinaryArray().

224 {
226  {
227  OGS_FATAL("The project directory has already been set.");
228  }
229  project_directory = dir;
231 }
static bool project_directory_is_set
Whether the project directory has already been set.
Definition: FileTools.cpp:28
#define OGS_FATAL(fmt,...)
Definition: Error.h:63
static std::string project_directory
The directory where the prj file resides.
Definition: FileTools.cpp:25

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

References trim().

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

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

◆ splitString() [1/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 splitted
Returns
Vector of strings

Definition at line 28 of file StringTools.cpp.

References MathLib::LinAlg::copy().

Referenced by FileIO::SwmmInterface::addPointElevation(), FileIO::SwmmInterface::addRainGaugeTimeSeriesLocations(), GeoLib::StationBorehole::createStation(), GeoLib::Station::createStation(), FileIO::CsvInterface::findColumn(), FileIO::CsvInterface::getColumnNames(), FileIO::FEFLOWMeshInterface::getIndexList(), FileIO::TetGenInterface::getNFacets(), FileIO::TetGenInterface::parseNodesFileHeader(), FileIO::TetGenInterface::parseSmeshFacets(), FileIO::GMSInterface::readBoreholesFromGMS(), FileIO::CsvInterface::readColumn(), FileIO::SwmmInterface::readCoordinates(), 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(), GeoLib::StationBorehole::readStratigraphyFile(), and FileIO::SwmmInterface::readSubcatchments().

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 }
void copy(MatrixOrVector const &x, MatrixOrVector &y)
Copies x to y.
Definition: LinAlg.h:36

◆ splitString() [2/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 splitted
delimCharacter indicating that the string should be splitted
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 }

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

References padLeft(), simplify(), and trim().

56 {
57  std::stringstream strs (str, std::stringstream::in | std::stringstream::out);
58  T v;
59  strs >> v;
60  return v;
61 }

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

References date2int().

Referenced by GeoLib::StationBorehole::createStation(), and SensorData::readDataFromFile().

99 {
100  std::string str(s);
101  if (s.length() > 10)
102  {
103  str = s.substr(0, 10);
104  }
105  std::size_t sep ( str.find('.',0) );
106  int d ( atoi(str.substr(0, sep).c_str()) );
107  std::size_t sep2 ( str.find('.', sep + 1) );
108  int m ( atoi(str.substr(sep + 1,sep2 - (sep + 1)).c_str()) );
109  int y ( atoi(str.substr(sep2 + 1, s.length() - (sep2 + 1)).c_str()) );
110  return date2int(y, m, d);
111 }
int date2int(int y, int m, int d)
Definition: DateTools.cpp:26

◆ swapEndianness() [1/2]

double BaseLib::swapEndianness ( double const &  v)

Definition at line 42 of file FileTools.cpp.

References anonymous_namespace{Density100MPa.cpp}::c.

Referenced by FileIO::Gocad::GocadSGridReader::readElementPropertiesBinary(), FileIO::Gocad::GocadSGridReader::readNodesBinary(), and swapEndianness().

43 {
44  union
45  {
46  double v;
47  char c[sizeof(double)];
48  } a {}, b {};
49 
50  a.v = v;
51  for (unsigned short i = 0; i < sizeof(double) / 2; i++)
52  {
53  b.c[i] = a.c[sizeof(double) / 2 - i - 1];
54  }
55 
56  for (unsigned short i = sizeof(double) / 2; i < sizeof(double); i++)
57  {
58  b.c[i] = a.c[sizeof(double) + sizeof(double) / 2 - i - 1];
59  }
60 
61  return b.v;
62 }

◆ swapEndianness() [2/2]

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

Definition at line 45 of file FileTools.h.

References anonymous_namespace{Density100MPa.cpp}::c, and swapEndianness().

46 {
47  union
48  {
49  T v;
50  char c[sizeof(T)];
51  } a, b;
52 
53  a.v = v;
54  for (unsigned short i = 0; i < sizeof(T); i++)
55  {
56  b.c[i] = a.c[sizeof(T) - i - 1];
57  }
58 
59  return b.v;
60 }

◆ tostring() [1/2]

template<typename T >
std::string BaseLib::tostring ( T const &  value)

Method for handling conversion to string uniformly across all types and std::string; see std::string overload below.

Definition at line 82 of file StringTools.h.

References format(), and tostring().

83 {
84  return std::to_string(value);
85 }

◆ tostring() [2/2]

std::string const & BaseLib::tostring ( std::string const &  value)

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

Referenced by getOrError(), insertIfKeyUniqueElseError(), insertIfKeyValueUniqueElseError(), insertIfTypeIndexKeyUniqueElseError(), tostring(), and writeMeshOutput().

93 {
94  return value;
95 }

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

Referenced by FileIO::FEFLOWMeshInterface::getIndexList(), getValue(), getVariables(), MeshLib::IO::Legacy::MeshIO::loadMeshFromFile(), FileIO::Gocad::parseGocadPropertyMetaData(), FileIO::FEFLOWMeshInterface::readELEMENTALSETS(), FileIO::FEFLOWMeshInterface::readElevation(), FileIO::GMSInterface::readSoilIDfromFile(), FileIO::FEFLOWGeoInterface::readSuperMesh(), simplify(), and str2number().

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 }

◆ truncateFile()

void BaseLib::truncateFile ( std::string const &  file_path)

truncate a file

Parameters
file_paththe file name

Definition at line 67 of file FileTools.cpp.

Referenced by readBinaryArray().

68 {
69  std::ofstream ofs(filename.c_str(), std::ios_base::trunc);
70  ofs.close();
71 }

◆ uniquePushBack()

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

Definition at line 213 of file Algorithm.h.

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

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

Referenced by ApplicationUtils::writePropertiesBinary().

40 {
41  out.write(reinterpret_cast<const char*>(&val), sizeof(T));
42 }

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

References date2int().

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

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

Variable Documentation

◆ pathSeparator

const char BaseLib::pathSeparator
static
Initial value:
=
'/'

Definition at line 148 of file FileTools.cpp.

Referenced by appendPathSeparator(), copyPathToFileName(), and joinPaths().