MeteoIODoc 20250905.f67af007
 
Loading...
Searching...
No Matches
IOUtils.h
Go to the documentation of this file.
1// SPDX-License-Identifier: LGPL-3.0-or-later
2/***********************************************************************************/
3/* Copyright 2009 WSL Institute for Snow and Avalanche Research SLF-DAVOS */
4/***********************************************************************************/
5/* This file is part of MeteoIO.
6 MeteoIO is free software: you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 MeteoIO is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with MeteoIO. If not, see <http://www.gnu.org/licenses/>.
18*/
19#ifndef IOUTILS_H
20#define IOUTILS_H
21
22#include <iostream>
23#include <string>
24#include <map>
25#include <vector>
26#include <set>
27#include <cstdlib>
28#include <limits>
29#include <cmath>
30
35
36namespace mio {
37
38#ifdef _MSC_VER
39double round(const double& x);
40#endif
41
42class MeteoData;
43class Coords;
44class Config;
45
51std::string getLibVersion(const bool& short_version=false);
52
53namespace IOUtils {
55 raw = 1,
56 filtered = 1 << 1,
57 resampled = 1 << 2,
58 generated = 1 << 3,
59 num_of_levels = 1 << 4
60 };
61
73
75 const double nodata = -999.0;
76 const unsigned int unodata = static_cast<unsigned int>(-1);
77 const int inodata = -999;
78 const long lnodata = -999;
79 const short int snodata = -999;
80 const char cnodata = std::numeric_limits<char>::max();
81 const size_t npos = static_cast<size_t>(-1);
82
83 const double grid_epsilon = 5.;
85 const double lat_epsilon = lon_epsilon;
86
87 inline double C_TO_K(const double& T) {return ((T==nodata)? T : T + Cst::t_water_freezing_pt);}
88 inline double K_TO_C(const double& T) {return ((T==nodata)? T : T - Cst::t_water_freezing_pt);}
89
97 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.));}
98
105 inline double VWDW_TO_U(const double& VW, const double& DW) {return ((VW==nodata || DW==nodata)? nodata : (- VW * sin(DW*Cst::to_rad)));}
106
113 inline double VWDW_TO_V(const double& VW, const double& DW) {return ((VW==nodata || DW==nodata)? nodata : (- VW * cos(DW*Cst::to_rad)));}
114
122 inline bool checkEpsilonEquality(const double& val1, const double& val2, const double& epsilon) {return (std::abs(val1-val2) < epsilon);}
123
133 size_t seek(const Date& soughtdate, const std::vector<MeteoData>& vecM, const bool& exactmatch=true);
134
140 double bearing_to_angle(const double& bearing);
146 double angle_to_bearing(const double& angle);
152 double bearing(std::string bearing_str);
158 std::string bearing(double bearing);
159
165 std::string getLogName();
166
171 std::string getHostName();
172
177 std::string getDomainName();
178
183 void trim(std::string &s);
184
190 std::string trim(const std::string &s);
191
192 void stripComments(std::string& str);
193
194 void stripComments(std::string& str, const char& comment_mk);
195
196 void cleanEscapedCharacters(std::string& str, const std::vector<char>& escaped_chars);
197
205 void replace_all(std::string &input, const std::string& search, const std::string& format);
206
211 void removeDuplicateWhitespaces(std::string& line);
212
218 void replaceWhitespaces(std::string& line, const char& rep = '\0');
219
225 void replaceInvalidChars(std::string& line, const char& rep = '\0');
226
231 void removeQuotes(std::string& line);
232
238 void removeChars(std::string& line, const std::set<char>& specialChars);
239
248 void cleanFieldName(std::string& field, const bool& clean_whitespaces = true, const char& rep = '-');
249
257 size_t count(const std::string &input, const std::string& search);
258
267 size_t FNV_hash(const std::string& text);
268
278 bool readKeyValuePair(const std::string& in_line, const std::string& delimiter,
279 std::string &key, std::string &value, const bool& setToUpperCase=false);
280
281 void toUpper(std::string& str);
282 std::string strToUpper(std::string str);
283 void toLower(std::string& str);
284 std::string strToLower(std::string str);
285 bool isNumeric(std::string input, const unsigned int& nBase=10);
286 size_t readLineToVec(const std::string& line_in, std::vector<double>& vec_data);
287 size_t readLineToSet(const std::string& line_in, std::set<std::string>& setString);
288 size_t readLineToVec(const std::string& line_in, std::vector<std::string>& vecString);
289 size_t readLineToVec(const std::string& line_in, std::vector<std::string>& vecString, const char& delim);
290 size_t readLineToVec(const std::string& line_in, std::vector<double>& vecRet, const char& delim);
291
292 std::vector<std::string> split(const std::string& str, char delim);
293 std::vector<std::string> split(const std::string& str, std::string delim);
294
295 template <class T> std::string toString(const T& t) {
296 std::ostringstream os;
297 os << t;
298 return os.str();
299 }
300
310 template <class T> bool convertString(T& t, std::string str, std::ios_base& (*f)(std::ios_base&) = std::dec) {
311 trim(str); //delete trailing and leading whitespaces and tabs
312 if (str.empty()) {
313 t = static_cast<T>(nodata);
314 return true;
315 } else {
316 std::istringstream iss(str);
317 iss.setf(std::ios::fixed);
318 iss.precision(std::numeric_limits<double>::digits10); //try to read values with maximum precision
319 iss >> f >> t; //Convert first part of stream with the formatter (e.g. std::dec, std::oct)
320 if (iss.fail()) {
321 //Conversion failed
322 return false;
323 }
324 std::string tmp;
325 getline(iss, tmp); //get rest of line, if any
326 trim(tmp);
327 if (!tmp.empty() && tmp[0] != '#' && tmp[0] != ';') {
328 //if line holds more than one value it's invalid
329 return false;
330 }
331 return true;
332 }
333 }
334 // fully specialized template functions (implementation must not be in header)
335 template<> bool convertString<double>(double& t, std::string str, std::ios_base& (*f)(std::ios_base&));
336 template<> bool convertString<std::string>(std::string& t, std::string str, std::ios_base& (*f)(std::ios_base&));
337 template<> bool convertString<bool>(bool& t, std::string str, std::ios_base& (*f)(std::ios_base&));
338 template<> bool convertString<char>(char& t, std::string str, std::ios_base& (*f)(std::ios_base&));
339 template<> bool convertString<unsigned int>(unsigned int& t, std::string str, std::ios_base& (*f)(std::ios_base&));
340 template<> bool convertString<Coords>(Coords& t, std::string str, std::ios_base& (*f)(std::ios_base&));
341
342 bool convertString(Date& t, std::string str, const double& time_zone, std::ios_base& (*f)(std::ios_base&) = std::dec);
343
352 template <class T> void getValueForKey(const std::map<std::string,std::string>& properties,
353 const std::string& key, T& t, const ThrowOptions& options=IOUtils::dothrow) {
354 if (key.empty() && options!=IOUtils::nothrow)
355 throw InvalidArgumentException("Empty key", AT);
356
357 const std::map<std::string, std::string>::const_iterator it( properties.find(key) );
358 if (it == properties.end()){
359 if (options == IOUtils::nothrow)
360 return;
361 else
362 throw UnknownValueException("No value for key " + key, AT);
363 }
364 const std::string& value = it->second;
365
366 if (!convertString<T>(t, value, std::dec) && options!=IOUtils::nothrow) {
367 std::cerr << "[E] When reading \"" << key << "\" = \"" << t << "\"\n";
368 throw ConversionFailedException(value, AT);
369 }
370 }
371
380 template <class T> void getValueForKey(const std::map<std::string,std::string>& properties,
381 const std::string& key, std::vector<T>& vecT, const ThrowOptions& options=IOUtils::dothrow)
382 {
383 if (key.empty() && options!=IOUtils::nothrow)
384 throw InvalidArgumentException("Empty key", AT);
385
386 const std::map<std::string, std::string>::const_iterator it( properties.find(key) );
387 if (it == properties.end()) {
388 if (options == IOUtils::nothrow) {
389 return;
390 } else {
391 throw UnknownValueException("No value for key " + key, AT);
392 }
393 }
394 const std::string& value = it->second;
395
396 //split value string
397 std::vector<std::string> vecUnconvertedValues;
398 const size_t counter = readLineToVec(value, vecUnconvertedValues);
399 vecT.resize( counter );
400 for (size_t ii=0; ii<counter; ii++){
401 T myvar;
402 if (!convertString<T>(myvar, vecUnconvertedValues.at(ii), std::dec) && options!=IOUtils::nothrow){
403 std::cerr << "[E] When reading \"" << key << "\" = \"" << myvar << "\"\n";
404 throw ConversionFailedException(vecUnconvertedValues.at(ii), AT);
405 }
406 vecT[ii] = myvar;
407 }
408 }
409
417 template <class T> T standardizeNodata(const T& value, const double& plugin_nodata) {
418 if (value==plugin_nodata) return static_cast<T> (nodata);
419 else return value;
420 }
421
429 template <class T> static void parseArg(const std::pair< std::string, std::string>& arg, const std::string& algo, T& val) {
430 if (!IOUtils::convertString(val, arg.second))
431 throw InvalidArgumentException("Can not parse argument '"+arg.first+"::"+arg.second+"' for " + algo, AT);
432 }
433
443 void getProjectionParameters(const Config& cfg, std::string& coordin, std::string& coordinparam,
444 std::string& coordout, std::string& coordoutparam);
445
453 void getProjectionParameters(const Config& cfg, std::string& coordin, std::string& coordinparam);
454
461 void getTimeZoneParameters(const Config& cfg, double& tz_in, double& tz_out);
462
468 double unitsPrefix(const char& prefix);
469
478 double unitsConversion(const double& val, std::string unitIn, std::string unitOut);
479
485 std::string escapeXml(const std::string& input);
486} //end namespace IOUtils
487
488} //end namespace mio
489
490#endif
#define AT
Definition IOExceptions.h:28
A class that reads a key/value file. These files (typically named *.ini) follow the INI file format s...
Definition Config.h:79
thrown when an unsuccessful attempt to convert data types/classes is made (e.g. attempt to convert a ...
Definition IOExceptions.h:118
A class to handle geographic coordinate systems. This class offers an easy way to transparently conve...
Definition Coords.h:83
A class to handle timestamps. This class handles conversion between different time display formats (I...
Definition Date.h:87
thrown when encountered an unexpected function's argument (e.g. bad index, bad or missing parameter n...
Definition IOExceptions.h:130
thrown when encountered an unexpected value (e.g. unknown name or key)
Definition IOExceptions.h:142
static const double to_rad
Definition Meteoconst.h:85
static const double t_water_freezing_pt
Definition Meteoconst.h:50
static const double earth_R0
Definition Meteoconst.h:62
static const double to_deg
Definition Meteoconst.h:86
bool convertString< char >(char &t, std::string str, std::ios_base &(*f)(std::ios_base &))
Definition IOUtils.cc:602
double bearing_to_angle(const double &bearing)
Converts a compass bearing to a trigonometric angle.
Definition IOUtils.cc:67
size_t readLineToVec(const std::string &line_in, std::vector< double > &vec_data)
Definition IOUtils.cc:401
bool convertString< std::string >(std::string &t, std::string str, std::ios_base &(*f)(std::ios_base &))
Definition IOUtils.cc:514
const double lat_epsilon
in degrees. Small angle for latitudes.
Definition IOUtils.h:85
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:325
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:660
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:429
std::string escapeXml(const std::string &input)
Escape special charaters in a string to make it suitable for XML output.
Definition IOUtils.cc:969
std::string getLogName()
Retrieve the user name This checks various environment variables (USERNAME, USER, LOGNAME).
Definition IOUtils.cc:347
T standardizeNodata(const T &value, const double &plugin_nodata)
Standardize a given value to use MeteoIO's internal nodata value (if applicable)
Definition IOUtils.h:417
double bearing(std::string bearing_str)
Converts a string bearing to a compass bearing.
Definition IOUtils.cc:75
void stripComments(std::string &str)
Definition IOUtils.cc:128
double VWDW_TO_V(const double &VW, const double &DW)
From wind speed and direction to v component (south-to-north)
Definition IOUtils.h:113
void removeQuotes(std::string &line)
Removes single and double quotation marks.
Definition IOUtils.cc:235
void removeChars(std::string &line, const std::set< char > &specialChars)
Removes any character present in the provided set from the given line.
Definition IOUtils.cc:241
void toLower(std::string &str)
Definition IOUtils.cc:289
double C_TO_K(const double &T)
Definition IOUtils.h:87
const size_t npos
npos is the out-of-range value
Definition IOUtils.h:81
const long lnodata
Definition IOUtils.h:78
void removeDuplicateWhitespaces(std::string &line)
Removes consecutive occurrences of spaces and tabs.
Definition IOUtils.cc:217
bool convertString< unsigned int >(unsigned int &t, std::string str, std::ios_base &(*f)(std::ios_base &))
Definition IOUtils.cc:626
const int inodata
Definition IOUtils.h:77
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:916
void cleanEscapedCharacters(std::string &str, const std::vector< char > &escaped_chars)
Definition IOUtils.cc:156
double unitsPrefix(const char &prefix)
Convert a textual representation of a unit prefix (like 'm' or 'G') to multiplying factor.
Definition IOUtils.cc:891
size_t FNV_hash(const std::string &text)
Fowler/Noll/Vo hash function (FNV-1a)
Definition IOUtils.cc:272
bool convertString< double >(double &t, std::string str, std::ios_base &(*f)(std::ios_base &))
Definition IOUtils.cc:551
bool isNumeric(std::string str, const unsigned int &nBase)
Definition IOUtils.cc:305
std::string strToUpper(std::string str)
Definition IOUtils.cc:293
size_t readLineToSet(const std::string &line_in, std::set< std::string > &setString)
Definition IOUtils.cc:423
std::string getDomainName()
Retrieve the domain name of the computer running the binary.
Definition IOUtils.cc:389
OperationMode
Keywords for mode of operation. Please keep all the GRID_xxx last!
Definition IOUtils.h:63
@ GRID_EXTRACT_PTS
as GRID_EXTRACT, but queries plugin only for virtual stations points, instead of full grids
Definition IOUtils.h:68
@ GRID_SMART
extract all relevant grid points from a provided grid
Definition IOUtils.h:69
@ GRID_ALL
extract all grid points from a provided grid
Definition IOUtils.h:70
@ GRID_RESAMPLE
generate a grid at a different resolution
Definition IOUtils.h:71
@ VSTATIONS
extract virtual stations as specified in the ini file
Definition IOUtils.h:65
@ GRID_1DINTERPOLATE
temporally interpolate existing grids (must be enumerated before GRID_EXTRACT)
Definition IOUtils.h:66
@ GRID_EXTRACT
extract data from grids at locations provided in the ini file
Definition IOUtils.h:67
@ STD
default: extract timeseries from timeseries or grids from grids or spatially interpolate timeseries
Definition IOUtils.h:64
const double nodata
This is the internal nodata value.
Definition IOUtils.h:75
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:97
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:352
bool convertString< Coords >(Coords &t, std::string str, std::ios_base &(*f)(std::ios_base &))
Definition IOUtils.cc:795
std::string toString(const T &t)
Definition IOUtils.h:295
const char cnodata
Definition IOUtils.h:80
const unsigned int unodata
Definition IOUtils.h:76
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:197
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:812
void trim(std::string &str)
Removes trailing and leading whitespaces, tabs and newlines from a string.
Definition IOUtils.cc:175
double VWDW_TO_U(const double &VW, const double &DW)
From wind speed and direction to u component (west-to-east)
Definition IOUtils.h:105
void toUpper(std::string &str)
Definition IOUtils.cc:285
const short int snodata
Definition IOUtils.h:79
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:833
std::string getHostName()
Retrieve the name of the computer running the binary.
Definition IOUtils.cc:361
const double lon_epsilon
in degrees. Small angle for longitudes, so sin(x)=x
Definition IOUtils.h:84
void replaceWhitespaces(std::string &line, const char &rep)
Replaces spaces and tabs with a single character or removes them.
Definition IOUtils.cc:225
ProcessingLevel
Definition IOUtils.h:54
@ resampled
Definition IOUtils.h:57
@ num_of_levels
Definition IOUtils.h:59
@ raw
Definition IOUtils.h:55
@ filtered
Definition IOUtils.h:56
@ generated
Definition IOUtils.h:58
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:827
void replaceInvalidChars(std::string &line, const char &rep)
Replaces invalid characters with a single character or removes them.
Definition IOUtils.cc:230
double K_TO_C(const double &T)
Definition IOUtils.h:88
bool convertString< bool >(bool &t, std::string str, std::ios_base &(*f)(std::ios_base &))
Definition IOUtils.cc:522
std::vector< std::string > split(const std::string &s, char delimiter)
Definition IOUtils.cc:484
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:247
double angle_to_bearing(const double &angle)
Converts a trigonometric angle to a compass bearing.
Definition IOUtils.cc:71
size_t count(const std::string &input, const std::string &search)
count how many times a substring appears in a string
Definition IOUtils.cc:257
const double grid_epsilon
What is an acceptable small distance on a grid, in meters.
Definition IOUtils.h:83
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:122
std::string strToLower(std::string str)
Definition IOUtils.cc:300
ThrowOptions
Definition IOUtils.h:74
@ nothrow
Definition IOUtils.h:74
@ dothrow
Definition IOUtils.h:74
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:45
Definition Config.cc:34
std::string getLibVersion(const bool &short_version)
Return the library version.
Definition IOUtils.cc:58
static const double plugin_nodata
Definition GRIBIO.cc:141