Initfile.h 12.9 KB
Newer Older
Praetorius, Simon's avatar
Praetorius, Simon committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#ifndef INITFILE_H
#define INITFILE_H

#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <list>
#include <set>
#include <vector>
#include <stdexcept>
#include <iostream>
#include <typeinfo>
#include "FixVec.h"

#include <boost/algorithm/string/trim.hpp>
#include <boost/lexical_cast.hpp>
18
19
#include <boost/numeric/conversion/cast.hpp> 

20
#include <boost/type_traits.hpp>
Praetorius, Simon's avatar
Praetorius, Simon committed
21

22
23
// a parser for arithmetic expressions
#include "muParser.h"
Praetorius, Simon's avatar
Praetorius, Simon committed
24

25
26
27
28
namespace AMDiS {

  namespace InitfileInternal {

Praetorius, Simon's avatar
Praetorius, Simon committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
	/// Exceptions
    struct WrongVectorSize : std::runtime_error {
		WrongVectorSize(std::string m):std::runtime_error(m) {}
	};
    struct NoDelim : std::runtime_error {
		NoDelim(std::string m):std::runtime_error(m) {}
	};
    struct WrongVectorFormat : std::runtime_error {
		WrongVectorFormat(std::string m):std::runtime_error(m) {}
	};
	template< typename T >
    struct WrongValueFormat : std::runtime_error {
		static std::string name(int ) { return "int"; }
		static std::string name(bool ) { return "bool"; }
		static std::string name(double ) { return "double"; }
		static std::string name(unsigned int ) { return "unsigned int"; }
		template< typename G >
		static std::string name(G ) { return std::string(typeid(G).name()); }
		
		WrongValueFormat(std::string value): std::runtime_error(std::string("cannot convert '") + value + std::string("' into <")+ name(T())+">" ) 
		{}
50
51
52
53
54
55
56
57
58
59
60
61
	};
	template< typename T >
    struct BadArithmeticExpression : std::runtime_error {
		static std::string name(int ) { return "int"; }
		static std::string name(bool ) { return "bool"; }
		static std::string name(double ) { return "double"; }
		static std::string name(unsigned int ) { return "unsigned int"; }
		template< typename G >
		static std::string name(G ) { return std::string(typeid(G).name()); }
		
		BadArithmeticExpression(std::string m, std::string value): std::runtime_error(std::string("cannot evaluate expression '") + value + std::string("' into <")+ name(T())+">\nParser message: '" + m + "'" ) 
		{}
Praetorius, Simon's avatar
Praetorius, Simon committed
62
63
64
65
66
67
68
69
70
	};
	
	/// trim std::string
	inline std::string trim(const std::string& oldStr) {
		std::string swap(oldStr);
		boost::algorithm::trim(swap);
		return swap;
	}
	/// return the delimiter or throw an exception if there is no known delimiter in value
71
	inline size_t checkDelim(const std::string& value, const std::string& delims) {
Praetorius, Simon's avatar
Praetorius, Simon committed
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
		size_t pos(std::string::npos);
		for (unsigned i= 0; i<delims.length(); ++i) {
			pos= value.find(delims[i]);
			if (pos!=std::string::npos)
				return i;
		}
		throw NoDelim("cannot detect the delimiter in " + value);
		return 0; 
	}


