Initfile.h 19.1 KB
Newer Older
1
2
3
4
5
6
7
/******************************************************************************
 *
 * AMDiS - Adaptive multidimensional simulations
 *
 * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.
 * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis
 *
8
 * Authors:
9
10
11
12
13
14
15
16
17
 * Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al.
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 *
 * This file is part of AMDiS
 *
 * See also license.opensource.txt in the distribution.
18
 *
19
 ******************************************************************************/
20

Praetorius, Simon's avatar
Praetorius, Simon committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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"

36
37
#include "traits/size.hpp"

Praetorius, Simon's avatar
Praetorius, Simon committed
38
#include <boost/lexical_cast.hpp>
39
#include <boost/numeric/conversion/cast.hpp>
40

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

43
44
namespace AMDiS {

45
  namespace detail {
46

47
48
    // Exceptions
    //_________________________________________________________________________________________
49

50
    /// Exception for wrong vector size when parsing for concrete vector type
Praetorius, Simon's avatar
Praetorius, Simon committed
51
    struct WrongVectorSize : std::runtime_error {
Praetorius, Simon's avatar
Praetorius, Simon committed
52
      WrongVectorSize(std::string m) : std::runtime_error(m) {}
53
54
    };

55

56
    /// Exception for no delimiter found in vector
Praetorius, Simon's avatar
Praetorius, Simon committed
57
    struct NoDelim : std::runtime_error {
Praetorius, Simon's avatar
Praetorius, Simon committed
58
      NoDelim(std::string m) : std::runtime_error(m) {}
59
60
    };

61

62
    /// Exception for begin and end brackets are different in vector
Praetorius, Simon's avatar
Praetorius, Simon committed
63
    struct WrongVectorFormat : std::runtime_error {
Praetorius, Simon's avatar
Praetorius, Simon committed
64
      WrongVectorFormat(std::string m) : std::runtime_error(m) {}
65
    };
66
67


68
    /// Exception for wrong value format
69
    template<typename T>
70
71
    struct WrongValueFormat : std::runtime_error
    {
Praetorius, Simon's avatar
Praetorius, Simon committed
72
73
74
75
76
      static std::string name(bool) { return "bool"; }
      static std::string name(double) { return "double"; }
      static std::string name(float) { return "float"; }
      static std::string name(int) { return "int"; }
      static std::string name(unsigned int) { return "unsigned int"; }
77
78

      template<typename G>
79
80
81
      static std::string name(G)
      {
        return std::string(typeid(G).name());
82
      }
83

84
      WrongValueFormat(std::string value)
Praetorius, Simon's avatar
Praetorius, Simon committed
85
      : std::runtime_error("cannot convert '" + value + "' into <" + name(T()) + ">")
86
87
      {}
    };
88

Praetorius, Simon's avatar
Praetorius, Simon committed
89

90
    /// Exception for bad arithmetic expression that can not be evaluated
91
    template<typename T>
92
    struct BadArithmeticExpression : std::runtime_error
93
    {
Praetorius, Simon's avatar
Praetorius, Simon committed
94
95
96
97
98
      static std::string name(bool) { return "bool"; }
      static std::string name(double) { return "double"; }
      static std::string name(float) { return "float"; }
      static std::string name(int) { return "int"; }
      static std::string name(unsigned int) { return "unsigned int"; }
99

100
      template<typename G>
101
102
      static std::string name(G)
      {
103
        return std::string(typeid(G).name());
104
      }
105

106
      BadArithmeticExpression(std::string m, std::string value)
Praetorius, Simon's avatar
Praetorius, Simon committed
107
108
      : std::runtime_error("cannot evaluate expression '" + value + "' into <" + name(T()) + ">\n"
			   "Parser message: '" + m + "'")
109
110
      {}
    };
111

112
// _____________________________________________________________________________
113

114
    /// return the delimiter or throw an exception if there is no known
115
    /// delimiter in value
116
117
118
    inline size_t checkDelim(const std::string& value, const std::string& delims)
    {
      size_t pos(std::string::npos);
Praetorius, Simon's avatar
Praetorius, Simon committed
119
      for (size_t i = 0; i < delims.length(); i++) {
120
121
122
        pos = value.find(delims[i]);
        if (pos != std::string::npos)
          return i;
123
      }
Thomas Witkowski's avatar
Thomas Witkowski committed
124
      //      throw NoDelim("cannot detect the delimiter in " + value);
125
      return 0;
126
    }
127
128


129
    double mu_parser_eval(std::string const& valStr);
130
131
132


