WSL/SLF GitLab Repository

IOUtils.h 13.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/***********************************************************************************/
/*  Copyright 2009 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
/***********************************************************************************/
/* This file is part of MeteoIO.
    MeteoIO is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MeteoIO is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with MeteoIO.  If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __IOUTILS_H__
#define __IOUTILS_H__

21
#include <iostream>
22
23
24
25
26
#include <string>
#include <map>
#include <vector>
#include <cstdlib>
#include <limits>
27
#include <cmath>
28

29
30
#include <meteoio/dataClasses/Coords.h>
#include <meteoio/dataClasses/Date.h>
31
#include <meteoio/IOExceptions.h>
32
#include <meteoio/meteoLaws/Meteoconst.h>
33

34
35
namespace mio {

36
37
38
39
#ifdef _MSC_VER
double round(const double& x);
#endif

40
41
class MeteoData;
class Coords;
42
class Config;
43

44
45
46
47
48
49
/**
* @brief Return the library version
* @return library version string
*/
std::string getLibVersion();

50
namespace IOUtils {
51
52
53
54
55
56
57
58
	enum ProcessingLevel {
		raw           = 1,
		filtered      = 1 << 1,
		resampled     = 1 << 2,
		generated     = 1 << 3,
		num_of_levels = 1 << 4
	};

59
	enum ThrowOptions { dothrow, nothrow };
60
61
62
63
	const double nodata = -999.0; ///<This is the internal nodata value
	//const double not_set = std::numeric_limits<double>::max()-2.;
	const unsigned int unodata = (unsigned int)-1;
	const int inodata = -999;
64
	const short int snodata = -999;
65
	const size_t npos    = (size_t)-1;  ///<npos is the out-of-range value
66
67

	const double grid_epsilon = 5.; ///<What is an acceptable small distance on a grid, in meters
68
69
	const double lon_epsilon = grid_epsilon / Cst::earth_R0 *  Cst::to_deg; ///<in degrees. Small angle for longitudes, so sin(x)=x
	const double lat_epsilon = lon_epsilon; ///<in degrees. Small angle for latitudes.
70

71
72
	inline double C_TO_K(const double& T) {return ((T==nodata)? T : T + Cst::t_water_freezing_pt);}
	inline double K_TO_C(const double& T) {return ((T==nodata)? T : T - Cst::t_water_freezing_pt);}
73
	
74
75
76
77
78
79
80
	/**
	* @brief Check whether two values are equal regarding a certain epsilon environment (within certain radius of each other)
	* @param val1
	* @param val2
	* @param epsilon is a radius around val1
	* @return true if val2 is within the radius around val1, false otherwise.
	*/
81
	inline bool checkEpsilonEquality(const double& val1, const double& val2, const double& epsilon) {return (fabs(val1-val2) < epsilon);}
82

83
	size_t seek(const Date& soughtdate, const std::vector<MeteoData>& vecM, const bool& exactmatch=true);
84
85
86
87
88
89
90
91
92
93
94
95
96

	/**
	* @brief Converts a compass bearing to a trigonometric angle
	* @param bearing compass bearing (0° on top, clockwise, in [0°, 360°[)
	* @return trigonometric angle (0° on the right, counterclockwise, in [0, 2PI[)
	*/
	double bearing_to_angle(const double& bearing);
	/**
	* @brief Converts a trigonometric angle to a compass bearing
	* @param angle trigonometric angle (0° on the right, counterclockwise, in [0, 2PI[)
	* @return bearing (0° on top, clockwise, in [0°, 360°[)
	*/
	double angle_to_bearing(const double& angle);
97
98
99
100
101
	/**
	* @brief Converts a string bearing to a compass bearing
	* @param bearing_str as N, NE, SSW, etc
	* @return bearing (0° on top, clockwise, in [0°, 360°[)
	*/
102
	double bearing(std::string bearing_str);
103
104
105
106
107
108
	/**
	* @brief Converts a compass bearing to a string bearing
	* @param bearing (0° on top, clockwise, in [0°, 360°[)
	* @return bearing_str as N, NE, SSW, etc
	*/
	std::string bearing(double bearing);
109

110
111
112
113
114
115
116
	/**
	* @brief Retrieve the user name
	* This checks various environment variables (USERNAME, USER, LOGNAME).
	* @return user name
	*/
	std::string getLogName();

117
	/**
118
	* @brief Removes trailing and leading whitespaces, tabs and newlines from a string.
119
120
121
122
	* @param s The reference of the string to trim (in/out parameter)
	*/
	void trim(std::string &s);

123
124
	void stripComments(std::string& str);

125
126
127
128
	/**
	* @brief read a string line, parse it and save it into a map object, that is passed by reference
	* @param in_line (const string&) string to parse
	* @param delimiter (const string&) delimiter to use for the parsing
129
	* @param setToUpperCase If set to true the key will be put into upper case (for case insensitivity)
130
131
	* @param key retrieved key
	* @param value retrieved value
132
133
	* @return (bool) true when line is empty
	*/
134
135
	bool readKeyValuePair(const std::string& in_line, const std::string& delimiter,
	                      std::string &key, std::string &value, const bool& setToUpperCase=false);
136
137