	/** parse an container from tag tag. The Container must have the properties:
	 * 	- type value_type
	 * 	- member function push_back
	 */
	template< typename Container >
	inline void getContainer(const std::string val_, Container& c) {
		
		// accepted brackets and delimiters for vector input
		std::string begBrackets= "{[(";
		std::string endBrackets= "}])";
		std::string delims= ",;";

		c.clear();
		std::string val= trim(val_); 
		size_t pos= begBrackets.find(val[0]);
		if( pos == std::string::npos )
			throw WrongVectorFormat("cannot convert '" + val + "' into a list. No leading bracket found!");
		if( val[val.length() - 1] != endBrackets[pos] )
			throw WrongVectorFormat("begin and end bracket are different in value '" + val + "'");
		size_t oldPos= 1;
		size_t curDelim= 0;
		typedef typename Container::value_type ValueType;
		ValueType swap;
		try {
			curDelim= checkDelim(val, delims);
			pos= val.find(delims[curDelim], oldPos);
			while( pos != std::string::npos ) {
110
				std::string curWord= val.substr(oldPos, pos - oldPos);
Praetorius, Simon's avatar
Praetorius, Simon committed
111
112
113
114
115
116
				oldPos= pos + 1;
				convert(curWord, swap);
				c.push_back(swap);
				pos= val.find(delims[curDelim], oldPos);
			}
			//last entry
117
			std::string curWord= val.substr(oldPos, val.length()-1 - oldPos);
Praetorius, Simon's avatar
Praetorius, Simon committed
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
			convert(curWord, swap);
			c.push_back(swap);
		} catch (NoDelim nd) {
			std::string curWord= val.substr(1, val.length()-2);
			curWord = trim(curWord);
			if(curWord.length()>0) {
			// container with one entry
				convert(curWord, swap);
				c.push_back(swap);
			}
		}
	}

	/// convert string to string
	inline void convert(const std::string valStr, std::string& value) {
		value= trim(valStr);
	}

	/// convert string to intrinsic type
137
138
139
	template< typename T >	
	inline void convert(const std::string valStr, T& value , 
	        typename boost::enable_if< boost::is_pod< T > >::type* p = NULL , 
140
141
	        typename boost::disable_if< boost::is_enum< T > >::type* p2 = NULL ) 
	{
Praetorius, Simon's avatar
Praetorius, Simon committed
142
		using boost::lexical_cast;
143
		using boost::numeric_cast;
144

145
146
147
148
		mu::Parser parser;

		parser.DefineConst(_T("M_PI"), m_pi);
		parser.DefineConst(_T("M_E"), m_e);
Praetorius, Simon's avatar
Praetorius, Simon committed
149
		try {
150
151
152
153
154
155
			parser.SetExpr(valStr);
// 			value = lexical_cast< T >(trim(valStr));
			value= numeric_cast< T >(parser.Eval());
		} catch(boost::bad_lexical_cast e) {
			throw WrongValueFormat< T >(valStr);
		} catch(boost::bad_numeric_cast e) {
Praetorius, Simon's avatar
Praetorius, Simon committed
156
			throw WrongValueFormat< T >(valStr);
157
158
		} catch (mu::Parser::exception_type &e) {
			throw BadArithmeticExpression< T >(e.GetMsg(), valStr);
Praetorius, Simon's avatar
Praetorius, Simon committed
159
160
		}
	}
161
162
163

	template< typename T >
	inline void convert(const std::string valStr, T& value, 
164
165
	        typename boost::enable_if< boost::is_enum< T > >::type* p = NULL) 
	{
166
167
168
169
170
171
172
173
174
175

		unsigned int swap= 0;
		try {
			swap = boost::lexical_cast< unsigned int >(trim(valStr));
		}catch(boost::bad_lexical_cast e) {
			throw WrongValueFormat< T >(valStr);
		}
		value = static_cast< T >(swap);
	}

Praetorius, Simon's avatar
Praetorius, Simon committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
	/// convert string to WorldVector
	template< typename T >
	inline void convert(const std::string valStr, WorldVector<T>& c) {
		std::vector<T> temp_vec;
		getContainer(valStr, temp_vec);
		if (static_cast<int>(temp_vec.size())!=c.getSize())
			throw WrongVectorSize("wrong number of entries for WorldVector");
		
		for (unsigned i= 0; i<temp_vec.size(); ++i)
			c[i]= temp_vec[i];
	}

	/// convert string to std::list using begBrackets, endBrackets and delims
	template< typename T >
	inline void convert(const std::string valStr, std::list< T >& value) {
		getContainer(valStr, value);
	}

	/// convert string to std::vector using begBrackets, endBrackets and delims
	template< typename T >
	inline void convert(const std::string valStr, std::vector< T >& value) {
		getContainer(valStr, value);
	}