    /// convert string to string
133
    inline void convert(const std::string valStr, std::string& value)
134
135
136
137
138
139
    {
      value = trim(valStr);
    }


    /// convert string to intrinsic type
140
141
142
    template<typename T> inline
    typename boost::enable_if
	     < boost::mpl::and_
143
144
	       < boost::is_pod<T>,
	         boost::mpl::not_< boost::is_enum<T> > >,
145
146
147
	       void
	     >::type
    convert(const std::string valStr, T& value)
148
149
150
151
    {
      using boost::lexical_cast;
      using boost::numeric_cast;

152
      value = numeric_cast< T >(mu_parser_eval(valStr));
Thomas Witkowski's avatar
Thomas Witkowski committed
153
154
155
156
157
158
159
/*       } catch (boost::bad_lexical_cast e) { */
/*         throw WrongValueFormat< T >(valStr); */
/*       } catch (boost::bad_numeric_cast e) { */
/*         throw WrongValueFormat< T >(valStr); */
/*       } catch (mu::Parser::exception_type &e) { */
/*         throw BadArithmeticExpression<T>(e.GetMsg(), valStr); */
/*       } */
160
161
162
    }


163
164
    template<typename T> inline
    typename boost::enable_if
165
	     < boost::is_enum<T>,
166
167
	       void
	     >::type
168
    convert(const std::string valStr, T& value)
169
    {
170
      int swap = 0;
Thomas Witkowski's avatar
Thomas Witkowski committed
171
      //      try {
172
        swap = boost::lexical_cast<int>(trim(valStr));
Thomas Witkowski's avatar
Thomas Witkowski committed
173
174
175
/*       } catch (boost::bad_lexical_cast e) { */
/*         throw WrongValueFormat< T >(valStr); */
/*       } */
176
177
178
179
      value = static_cast< T >(swap);
    }


180
    /// convert special enums
181
    inline void convert(const std::string valStr, Norm& value)
182
183
184
185
186
187
188
189
190
191
    {
      std::string swapStr = boost::to_upper_copy(valStr);

      if (swapStr == "NO_NORM")
        value = static_cast< Norm >(NO_NORM);
      else if (swapStr == "H1_NORM")
        value = static_cast< Norm >(H1_NORM);
      else if (swapStr == "L2_NORM")
        value = static_cast< Norm >(L2_NORM);
      else {
Praetorius, Simon's avatar
Praetorius, Simon committed
192
        int swap = 0;
193
194
195
196
197
198
        convert(valStr, swap);
        value = static_cast< Norm >(swap);
      }
    }


199
    /// convert value of arbitrary type to string using stringstream and
Naumann, Andreas's avatar
Naumann, Andreas committed
200
201
    /// operator<< for type
    template<typename T>
202
    inline void convert(const T value, std::string& valStr)
Naumann, Andreas's avatar
Naumann, Andreas committed
203
204
205
206
207
208
209
210
211
    {
      std::stringstream ss;
      ss.precision(6);
      ss << value;
      valStr = ss.str();
    }


    /// convert WorldVector to string
212
213
    // TODO: allgemeine Funktion zum Schreiben von Vektoren implementieren
    //       unter Ausnutzung von Type-Traits
Naumann, Andreas's avatar
Naumann, Andreas committed
214
215
216
    template<typename T>
    inline void convert(const WorldVector<T>& c, std::string& valStr)
    {
217
218
      std::vector<T> temp_vec(size(c));
      for (unsigned i = 0; i < size(temp_vec); i++)
Naumann, Andreas's avatar
Naumann, Andreas committed
219
220
221
222
        temp_vec[i] = c[i];
      convert(temp_vec, valStr);
    }

223
    // forward declarations
Thomas Witkowski's avatar
Thomas Witkowski committed
224
225
226
227
228
229
230
231
232
    template< typename T >
    inline void convert(const std::string valStr, WorldVector<T>& c);

    template<typename T>
    inline void convert(const std::string valStr, std::list<T>& value);