	void toUpper(std::string& str);
138
	std::string strToUpper(std::string str);
139
	void toLower(std::string& str);
140
	std::string strToLower(std::string str);
141
	bool isNumeric(std::string input, const unsigned int& nBase=10);
142
	size_t readLineToVec(const std::string& line_in, std::vector<double>& vec_data);
143
144
	size_t readLineToVec(const std::string& line_in, std::vector<std::string>& vecString);
	size_t readLineToVec(const std::string& line_in, std::vector<std::string>& vecString, const char& delim);
145
146
147
148
149
150
151

	/**
	* @brief Convert a string to the requested type (template function).
	* @tparam T   [in] The type wanted for the return value (template type parameter).
	* @param t   [out] The value converted to the requested type.
	* @param str   [in] The input string to convert; trailling whitespaces are ignored,
	*              comment after non-string values are allowed, but multiple values are not allowed.
152
153
154
155
	* @param f   [in] The radix for reading numbers, such as std::dec or std::oct; default is std::dec.
	* @return true if everything went fine, false otherwise
	*/
	template <class T> bool convertString(T& t, const std::string& str, std::ios_base& (*f)(std::ios_base&) = std::dec) {
156
		std::string s(str);
157
		trim(s); //delete trailing and leading whitespaces and tabs
158
		if (s.empty()) {
159
160
161
162
163
164
165
166
167
168
169
			t = static_cast<T> (nodata);
			return true;
		} else {
			std::istringstream iss(s);
			iss.setf(std::ios::fixed);
			iss.precision(std::numeric_limits<double>::digits10); //try to read values with maximum precision
			iss >> f >> t; //Convert first part of stream with the formatter (e.g. std::dec, std::oct)
			if (iss.fail()) {
				//Conversion failed
				return false;
			}
170
			std::string tmp;
171
172
			getline(iss,  tmp); //get rest of line, if any
			trim(tmp);
173
			if (!tmp.empty() && tmp[0] != '#' && tmp[0] != ';') {
174
175
176
177
178
179
180
				//if line holds more than one value it's invalid
				return false;
			}
			return true;
		}
	}
	// fully specialized template functions (implementation must not be in header)
181
	template<> bool convertString<double>(double& t, const std::string& str, std::ios_base& (*f)(std::ios_base&));
182
183
	template<> bool convertString<std::string>(std::string& t, const std::string& str, std::ios_base& (*f)(std::ios_base&));
	template<> bool convertString<bool>(bool& t, const std::string& str, std::ios_base& (*f)(std::ios_base&));
184
	template<> bool convertString<unsigned int>(unsigned int& t, const std::string& str, std::ios_base& (*f)(std::ios_base&));
185
186
	template<> bool convertString<Coords>(Coords& t, const std::string& str, std::ios_base& (*f)(std::ios_base&));

187
	bool convertString(Date& t, const std::string& str, const double& time_zone, std::ios_base& (*f)(std::ios_base&) = std::dec);
188

189
190
191
	/**
	* @brief Returns, with the requested type, the value associated to a key (template function).
	* @tparam T   [in] The type wanted for the return value (template type parameter).
192
193
194
195
	* @param[in]  properties  A map containing all the parameters.
	* @param[in]  key         The key of the parameter to retrieve.
	* @param[out] t           The value associated to the key, converted to the requested type
	* @param[in]  options     Extra options, by default IOUtils::dothrow
196
197
	*/
	template <class T> void getValueForKey(const std::map<std::string,std::string>& properties,
198
	                                       const std::string& key, T& t, const ThrowOptions& options=IOUtils::dothrow){
199
		if (key.empty() && options!=IOUtils::nothrow)
200
201
			throw InvalidArgumentException("Empty key", AT);

202
		const std::map<std::string, std::string>::const_iterator it = properties.find(key);
203
204
205
206

		if (it == properties.end()){
			if (options == IOUtils::nothrow)
				return;
207
			else
208
				throw UnknownValueException("No value for key " + key, AT);
209
		}
210
		const std::string& value = it->second;
211

212
		if(!convertString<T>(t, value, std::dec) && options!=IOUtils::nothrow) {
Mathias Bavay's avatar
Mathias Bavay committed
213
			std::cerr << "[E] When reading \"" << key << "\" = \"" << t << "\"\n";
214
215
216
217
218
219
220
			throw ConversionFailedException(value, AT);
		}
	}