	/// convert value of arbitrary type to string using stringstream and operator<< for type
	template< typename T >
	inline void convert(const T value, std::string& valStr) {
		std::stringstream ss;
		ss << value;
		valStr= ss.str();
	}
	/// convert WorldVector to string
	template< typename T >
	inline void convert(const WorldVector<T>& c, std::string& valStr) {
		std::vector<T> temp_vec(c.getSize());
		for (unsigned i= 0; i<temp_vec.size(); ++i)
			temp_vec[i]= c[i];
		convert(temp_vec, valStr);
	}
215
  } // end namespace InitfileInternal
Praetorius, Simon's avatar
Praetorius, Simon committed
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268

/** The entry in an initfile. This helper class was constructed to allow calls like
 *  val = data.get(tag)
 *  for arbitrary types of val. At current stage, only double and bool is supported
 */

struct InitEntry {
	///the value as string
	std::string valStr;

	/// initialize with value as string
	InitEntry(std::string v= ""):
		valStr(v) {}

	/// cast string to type T
	template< typename T >
	operator T() const { T t; convert(valStr, t); return t;}
};

/// output-stream for std::list
template< typename T >
std::ostream& operator<<(std::ostream& o, const std::list< T >& l) {
	typename std::list< T >::const_iterator it= l.begin();
	o << "[";
	for(unsigned i= 0; it!=l.end() && i<l.size(); ++i) {
		o << *it << (i<l.size()-1?", ":"");
		++it;
	}
	o << "]";
	return o;
}
/// output-stream for std::vector
template< typename T >
std::ostream& operator<<(std::ostream& o, const std::vector< T >& l) {
	typename std::vector< T >::const_iterator it= l.begin();
	o << "[";
	for(unsigned i= 0; it!=l.end() && i<l.size(); ++i) {
		o << *it << (i<l.size()-1?", ":"");
		++it;
	}
	o << "]";
	return o;
}

/** Basis data container as a map of tag on a value as strings. The container throws an exception, if the tag was not found.
 */
struct Initfile : public std::map< std::string, std::string > {
	typedef std::map< std::string, std::string > super;

	/// Exceptions
    struct TagNotFound : std::invalid_argument {
		TagNotFound(std::string m):std::invalid_argument(m) {}
	};
269
270
271
    struct TagNotFoundBreak : std::invalid_argument { // print 'tag not found' and exit
		TagNotFoundBreak(std::string m):std::invalid_argument(m) {}
	};
Praetorius, Simon's avatar
Praetorius, Simon committed
272
273
274
275
276
		
	/** initialize init-file from file with filename in, read data and save it to singleton-map
	 * @param in: filename string
	 */
	static void init(std::string in);
277
278
279
280
    static void init(int print, string filename, const char *flags = NULL) {
		WARNING("Parameters::init(int,std::string,const char*) is depreciated. Use Parameters::init(std::string) instead!\n");
		init(filename);
	}
Praetorius, Simon's avatar
Praetorius, Simon committed
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
	
	/** Static get routine for getting parameter-values from init-file initialized in init()-method.
	 * Cast the value to the desired type using std::stringstream.
	 * @param tag: The tag to look for
	 * @param value: The result.
	 * @param debug_info: msgInfo for current parameter. (0..no printing, 1..print missing parameter info, 2..print parameter value) [optional]
	 */
	template< typename T >
	static void get(const std::string tag, T& value, int debug_info= -1) {
	using namespace InitfileInternal;
		initIntern();
		if (debug_info==-1)
			debug_info= singlett->getMsgInfo();
		
		try {
			std::string valStr(singlett->checkedGet(tag));
			valStr= trim(valStr);
			convert(valStr, value);
			if (debug_info==2)
				std::cout << "Parameter '" << tag << "' initialized with: " << value << std::endl;
		} catch (TagNotFound ia) {
			if (debug_info>=1)
				std::cout << ia.what() << std::endl;
		}
	}
	/// return InitEntry object for tag tag
	static InitEntry get(const std::string tag) {
	using namespace InitfileInternal;
		int debug_info= singlett->getMsgInfo();
		InitEntry result;
		try {
			std::string valStr(singlett->checkedGet(tag));
			valStr= trim(valStr);
			result= InitEntry(valStr);
		} catch (TagNotFound ia) {
			if (debug_info>=1)
				std::cout << ia.what() << std::endl;
		}
		return result;
	}
	