    template<typename T>
    inline void convert(const std::string valStr, std::vector<T>& value);

Naumann, Andreas's avatar
Naumann, Andreas committed
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
    /** 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_);
      bool hasBrackets = true;
      size_t pos = begBrackets.find(val[0]);
      if (pos == std::string::npos)
        hasBrackets = false;
251
252
       if (hasBrackets && val[val.length() - 1] != endBrackets[pos])
        throw WrongVectorFormat("begin and end bracket are different in"
253
            " value '" + val + "'");
Naumann, Andreas's avatar
Naumann, Andreas committed
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
      size_t oldPos = (hasBrackets ? 1 : 0);
      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) {
          std::string curWord = val.substr(oldPos, pos - oldPos);
          oldPos = pos + 1;
          convert(curWord, swap);
          c.push_back(swap);
          pos = val.find(delims[curDelim], oldPos);
        }
        //last entry
        std::string curWord = val.substr(oldPos, val.length() - (hasBrackets ? 1 : 0) - oldPos);
        convert(curWord, swap);
        c.push_back(swap);
      } catch (NoDelim nd) {
        std::string curWord = val.substr(oldPos, val.length() - (hasBrackets ? 2 : 0));
        curWord = trim(curWord);
        if (curWord.length() > 0) {
          // container with one entry
          convert(curWord, swap);
          c.push_back(swap);
        }
      }
    }

283
284
    // TODO: Verallgemeinerung der convert-method für bel. Vektoren und
    //       hinzunahme der Möglichkeit Matrizen anzugeben
Naumann, Andreas's avatar
Naumann, Andreas committed
285

286
287
    /// convert string to WorldVector
    template< typename T >
288
    inline void convert(const std::string valStr, WorldVector<T>& c)
289
290
291
    {
      std::vector<T> temp_vec;
      getContainer(valStr, temp_vec);
292
       if (static_cast<int>(temp_vec.size()) != c.getSize())
293
294
        throw WrongVectorSize("wrong number of entries for WorldVector");

Praetorius, Simon's avatar
Praetorius, Simon committed
295
      for (size_t i = 0; i < temp_vec.size(); i++)
296
        c[i] = temp_vec[i];
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
    }

    /// 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);
    }


315
  } // end namespace detail
Praetorius, Simon's avatar
Praetorius, Simon committed
316

317
// _____________________________________________________________________________
Praetorius, Simon's avatar
Praetorius, Simon committed
318

319
  /** The entry in an initfile. This helper class was constructed to allow calls
320
321
322
  *  like val = data.get(tag) for arbitrary types of val. At current stage, only
  *  double and bool is supported
  */
323
324
325
326
327
328
  struct InitEntry {
    ///the value as string
    std::string valStr;

    /// initialize with value as string
    InitEntry(std::string v = "")
329
    : valStr(v)
330
331
332
333
    {}

    /// cast string to type T
    template<typename T>
334
335
336
337
    operator T() const
    {
      T t;
      detail::convert(valStr, t);
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
      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;
  }

372
// _____________________________________________________________________________
373

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

381
382
    static const int TAG_NOT_FOUND = 1;
    static const int TAG_NOT_FOUND_BREAK = 2;
383

384
    /// Exceptions
Praetorius, Simon's avatar
Praetorius, Simon committed
385
    struct TagNotFound : std::invalid_argument {
386
387
      TagNotFound(std::string m)
      : std::invalid_argument(m)
388
389
390
      {}
    };

391
392
393

