OGS 6.2.1-599-g427777a38.dirty.20191113164234
BaseLib Namespace Reference

Detailed Description

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

Basic algorithms and helper functions provided for all other libraries.

Namespaces

 anonymous_namespace{FileTools.cpp}
 
 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 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 >
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 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
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 453 of file ConfigTree.cpp.

References BaseLib::ConfigTree::checkAndInvalidate().

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

454 {
455  conf.checkAndInvalidate();
456 }

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

References BaseLib::ConfigTree::checkAndInvalidate().

459 {
460  if (conf)
461  {
462  conf->checkAndInvalidate();
463  }
464 }

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

467 {
468  if (conf)
469  {
470  conf->checkAndInvalidate();
471  }
472 }

◆ contains()

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

Definition at line 241 of file Algorithm.h.

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

243 {
244  return std::find(container.begin(), container.end(), element) !=
245  container.end();
246 }

◆ containsIf()

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

Definition at line 249 of file Algorithm.h.

Referenced by ProjectData::parseProcesses().

250 {
251  return std::find_if(container.begin(), container.end(), predicate) !=
252  container.end();
253 }

◆ 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::rapidReadStations(), readBinaryArray(), anonymous_namespace{ProjectData.cpp}::readMeshes(), anonymous_namespace{ProjectData.cpp}::readSingleMesh(), 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
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 21 of file TimeInterval.cpp.

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

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

23 {
25  auto const& time_interval_config = config.getConfigSubtree("time_interval");
26 
27  const auto start_time =
29  time_interval_config.getConfigParameter<double>("start");
30 
31  const auto end_time =
33  time_interval_config.getConfigParameter<double>("end");
34 
35  return std::make_unique<BaseLib::TimeInterval>(start_time, end_time);
36 }

◆ 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(), FileIO::Gocad::GocadAsciiReader::readFile(), 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 }
std::string::size_type findLastDot(std::string const &path)
Definition: FileTools.cpp:91
static const double p
std::string::size_type findLastPathSeparator(std::string const &path)
Definition: FileTools.cpp:82

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

References MathLib::LinAlg::copy().

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

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

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

References excludeObjectCopy().

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

◆ 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
std::string::size_type findLastPathSeparator(std::string const &path)
Definition: FileTools.cpp:82

◆ extractBaseNameWithoutExtension()

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

References OGS_FATAL.

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

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

◆ findFirstNotEqualElement()

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

Definition at line 256 of file Algorithm.h.

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

258 {
259  auto const it =
260  std::find_if_not(container.begin(), container.end(),
261  [&element](typename Container::value_type const& e) {
262  return e == element;
263  });
264  return it == container.end() ? boost::none : boost::make_optional(*it);
265 }

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

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

275 {
276  auto const it = std::find(container.begin(), container.end(), element);
277  if (it == container.end())
278  {
279  return std::numeric_limits<std::size_t>::max();
280  }
281  return std::distance(container.begin(), it);
282 }

◆ 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 &  path)

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
std::string::size_type findLastDot(std::string const &path)
Definition: FileTools.cpp:91
static const double p

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

References OGS_FATAL.

Referenced by ProcessLib::createPerProcessData().

181 {
182  auto it = std::find_if(begin(container), end(container), predicate);
183  if (it == end(container))
184  {
185  OGS_FATAL("Could not find element matching the predicate: %s",
186  error_message.c_str());
187  }
188  return *it;
189 }
#define OGS_FATAL(fmt,...)
Definition: Error.h:64

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

References OGS_FATAL, and tostring().

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

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

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

References OGS_FATAL, and tostring().

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

◆ 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 MaterialLib::Solids::MFront::createMFront(), main(), anonymous_namespace{CreateChemicalSolverInterface.cpp}::parseDatabasePath(), and readBinaryArray().

215 {
217  {
218  OGS_FATAL("The project directory has not yet been set.");
219  }
220  return project_directory;
221 }
bool project_directory_is_set
Whether the project directory has already been set.
Definition: FileTools.cpp:28
#define OGS_FATAL(fmt,...)
Definition: Error.h:64
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 103 of file Algorithm.h.

References OGS_FATAL, and tostring().

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

105 {
106  auto const inserted = map.emplace(key, std::forward<Value>(value));
107  if (!inserted.second)
108  { // insertion failed, i.e., key already exists
109  OGS_FATAL("%s Key `%s' already exists.", error_message.c_str(),
110  tostring(key).c_str());
111  }
112 }
std::string const & tostring(std::string const &value)
Definition: StringTools.cpp:92
#define OGS_FATAL(fmt,...)
Definition: Error.h:64

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

References OGS_FATAL, and tostring().

121 {
122  auto value_compare = [&value](typename Map::value_type const& elem) {
123  return value == elem.second;
124  };
125 
126  if (std::find_if(map.cbegin(), map.cend(), value_compare) != map.cend())
127  {
128  OGS_FATAL("%s Value `%s' already exists.", error_message.c_str(),
129  tostring(value).c_str());
130  }
131 
132  auto const inserted = map.emplace(key, std::forward<Value>(value));
133  if (!inserted.second)
134  { // insertion failed, i.e., key already exists
135  OGS_FATAL("%s Key `%s' already exists.", error_message.c_str(),
136  tostring(key).c_str());
137  }
138 }
std::string const & tostring(std::string const &value)
Definition: StringTools.cpp:92
#define OGS_FATAL(fmt,...)
Definition: Error.h:64

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

References OGS_FATAL, and tostring().

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

◆ 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 anonymous_namespace{TestDefinition.cpp}::findVtkdiff(), VtkRaster::findWorldFile(), anonymous_namespace{CreateChemicalSolverInterface.cpp}::parseDatabasePath(), 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::createChemicalSolverInterface< ChemicalSolver::Phreeqc >(), MaterialLib::Solids::MFront::createMFront(), ProcessLib::Output::doOutputNonlinearIteration(), anonymous_namespace{TestDefinition.cpp}::findVtkdiff(), main(), anonymous_namespace{CreateChemicalSolverInterface.cpp}::parseDatabasePath(), 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 51 of file ConfigTreeUtil.cpp.

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

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

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

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

205 {
206  std::sort(v.begin(), v.end(), comp);
207  auto it = std::unique(v.begin(), v.end());
208  v.erase(it, v.end());
209 }

◆ 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::PhreeqcIOData::SurfaceSite::SurfaceSite(), and ChemistryLib::PhreeqcIOData::UserPunch::UserPunch().

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

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

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

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(
34  first1, last1, first2, std::back_inserter(data),
35  [](T1 const& t1, T2 const& t2) { 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 }

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

References quicksort().

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

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

References quicksort().

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

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

References quicksort().

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

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

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

◆ 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:64

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

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

219 {
220  std::vector<ValueType> temp_v(v.size());
221  temp_v.swap(v);
222 
223  for (std::size_t i=0; i<order.size(); i++)
224  {
225  std::swap(v[i], temp_v[order[i]]);
226  }
227 }

◆ 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 }
bool project_directory_is_set
Whether the project directory has already been set.
Definition: FileTools.cpp:28
#define OGS_FATAL(fmt,...)
Definition: Error.h:64
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::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(), 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:37

◆ 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::Gocad::GocadAsciiReader::parseHeader(), FileIO::Gocad::parseName(), 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 &  filename)

truncate a file

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

232 {
233  if (std::find(container.begin(), container.end(), element) ==
234  container.end())
235  {
236  container.push_back(element);
237  }
238 }

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