	/**
	* @brief Returns, with the requested type, the value associated to a key (template function).
	* @tparam T           [in] The type wanted for the return value (template type parameter).
221
222
	* @param[in]  properties  A map containing all the parameters.
	* @param[in]  key         The key of the parameter to retrieve.
223
	* @param[out] vecT        The vector of values associated to the key, each value is converted to the requested type
224
	* @param[in]  options     Extra options, by default IOUtils::dothrow
225
	*/
226
	template <class T> void getValueForKey(const std::map<std::string,std::string>& properties,
227
	                                       const std::string& key, std::vector<T>& vecT, const ThrowOptions& options=IOUtils::dothrow)
228
	{
229
230
		if (key.empty() && options!=IOUtils::nothrow)
			throw InvalidArgumentException("Empty key", AT);
231

232
		const std::map<std::string, std::string>::const_iterator it = properties.find(key);
233
234
		if (it == properties.end()) {
			if (options == IOUtils::nothrow) {
235
				return;
236
			} else {
237
				throw UnknownValueException("No value for key " + key, AT);
238
			}
239
		}
240
		const std::string& value = it->second;
241

242
		//split value string
243
		std::vector<std::string> vecUnconvertedValues;
244
		const size_t counter = readLineToVec(value, vecUnconvertedValues);
245
		for (size_t ii=0; ii<counter; ii++){
246
			T myvar;
247
			if(!convertString<T>(myvar, vecUnconvertedValues.at(ii), std::dec) && options!=IOUtils::nothrow){
Mathias Bavay's avatar
Mathias Bavay committed
248
				std::cerr << "[E] When reading \"" << key << "\" = \"" << myvar << "\"\n";
249
250
251
252
253
254
255
256
				throw ConversionFailedException(vecUnconvertedValues.at(ii), AT);
			}
			vecT.push_back(myvar);
		}
	}

	/**
	* @brief Standardize a given value to use MeteoIO's internal nodata value (if applicable)
257
	* @tparam T[in] The type wanted for the return value (template type parameter).
258
259
260
261
262
263
264
265
266
267
	* @param[in] value  the value to check/convert
	* @param[in] plugin_nodata plugin-specific nodata value
	* @return checked/converted value
	*/
	template <class T> T standardizeNodata(const T& value, const double& plugin_nodata) {
		if(value==plugin_nodata) return static_cast<T> (nodata);
		else return value;
	}

	/**
268
	* @brief A function that parses a Config object for COORSYS, COORDPARAM keywords in [Input] and [Output]
269
	*        section and sets the respective strings to the values of those keywords
270
	* @param[in] cfg  A Config object
271
272
273
274
275
	* @param[out] coordin The coordinate system to be used for input data
	* @param[out] coordinparam The coordinate system parameters to be used for output data
	* @param[out] coordout The coordinate system to be used for output data
	* @param[out] coordoutparam The coordinate system parameters to be used for output data
	*/
276
	void getProjectionParameters(const Config& cfg, std::string& coordin, std::string& coordinparam,
277
	                             std::string& coordout, std::string& coordoutparam);
278
279

	/**
280
	* @brief A function that parses a Config object for the time_zone keyword and returns the timezone
281
	* @param[in] cfg  A Config object
282
283
284
	* @param[out] tz_in value to be used for the input timezone
	* @param[out] tz_out value to be used for the output timezone
	*/
285
	void getTimeZoneParameters(const Config& cfg, double& tz_in, double& tz_out);
286

287
288
289
290
291
292
	/**
	* @brief Returns the parameters for splitting an array in several, balanced sub-arrays.
	* This is mostly usefull for parallel calculations, where an array will be split and sent to different
	* workers.
	* @param[in] dimx number of cells in the desired dimension
	* @param[in] nbworkers total number of slices
293
	* @param[in] wk current slice index (starting at 1)
294
295
296
	* @param[out] startx calculated start index for the current slice
	* @param[out] nx calculated number of cells (in the desired dimension) of the current slice
	*/
297
	void getArraySliceParams(const size_t& dimx, const unsigned int& nbworkers, const unsigned int &wk, size_t& startx, size_t& nx);
298

299
300
301
302
303
304
305
306
307
	/**
	* @brief Convert a textual representation of a unit prefix (like 'm' or 'G') to multiplying factor
	* @param prefix unit prefix
	* return multiplying factor
	*/
	double unitsPrefix(const char& prefix);

	/**
	* @brief Performs simple unit conversion (supports temperature, prefixes and exponents)
308
	* NOTE "composite" units such as 'K/m' or 'N/m2' are currently NOT supported.
309
310
311
312
313
314
	* @param val value to convert
	* @param unitIn units of the input
	* @param unitOut units to convert to
	* return value, expressed in unitOut
	*/
	double unitsConversion(const double& val, std::string unitIn, std::string unitOut);
315
} //end namespace IOUtils
316

317
318
319
} //end namespace mio

#endif