    struct TagNotFoundBreak : std::invalid_argument {
    // print 'tag not found' and exit
394
      TagNotFoundBreak(std::string m)
395
      : std::invalid_argument(m)
396
397
      {}
    };
398
399


400
    /** initialize init-file from file with filename in, read data and save it
401
402
403
    *  to singleton-map
    *  @param in: filename string
    */
404
405
    static void init(std::string in);

406
    static void init(int print, std::string filename, const char *flags = NULL)
407
    {
408
409
410
        WARNING("Parameters::init(int,std::string,const char*) is depreciated. "
          "Use Parameters::init(std::string) instead!\n");
        init(filename);
411
    }
412
413


414
    /** Static get routine for getting parameter-values from init-file
415
416
417
418
419
420
421
    *  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 debugInfo: msgInfo for current parameter. (0..no printing,
    *    1..print missing parameter info, 2..print parameter value) [optional]
    */
422
423
424
425
426
    template<typename T>
    static void get(const std::string tag, T& value, int debugInfo = -1)
    {
      initIntern();
      if (debugInfo == -1)
427
        debugInfo = singlett->getMsgInfo();
428
429
430
431
432
      else {
	int swap(debugInfo);
	debugInfo = singlett->getMsgInfo();
	singlett->msgInfo=swap;
      }
433

434
      std::string valStr;
435
      try {
436
437
438
      int error_code = singlett->checkedGet(tag, valStr);
      if (error_code == 0) {
	valStr = trim(valStr);
439
	detail::convert(valStr, value);
440
      }
441
      else if(error_code == TAG_NOT_FOUND_BREAK)
442
	throw TagNotFoundBreak("required tag '" + tag + "' not found");
443
444
445
446
      else if (error_code == TAG_NOT_FOUND) {
	if (debugInfo == 2)
	  std::cout << "there is no tag '" + tag + "'" << std::endl;
      } else
Praetorius, Simon's avatar
Praetorius, Simon committed
447
	throw std::runtime_error("unknown error_code (" + boost::lexical_cast<std::string>(error_code) + ") returned for tag '" + tag + "'");
Thomas Witkowski's avatar
Thomas Witkowski committed
448

449
      } catch(...) {
450
451
452
	std::string parser_error = "Could not parse: " + tag;
	throw std::runtime_error(parser_error);
      }
453
454
455
      if (debugInfo == 2) {
	std::cout << "Parameter '" << tag << "'"
		  << " initialized with: " << value << std::endl;
456
      }
457
      singlett->msgInfo = debugInfo;
458
459
    }

460

461
    /** Static get routine for getting a parameter-map from init-file
462
    *  initialized in init()-method.
463
    *  Idea:
464
465
    *     line in Initfile: <tag><key>: <value>
    *     is extracted in am map [key]->[value].
466
    *  @param tag: The tag withch labels the parameter map
467
468
469
    *  @param debugInfo: msgInfo for current parameter. (0..no printing,
    *    2..print parameter value) [optional]
    */
470
    static void getParameterMap(const std::string tag,
471
472
473
474
				std::map<std::string,std::string> &pm,
				int debugInfo = -1)
    {
	initIntern();
475
	for (Initfile::iterator it = singlett->begin(); it != singlett->end(); it++){
476
477
	    std::string longTag= (*it).first ;
	    std::string value=(*it).second;
478
	    if(longTag.length()>tag.length() &&
479
	       longTag.compare(0,tag.length(),tag)==0){
480
		if (debugInfo == 2){
481
		  std::cout <<"tag "<< tag <<"\n";
482
		  std::cout <<"Extract Parameter map from "<<(*it).first
483
			    << " => " <<(*it).second  << std::endl;
484
		}
485

486
		std::string key=trim(longTag.substr(tag.length()));
487

488
		if (debugInfo == 2){
489
		  std::cout <<"Parameter map "<< key << " => "
490
			    << value << std::endl;
491
492
493
		}
		pm[key]=value;
	    }
494
	}
495
    }
496

497
    /// return InitEntry object for tag tag
498
    static InitEntry get(const std::string tag)
499
500
    {
      InitEntry result;
501

502
503
504
505
506
      std::string valStr;
      int error_code = singlett->checkedGet(tag, valStr);
      if (error_code == 0) {
	valStr = trim(valStr);
	result = InitEntry(valStr);
507
      }
Thomas Witkowski's avatar
Thomas Witkowski committed
508
509
510

#if 0
else if(error_code == TAG_NOT_FOUND_BREAK)
511
	throw TagNotFoundBreak("get(): required tag '" + tag + "' not found");
512
      else if (error_code == TAG_NOT_FOUND)
513
	throw TagNotFound("get(): there is no tag '" + tag + "'");
Praetorius, Simon's avatar
Praetorius, Simon committed
514
	// exception must be thrown, because an empty object would be return otherwise
515
      else
516
	throw std::runtime_error("get(): unknown error_code returned for tag '" + tag + "'");
Thomas Witkowski's avatar
Thomas Witkowski committed
517
518
#endif

519
520
      return result;
    }
521

522
523
524