	/// update map tag->value_old to tag->value in singleton
	template< typename T >
	static void set(const std::string tag, T& value, int debug_info= -1) {
	using namespace InitfileInternal;
		initIntern();
		if (debug_info==-1)
			debug_info= singlett->getMsgInfo();
		
		std::string swap= "";
		convert(value, swap);
		(*singlett)[trim(tag)]= swap;
		// update msg parameters msgInfo, msgWait, paramInfo
		singlett->getInternalParameters();
		if (debug_info==2)
			std::cout << "Parameter '" << tag << "' set to: " << value << std::endl;
	}
	
	/// add map tag->value to data in singleton
	template< typename T >
	static void add(const std::string tag, T& value, int debug_info= -1) {
		set(tag, value, debug_info);
	}

345
346
347
	/// rescheduling parameter
    static void readArgv(int argc, char **argv);

Praetorius, Simon's avatar
Praetorius, Simon committed
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
	/// Returns specified info level
	static int getMsgInfo() 
	{ 
		return (singlett!=NULL) ? singlett->msgInfo : 0; 
	}

	/// Returns specified wait value
	static int getMsgWait() 
	{ 
		return (singlett!=NULL) ? singlett->msgWait : 0; 
	}
	
	/// Checks whether parameters are initialized. if not, call init()
	static bool initialized() 
	{ 
		return (singlett!=NULL); 
	}

	/// return pointer to singleton
	static Initfile *getSingleton() 
	{ 
		return singlett; 
	}
	
	/// print all data in singleton to std::cout
	static void printParameters();

	/// clear data in singleton
	static void clearData()
	{
		initIntern();
		singlett->clear();
	}
	
	/// save singlett-data to file with filename fn
	static void save(std::string fn)
	{
		initIntern();
		singlett->write(fn);
	}
	
protected:	
390
	Initfile() : msgInfo(0), msgWait(1), paramInfo(1), breakOnMissingTag(0) {}
Praetorius, Simon's avatar
Praetorius, Simon committed
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
	
	static void initIntern() {
		if (singlett == NULL)
			singlett= new Initfile;
	}

	/// list of processed files
	static std::set< std::string > fn_include_list;

	/// pointer to the singleton that contains the data
	static Initfile* singlett;
	
	/// return the value of the given tag or throws an exception if the tag does not exist
	std::string checkedGet(const std::string& tag) const {
		super::const_iterator it= find(tag);
406
407
408
409
410
411
		if (it==end()) {
			if(breakOnMissingTag==0 || msgInfo<=2)
				throw TagNotFound("there is no tag '"+ tag + "'");
			else
				throw TagNotFoundBreak("required tag '"+ tag + "' not found");
		}
Praetorius, Simon's avatar
Praetorius, Simon committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
		return it->second;
	}

	/** Fill the initfile from an input stream.
	* @param in: the stream to fill the data from.
	* Current dataformat: tag:value
	* Comment char: percent '%'
	* Include files: #include "filename" or #include <filename>
	*/
	void read(std::istream& in);

	/// Fill the initfile from a file with filename fn
	void read(std::string fn);
	
	/** Write data-map to initfile
	* @param out: the stream to fill the data in.
	*/
	void write(std::ostream& out);

	/// Write data-map to initfile with filename fn
	void write(std::string fn);
	
	/// read parameters for msgInfo, msgWait, paramInfo
	void getInternalParameters();
	
437
	int msgInfo, msgWait, paramInfo, breakOnMissingTag;
Praetorius, Simon's avatar
Praetorius, Simon committed
438
439
	
};
440

441
442
typedef Initfile Parameters;

443
} // end namespace AMDiS
Praetorius, Simon's avatar
Praetorius, Simon committed
444
#endif