MeteoIODoc  MeteoIODoc-2.9.0
IOUtils.h
Go to the documentation of this file.
1 /***********************************************************************************/
2 /* Copyright 2009 WSL Institute for Snow and Avalanche Research SLF-DAVOS */
3 /***********************************************************************************/
4 /* This file is part of MeteoIO.
5  MeteoIO is free software: you can redistribute it and/or modify
6  it under the terms of the GNU Lesser General Public License as published by
7  the Free Software Foundation, either version 3 of the License, or
8  (at your option) any later version.
9 
10  MeteoIO is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public License
16  along with MeteoIO. If not, see <http://www.gnu.org/licenses/>.
17 */
18 #ifndef IOUTILS_H
19 #define IOUTILS_H
20 
21 #include <iostream>
22 #include <string>
23 #include <map>
24 #include <vector>
25 #include <set>
26 #include <cstdlib>
27 #include <limits>
28 #include <cmath>
29 
32 #include <meteoio/IOExceptions.h>
34 
35 namespace mio {
36 
37 #ifdef _MSC_VER
38 double round(const double& x);
39 #endif
40 
41 class MeteoData;
42 class Coords;
43 class Config;
44 
50 std::string getLibVersion(const bool& short_version=false);
51 
52 namespace IOUtils {
54  raw = 1,
55  filtered = 1 << 1,
56  resampled = 1 << 2,
57  generated = 1 << 3,
58  num_of_levels = 1 << 4
59  };
60 
63  STD,
69  };
70 
72  const double nodata = -999.0;
73  const unsigned int unodata = static_cast<unsigned int>(-1);
74  const int inodata = -999;
75  const short int snodata = -999;
76  const char cnodata = std::numeric_limits<char>::max();
77  const size_t npos = static_cast<size_t>(-1);
78 
79  const double grid_epsilon = 5.;
80  const double lon_epsilon = grid_epsilon / Cst::earth_R0 * Cst::to_deg;
81  const double lat_epsilon = lon_epsilon;
82 
83  inline double C_TO_K(const double& T) {return ((T==nodata)? T : T + Cst::t_water_freezing_pt);}
84  inline double K_TO_C(const double& T) {return ((T==nodata)? T : T - Cst::t_water_freezing_pt);}
85 
93  inline double UV_TO_DW(const double& U, const double& V) {return ((U==nodata || V==nodata)? nodata : fmod(atan2(U, V) * Cst::to_deg + 180., 360.));}
94 
101  inline double VWDW_TO_U(const double& VW, const double& DW) {return ((VW==nodata || DW==nodata)? nodata : (- VW * sin(DW*Cst::to_rad)));}
102 
109  inline double VWDW_TO_V(const double& VW, const double& DW) {return ((VW==nodata || DW==nodata)? nodata : (- VW * cos(DW*Cst::to_rad)));}
110 
118  inline bool checkEpsilonEquality(const double& val1, const double& val2, const double& epsilon) {return (fabs(val1-val2) < epsilon);}
119 
129  size_t seek(const Date& soughtdate, const std::vector<MeteoData>& vecM, const bool& exactmatch=true);
130 
136  double bearing_to_angle(const double& bearing);
142  double angle_to_bearing(const double& angle);
148  double bearing(std::string bearing_str);
154  std::string bearing(double bearing);
155 
161  std::string getLogName();
162 
167  std::string getHostName();
168 
173  std::string getDomainName();
174 
179  void trim(std::string &s);
180 
186  std::string trim(const std::string &s);
187 
188  void stripComments(std::string& str);
189 
197  void replace_all(std::string &input, const std::string& search, const std::string& format);
198 
203  void removeDuplicateWhitespaces(std::string& line);
204 
210  void replaceWhitespaces(std::string& line, const char& rep = '\0');
211 
217  void replaceInvalidChars(std::string& line, const char& rep = '\0');
218 
223  void removeQuotes(std::string& line);
224 
233  void cleanFieldName(std::string& field, const bool& clean_whitespaces = true, const char& rep = '-');
234 
242  size_t count(const std::string &input, const std::string& search);
243 
252  size_t FNV_hash(const std::string& text);
253 
263  bool readKeyValuePair(const std::string& in_line, const std::string& delimiter,
264  std::string &key, std::string &value, const bool& setToUpperCase=false);
265 
266  void toUpper(std::string& str);
267  std::string strToUpper(std::string str);
268  void toLower(std::string& str);
269  std::string strToLower(std::string str);
270  bool isNumeric(std::string input, const unsigned int& nBase=10);
271  size_t readLineToVec(const std::string& line_in, std::vector<double>& vec_data);
272  size_t readLineToSet(const std::string& line_in, std::set<std::string>& setString);
273  size_t readLineToVec(const std::string& line_in, std::vector<std::string>& vecString);
274  size_t readLineToVec(const std::string& line_in, std::vector<std::string>& vecString, const char& delim);
275  size_t readLineToVec(const std::string& line_in, std::vector<double>& vecRet, const char& delim);
276 
277  template <class T> std::string toString(const T& t) {
278  std::ostringstream os;
279  os << t;
280  return os.str();
281  }
282 
292  template <class T> bool convertString(T& t, std::string str, std::ios_base& (*f)(std::ios_base&) = std::dec) {
293  trim(str); //delete trailing and leading whitespaces and tabs
294  if (str.empty()) {
295  t = static_cast<T> (nodata);
296  return true;
297  } else {
298  std::istringstream iss(str);
299  iss.setf(std::ios::fixed);
300  iss.precision(std::numeric_limits<double>::digits10); //try to read values with maximum precision
301  iss >> f >> t; //Convert first part of stream with the formatter (e.g. std::dec, std::oct)
302  if (iss.fail()) {
303  //Conversion failed
304  return false;
305  }
306  std::string tmp;
307  getline(iss, tmp); //get rest of line, if any
308  trim(tmp);
309  if (!tmp.empty() && tmp[0] != '#' && tmp[0] != ';') {
310  //if line holds more than one value it's invalid
311  return false;
312  }
313  return true;
314  }
315  }
316  // fully specialized template functions (implementation must not be in header)
317  template<> bool convertString<double>(double& t, std::string str, std::ios_base& (*f)(std::ios_base&));
318  template<> bool convertString<std::string>(std::string& t, std::string str, std::ios_base& (*f)(std::ios_base&));
319  template<> bool convertString<bool>(bool& t, std::string str, std::ios_base& (*f)(std::ios_base&));
320  template<> bool convertString<char>(char& t, std::string str, std::ios_base& (*f)(std::ios_base&));
321  template<> bool convertString<unsigned int>(unsigned int& t, std::string str, std::ios_base& (*f)(std::ios_base&));
322  template<> bool convertString<Coords>(Coords& t, std::string str, std::ios_base& (*f)(std::ios_base&));
323 
324  bool convertString(Date& t, std::string str, const double& time_zone, std::ios_base& (*f)(std::ios_base&) = std::dec);
325 
334  template <class T> void getValueForKey(const std::map<std::string,std::string>& properties,
335  const std::string& key, T& t, const ThrowOptions& options=IOUtils::dothrow) {
336  if (key.empty() && options!=IOUtils::nothrow)
337  throw InvalidArgumentException("Empty key", AT);
338 
339  const std::map<std::string, std::string>::const_iterator it( properties.find(key) );
340  if (it == properties.end()){
341  if (options == IOUtils::nothrow)
342  return;
343  else
344  throw UnknownValueException("No value for key " + key, AT);
345  }
346  const std::string& value = it->second;
347 
348  if (!convertString<T>(t, value, std::dec) && options!=IOUtils::nothrow) {
349  std::cerr << "[E] When reading \"" << key << "\" = \"" << t << "\"\n";
350  throw ConversionFailedException(value, AT);
351  }
352  }
353 
362  template <class T> void getValueForKey(const std::map<std::string,std::string>& properties,
363  const std::string& key, std::vector<T>& vecT, const ThrowOptions& options=IOUtils::dothrow)
364  {
365  if (key.empty() && options!=IOUtils::nothrow)
366  throw InvalidArgumentException("Empty key", AT);
367 
368  const std::map<std::string, std::string>::const_iterator it( properties.find(key) );
369  if (it == properties.end()) {
370  if (options == IOUtils::nothrow) {
371  return;
372  } else {
373  throw UnknownValueException("No value for key " + key, AT);
374  }
375  }
376  const std::string& value = it->second;
377 
378  //split value string
379  std::vector<std::string> vecUnconvertedValues;
380  const size_t counter = readLineToVec(value, vecUnconvertedValues);
381  vecT.resize( counter );
382  for (size_t ii=0; ii<counter; ii++){
383  T myvar;
384  if (!convertString<T>(myvar, vecUnconvertedValues.at(ii), std::dec) && options!=IOUtils::nothrow){
385  std::cerr << "[E] When reading \"" << key << "\" = \"" << myvar << "\"\n";
386  throw ConversionFailedException(vecUnconvertedValues.at(ii), AT);
387  }
388  vecT[ii] = myvar;
389  }
390  }
391 
399  template <class T> T standardizeNodata(const T& value, const double& plugin_nodata) {
400  if (value==plugin_nodata) return static_cast<T> (nodata);
401  else return value;
402  }
403 
411  template <class T> static void parseArg(const std::pair< std::string, std::string>& arg, const std::string& algo, T& val) {
412  if (!IOUtils::convertString(val, arg.second))
413  throw InvalidArgumentException("Can not parse argument '"+arg.first+"::"+arg.second+"' for " + algo, AT);
414  }
415 
425  void getProjectionParameters(const Config& cfg, std::string& coordin, std::string& coordinparam,
426  std::string& coordout, std::string& coordoutparam);
427 
435  void getProjectionParameters(const Config& cfg, std::string& coordin, std::string& coordinparam);
436 
443  void getTimeZoneParameters(const Config& cfg, double& tz_in, double& tz_out);
444 
450  double unitsPrefix(const char& prefix);
451 
460  double unitsConversion(const double& val, std::string unitIn, std::string unitOut);
461 } //end namespace IOUtils
462 
463 } //end namespace mio
464 
465 #endif
double angle_to_bearing(const double &angle)
Converts a trigonometric angle to a compass bearing.
Definition: IOUtils.cc:70
size_t readLineToVec(const std::string &line_in, std::vector< double > &vec_data)
Definition: IOUtils.cc:347
double VWDW_TO_U(const double &VW, const double &DW)
From wind speed and direction to u component (west-to-east)
Definition: IOUtils.h:101
bool isNumeric(std::string str, const unsigned int &nBase)
Definition: IOUtils.cc:258
const int inodata
Definition: IOUtils.h:74
ThrowOptions
Definition: IOUtils.h:71
bool convertString(Date &t, std::string str, const double &time_zone, std::ios_base &(*f)(std::ios_base &))
Convert a string to a date (template specialization of convertString)
Definition: IOUtils.cc:581
double UV_TO_DW(const double &U, const double &V)
From wind speed components (u,v) to wind direction, following standard meteorological definitions: U ...
Definition: IOUtils.h:93
OperationMode
Keywords for mode of operation. Please keep all the GRID_xxx last!
Definition: IOUtils.h:62
Definition: IOUtils.h:71
double K_TO_C(const double &T)
Definition: IOUtils.h:84
void replace_all(std::string &input, const std::string &search, const std::string &format)
Replace a substring within a given string by another one.
Definition: IOUtils.cc:157
const double to_deg
Definition: Meteoconst.h:80
extract all grid points from a provided grid
Definition: IOUtils.h:67
void toLower(std::string &str)
Definition: IOUtils.cc:242
Definition: Config.cc:28
std::string getDomainName()
Retrieve the domain name of the computer running the binary.
Definition: IOUtils.cc:335
const double to_rad
Definition: Meteoconst.h:79
double unitsPrefix(const char &prefix)
Convert a textual representation of a unit prefix (like &#39;m&#39; or &#39;G&#39;) to multiplying factor...
Definition: IOUtils.cc:812
std::string strToLower(std::string str)
Definition: IOUtils.cc:253
thrown when encountered an unexpected value (e.g. unknown name or key)
Definition: IOExceptions.h:142
extract virtual stations as specified in the ini file
Definition: IOUtils.h:64
void replaceInvalidChars(std::string &line, const char &rep)
Replaces invalid characters with a single character or removes them.
Definition: IOUtils.cc:189
void getTimeZoneParameters(const Config &cfg, double &tz_in, double &tz_out)
A function that parses a Config object for the time_zone keyword and returns the timezone.
Definition: IOUtils.cc:748
double unitsConversion(const double &val, std::string unitIn, std::string unitOut)
Performs simple unit conversion (supports temperature, prefixes and exponents) NOTE "composite" units...
Definition: IOUtils.cc:837
bool readKeyValuePair(const std::string &in_line, const std::string &delimiter, std::string &key, std::string &value, const bool &setToUpperCase)
read a string line, parse it and save it into a map object, that is passed by reference ...
Definition: IOUtils.cc:278
Definition: IOUtils.h:58
bool convertString< char >(char &t, std::string str, std::ios_base &(*f)(std::ios_base &))
Definition: IOUtils.cc:523
bool convertString< Coords >(Coords &t, std::string str, std::ios_base &(*f)(std::ios_base &))
Definition: IOUtils.cc:716
Definition: IOUtils.h:56
Definition: IOUtils.h:57
T standardizeNodata(const T &value, const double &plugin_nodata)
Standardize a given value to use MeteoIO&#39;s internal nodata value (if applicable)
Definition: IOUtils.h:399
A class to handle geographic coordinate systems. This class offers an easy way to transparently conve...
Definition: Coords.h:81
void getProjectionParameters(const Config &cfg, std::string &coordin, std::string &coordinparam, std::string &coordout, std::string &coordoutparam)
A function that parses a Config object for COORSYS, COORDPARAM keywords in [Input] and [Output] secti...
Definition: IOUtils.cc:733
void trim(std::string &str)
Removes trailing and leading whitespaces, tabs and newlines from a string.
Definition: IOUtils.cc:135
void replaceWhitespaces(std::string &line, const char &rep)
Replaces spaces and tabs with a single character or removes them.
Definition: IOUtils.cc:184
double VWDW_TO_V(const double &VW, const double &DW)
From wind speed and direction to v component (south-to-north)
Definition: IOUtils.h:109
bool convertString< double >(double &t, std::string str, std::ios_base &(*f)(std::ios_base &))
Definition: IOUtils.cc:472
const char cnodata
Definition: IOUtils.h:76
bool checkEpsilonEquality(const double &val1, const double &val2, const double &epsilon)
Check whether two values are equal regarding a certain epsilon environment (within certain radius of ...
Definition: IOUtils.h:118
const size_t npos
npos is the out-of-range value
Definition: IOUtils.h:77
double bearing_to_angle(const double &bearing)
Converts a compass bearing to a trigonometric angle.
Definition: IOUtils.cc:66
Definition: IOUtils.h:54
void stripComments(std::string &str)
Definition: IOUtils.cc:127
const double grid_epsilon
What is an acceptable small distance on a grid, in meters.
Definition: IOUtils.h:79
ProcessingLevel
Definition: IOUtils.h:53
void removeQuotes(std::string &line)
Removes single and double quotation marks.
Definition: IOUtils.cc:194
std::string getLogName()
Retrieve the user name This checks various environment variables (USERNAME, USER, LOGNAME)...
Definition: IOUtils.cc:300
const double earth_R0
Definition: Meteoconst.h:61
default: extract timeseries from timeseries or grids from grids or spatially interpolate timeseries ...
Definition: IOUtils.h:63
void toUpper(std::string &str)
Definition: IOUtils.cc:238
Definition: IOUtils.h:71
Definition: IOUtils.h:55
size_t count(const std::string &input, const std::string &search)
count how many times a substring appears in a string
Definition: IOUtils.cc:210
extract all relevant grid points from a provided grid
Definition: IOUtils.h:66
bool convertString< unsigned int >(unsigned int &t, std::string str, std::ios_base &(*f)(std::ios_base &))
Definition: IOUtils.cc:547
long int round(const double &x)
Optimized version of c++ round() This version works with positive and negative numbers but does not c...
Definition: MathOptim.h:44
size_t readLineToSet(const std::string &line_in, std::set< std::string > &setString)
Definition: IOUtils.cc:369
A class that reads a key/value file. These files (typically named *.ini) follow the INI file format s...
Definition: Config.h:79
const double t_water_freezing_pt
Definition: Meteoconst.h:49
thrown when an unsuccessful attempt to convert data types/classes is made (e.g. attempt to convert a ...
Definition: IOExceptions.h:118
std::string getHostName()
Retrieve the name of the computer running the binary.
Definition: IOUtils.cc:314
#define AT
Definition: IOExceptions.h:27
const double lon_epsilon
in degrees. Small angle for longitudes, so sin(x)=x
Definition: IOUtils.h:80
thrown when encountered an unexpected function&#39;s argument (e.g. bad index, bad or missing parameter n...
Definition: IOExceptions.h:130
extract data from grids at locations provided in the ini file
Definition: IOUtils.h:65
const double nodata
This is the internal nodata value.
Definition: IOUtils.h:72
void getValueForKey(const std::map< std::string, std::string > &properties, const std::string &key, T &t, const ThrowOptions &options=IOUtils::dothrow)
Returns, with the requested type, the value associated to a key (template function).
Definition: IOUtils.h:334
generate a grid at a different resolution
Definition: IOUtils.h:68
void removeDuplicateWhitespaces(std::string &line)
Removes consecutive occurrences of spaces and tabs.
Definition: IOUtils.cc:176
A class to handle timestamps. This class handles conversion between different time display formats (I...
Definition: Date.h:82
double C_TO_K(const double &T)
Definition: IOUtils.h:83
std::string toString(const T &t)
Definition: IOUtils.h:277
std::string strToUpper(std::string str)
Definition: IOUtils.cc:246
std::string getLibVersion(const bool &short_version)
Return the library version.
Definition: IOUtils.cc:57
double bearing(std::string bearing_str)
Converts a string bearing to a compass bearing.
Definition: IOUtils.cc:74
const short int snodata
Definition: IOUtils.h:75
size_t FNV_hash(const std::string &text)
Fowler/Noll/Vo hash function (FNV-1a)
Definition: IOUtils.cc:225
void cleanFieldName(std::string &field, const bool &clean_whitespaces, const char &rep)
Cleans up a string to be usable as, for example, a parameter name.
Definition: IOUtils.cc:200
size_t seek(const Date &soughtdate, const std::vector< MeteoData > &vecM, const bool &exactmatch)
Search for an element at a given date in a vector of MeteoData. The position of the matching date is ...
Definition: IOUtils.cc:754
bool convertString< bool >(bool &t, std::string str, std::ios_base &(*f)(std::ios_base &))
Definition: IOUtils.cc:443
static void parseArg(const std::pair< std::string, std::string > &arg, const std::string &algo, T &val)
Parse a given named argument.
Definition: IOUtils.h:411
const double lat_epsilon
in degrees. Small angle for latitudes.
Definition: IOUtils.h:81
const unsigned int unodata
Definition: IOUtils.h:73