    /// update map tag->value_old to tag->value in singleton
    template<typename T>
525
    static void set(const std::string tag, T& value, int debugInfo=  -1)
526
527
528
    {
      initIntern();
      if (debugInfo == -1)
529
530
        debugInfo = singlett->getMsgInfo();

531
      std::string swap = "";
532
      detail::convert(value, swap);
533
534
535
536
      (*singlett)[trim(tag)] = swap;
      // update msg parameters msgInfo, msgWait, paramInfo
      singlett->getInternalParameters();
      if (debugInfo == 2)
537
538
        std::cout << "Parameter '" << tag << "'"
                  << " set to: " << value << std::endl;
539
    }
540
541


542
543
    /// add map tag->value to data in singleton
    template< typename T >
544
    static void add(const std::string tag, T& value, int debugInfo = -1)
545
546
547
548
    {
      set(tag, value, debugInfo);
    }

549

550
    /// rescheduling parameter
Praetorius, Simon's avatar
Praetorius, Simon committed
551
    static void readArgv(std::string parameters, int debugInfo = 2);
552

553

554
    /// Returns specified info level
555
556
557
    static int getMsgInfo()
    {
      return (singlett != NULL) ? singlett->msgInfo : 0;
558
559
    }

560

561
    /// Returns specified wait value
562
563
564
    static int getMsgWait()
    {
      return (singlett != NULL) ? singlett->msgWait : 0;
565
    }
566
567


568
    /// Checks whether parameters are initialized. if not, call init()
569
570
571
    static bool initialized()
    {
      return (singlett != NULL);
572
573
    }

574

575
    /// return pointer to singleton
576
577
578
    static Initfile *getSingleton()
    {
      return singlett;
579
    }
580
581


582
583
584
    /// print all data in singleton to std::cout
    static void printParameters();

585

586
587
588
589
590
591
    /// clear data in singleton
    static void clearData()
    {
      initIntern();
      singlett->clear();
    }
592
593


594
595
596
597
598
599
    /// save singlett-data to file with filename fn
    static void save(std::string fn)
    {
      initIntern();
      singlett->write(fn);
    }
600

601
602
603
    static std::set< std::string > getIncludeList(){
      return fn_include_list;
    }
604
605
606
607
608
609
protected:
    Initfile()
    : msgInfo(0),
      msgWait(1),
      paramInfo(1),
      breakOnMissingTag(0)
610
    {}
611
612


613
    static void initIntern()
614
    {
615
      if (singlett == NULL)
Praetorius, Simon's avatar
Praetorius, Simon committed
616
	singlett = new Initfile;
617
    }
Praetorius, Simon's avatar
Praetorius, Simon committed
618

619

620
621
    /// list of processed files
    static std::set< std::string > fn_include_list;
Praetorius, Simon's avatar
Praetorius, Simon committed
622

623

624
625
    /// pointer to the singleton that contains the data
    static Initfile* singlett;
626
627


628
    /// return the value of the given tag or throws an exception if the tag
629
    /// does not exist
630
    int checkedGet(const std::string& tag, std::string &valStr) const
631
632
633
    {
      super::const_iterator it = find(tag);
      if (it == end()) {
634
        if (breakOnMissingTag == 0 || msgInfo <= 2)
635
	  return TAG_NOT_FOUND;
636
        else
637
	  return TAG_NOT_FOUND_BREAK;
638
      }
639
640
      valStr = it->second;
      return 0;
641
642
    }

643
644
645
646
647
    /// replace variables by its value defined as parameter previousely
    /// variable definition is simple parameter definition
    /// variable evaluation by ${variablename} or $variablename
    /// the last version only for variablenames without whitespaces
    std::string variableReplacement(const std::string& input) const;
648

Praetorius, Simon's avatar
Praetorius, Simon committed
649
    std::string variableEvaluation(const std::string& input) const;
650

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

    /// Fill the initfile from a file with filename fn
660
    void read(std::string fn, bool force = false);
661

662
    /** Write data-map to initfile
663
664
    * @param out: the stream to fill the data in.
    */
665
    void write(std::ostream& out);
Praetorius, Simon's avatar
Praetorius, Simon committed
666

667
668
    /// Write data-map to initfile with filename fn
    void write(std::string fn);
669

670
671
    /// read parameters for msgInfo, msgWait, paramInfo
    void getInternalParameters();
672

673
    int msgInfo, msgWait, paramInfo, breakOnMissingTag;
674
  };
675

676
  typedef Initfile Parameters;
677

678
} // end namespace AMDiS
Praetorius, Simon's avatar
Praetorius, Simon committed
679
#endif