Initfile.cc 8.83 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/******************************************************************************
 *
 * AMDiS - Adaptive multidimensional simulations
 *
 * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved.
 * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis
 *
 * Authors: 
 * 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.
 * 
 ******************************************************************************/
Praetorius, Simon's avatar
Praetorius, Simon committed
20
21
22
23
24
25
#include "Initfile.h"

#include <string>
#include <stdexcept>
#include <iostream>
#include <sstream>
Praetorius, Simon's avatar
Praetorius, Simon committed
26
#include<boost/tokenizer.hpp>
Praetorius, Simon's avatar
Praetorius, Simon committed
27
28
using namespace std;

29
30
namespace AMDiS {

31
32
  /// the small parser for the initfile. see description of 
  /// read(Initfile&,istream&)
33
34
35
36
  struct Parser {
    Parser(const string& line) 
    {
      size_t pos = line.find(':');
37
      if (pos == string::npos) {
38
39
	throw runtime_error("cannot find the delimiter ':' in line "
			    "'" + line + "'");
40
      }
41
42
43
44
45
46
      name = line.substr(0, pos);
      value = line.substr(pos + 1, line.length() - (pos + 1));

      // remove everything after the %
      pos = value.find('%');
      if (pos != string::npos)
47
        value = value.substr(0, pos);      
48
49
50
51
52
    }
    string name;
    string value;
  };

53

54
  Initfile* Initfile::singlett = nullptr;
55
56
57
58
59
60
61
62
63
64
  std::set<std::string> Initfile::fn_include_list;


  /// initialize singleton object an global parameters
  void Initfile::init(std::string in)
  {
    initIntern();
    fn_include_list.clear();
    singlett->read(in);	
    singlett->getInternalParameters();
65
  }
66
67
68


  /// Fill an initfile from a file with filename fn
69
  void Initfile::read(std::string fn, bool force)
70
71
  {
    // read file if its not parsed already
72
    if (fn_include_list.find(fn) == fn_include_list.end() || force) {
73
74
      std::ifstream inputFile;
      inputFile.open(fn.c_str(), std::ios::in);
75
76
      if (!inputFile.is_open())
	throw runtime_error("init-file '" + fn + "' cannot be opened for reading");
77

78
79
80
      fn_include_list.insert(fn);
      read(inputFile);
    }
81
  }
82
83
84
85
86


  /// Fill an initfile from an input stream
  void Initfile::read(istream& in) 
  {
87
    const unsigned line_length = 512;
88
89
    char swap[line_length];
    in.getline(swap, line_length);
90
    while (in.good() || in.gcount() > 0) {
91
      std::string whitespaces = " \t\r\f\n";
92
      std::string delimiter = "\r\n";
93
94
      std::string sw(swap);
      size_t pos0 = sw.find_first_not_of(whitespaces);
95

96
97
98
99
      if (pos0 != std::string::npos
          && sw[pos0] != '%' 
          && sw[pos0] != '#'
          && sw[pos0] != 0) {
100
101
        // parse line and extract map: tag->value
        Parser parser(sw);
102
        
103
        // add parameter to map after variable replacement
Praetorius, Simon's avatar
Praetorius, Simon committed
104
105
        std::string paramName = variableReplacement(trim(parser.name));
        std::string paramValue = variableReplacement(trim(parser.value));
Praetorius, Simon's avatar
Praetorius, Simon committed
106
107
        paramValue = variableEvaluation(paramValue);
      
108
109
110
111
        operator[](paramName) = paramValue;
        int info = 0;
        get("parameter information", info, 0);
        if (info >= 2)
112
          std::cout << "read [" << paramName << " => " << paramValue << "]\n";
113
114
115
      } else if (pos0 != std::string::npos &&
		 sw[pos0] == '#'  &&
		 static_cast<size_t>(sw.find("#include")) == pos0) {
116
        // include file by '#include "filename"' or '#include <filename>'
117
118
119
120
121
122
        bool forceRead = false;
        int posAdd = 1;
        if (sw[pos0 + std::string("#include").size()] == '!') {
          forceRead = true;
          posAdd++;
        }
123
        size_t pos = sw.find_first_not_of(whitespaces, 
124
          pos0 + std::string("#include").size() + posAdd);
125
126
127
128
129
130
131
        size_t epos = 0;
        std::string fn =  "";
        std::stringstream errorMsg;
        switch (char c= swap[pos++]) {
          case '<':
            c= '>';
          case '\"':
132
133
            delimiter += c;
            epos = sw.find_first_of(delimiter, pos);
134
135
136
137
            fn = sw.substr(pos, epos - pos);

            if (sw[epos]!=c) {
              errorMsg << "filename in #include not terminated by " << c;
138
	      throw std::runtime_error(errorMsg.str());
139
140
            }
            break;
141
142
	default:
	  throw std::runtime_error("no filename given for #include");
143
        }
144
145
        
        
146
        read(fn, forceRead);
147
      }
148

149
150
      in.getline(swap, line_length);
    }
151
  }
152
153
154
155
156


  std::string Initfile::variableReplacement(const std::string& input) const
  {
    std::string whitespaces = " \t\r\f";
Praetorius, Simon's avatar
Praetorius, Simon committed
157
    std::string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
158
159
160
161
    std::string inputSwap = input; 
    size_t posVar = inputSwap.find_first_of('$');
    while (posVar != string::npos) {
      size_t posVarBegin, posVarEnd;
Praetorius, Simon's avatar
Praetorius, Simon committed
162
      if (inputSwap[posVar+1] == '{') {						// ${var_name}
163
164
        posVarEnd = inputSwap.find_first_of('}',posVar + 2);
        posVarBegin = posVar + 1;
Praetorius, Simon's avatar
Praetorius, Simon committed
165
166
      } else if (inputSwap[posVar+1] != '(' && inputSwap[posVar+1] != '[') {
        posVarEnd = inputSwap.find_first_not_of(allowedChars, posVar + 1);
167
        posVarBegin = posVar;
Praetorius, Simon's avatar
Praetorius, Simon committed
168
169
170
      } else {
	posVar = inputSwap.find_first_of('$',posVar+1);
	continue;
171
      }
Praetorius, Simon's avatar
Praetorius, Simon committed
172
      
173
      std::string varName = inputSwap.substr(posVarBegin + 1 , posVarEnd - posVarBegin - 1);
174

Praetorius, Simon's avatar
Praetorius, Simon committed
175

176
      // if varname is found in parameter list then replace variable by value
177
      // otherwise throw tagNotFound exception
178
179
      std::string varParam;
      int error_code = checkedGet(varName, varParam);
180
181
      if (error_code > 2)
	throw TagNotFoundBreak("required tag '" + varName + "' for variable substitution not found");
182
      
183
184
185
      std::string replaceName = inputSwap.substr(posVar , posVarEnd - posVar + (posVarBegin - posVar));
      inputSwap.replace(inputSwap.find(replaceName), replaceName.length(), varParam);

Praetorius, Simon's avatar
Praetorius, Simon committed
186
      posVar = inputSwap.find_first_of('$',posVarBegin);
187
188
189
    }

    return inputSwap;
190
  }
Praetorius, Simon's avatar
Praetorius, Simon committed
191
  
192

Praetorius, Simon's avatar
Praetorius, Simon committed
193
194
195
196
  std::string Initfile::variableEvaluation(const std::string& input) const
  {
    std::string whitespaces = " \t\r\f";
    std::string inputSwap = input;
Praetorius, Simon's avatar
Praetorius, Simon committed
197
    size_t posVar = inputSwap.find("$(");
Praetorius, Simon's avatar
Praetorius, Simon committed
198
199
    while (posVar != string::npos) {
      size_t posVarBegin, posVarEnd;
Praetorius, Simon's avatar
Praetorius, Simon committed
200
201
      posVarEnd = inputSwap.find_first_of(')',posVar + 2);
      posVarBegin = posVar + 1;
Praetorius, Simon's avatar
Praetorius, Simon committed
202
203
204
      std::string varName = inputSwap.substr(posVarBegin + 1 , posVarEnd - posVarBegin - 1);

      double value = 0.0;
Praetorius, Simon's avatar
Praetorius, Simon committed
205
206
      details::convert(varName, value); // string -> double (using muparser)
      details::convert(value, varName); // double -> string
Praetorius, Simon's avatar
Praetorius, Simon committed
207
208
209
210

      std::string replaceName = inputSwap.substr(posVar , posVarEnd - posVar + (posVarBegin - posVar));
      inputSwap.replace(inputSwap.find(replaceName), replaceName.length(), varName);

Praetorius, Simon's avatar
Praetorius, Simon committed
211
      posVar = inputSwap.find("$(",posVarBegin);
Praetorius, Simon's avatar
Praetorius, Simon committed
212
213
214
215
    }

    return inputSwap;
  }
216

Praetorius, Simon's avatar
Praetorius, Simon committed
217
  void Initfile::readArgv(std::string parameters, int debugInfo)
218
  {
Praetorius, Simon's avatar
Praetorius, Simon committed
219
    initIntern();
Praetorius, Simon's avatar
Praetorius, Simon committed
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
    
    char seperator = ';';
    typedef boost::escaped_list_separator<char> TokenizerFunc;
    typedef boost::tokenizer<TokenizerFunc> Tokenizer;
    TokenizerFunc tokenizerFunc('\\', seperator, '\"');
    Tokenizer tok(parameters, tokenizerFunc);

    // split parameterstring by seperator ";"
    std::vector<std::string> val;
    for (Tokenizer::iterator cell = tok.begin(); cell != tok.end(); ++cell) {
      val.push_back(trim(*cell));
    }
    
    // split each parameter by ":"
    for (size_t i = 0; i < val.size(); i++) {
      int found = val[i].find_first_of(':');
      if (found != static_cast<int>(std::string::npos)) {
	std::string value = trim(val[i].substr(found+1));
	std::string key = trim(val[i].substr(0, found));
	set(key, value, debugInfo);
Praetorius, Simon's avatar
Praetorius, Simon committed
240
      }
241
242
243
244
245
246
247
248
249
250
    }
  }


  /// read standard values for output and information of parameter-values
  void Initfile::getInternalParameters() 
  {
    int val = 0;
    get("level of information", val, 0);
    msgInfo = val;
251

252
253
254
    val = 1;
    get("WAIT", val, 0);
    msgWait = val;
255

256
257
258
    val = 1;
    get("parameter information", val, 0);
    paramInfo = val;
259

260
261
262
263
264
265
    val = 0;
    get("break on missing tag", val, 0);
    breakOnMissingTag = val;

    if (msgInfo == 0)
      paramInfo = 0;
266
  }
267
268
269
270
271
272
273


  /// print all parameters to std::cout
  void Initfile::printParameters() 
  {
    initIntern();
    for (Initfile::iterator it = singlett->begin(); it != singlett->end(); it++)
274
      std::cout << (*it).first << " => " << (*it).second << std::endl;
275
  }
276
277
278
279
280
281


  /// Write data-map to initfile
  void Initfile::write(ostream& out)
  {
    for (Initfile::iterator it = begin() ; it!=end(); it++)
282
      out << (*it).first << ": " << (*it).second << std::endl;	
283
284
285
286
287
288
289
290
  }


  /// Write data-map to initfile
  void Initfile::write(std::string fn) 
  {
    std::ofstream outFile;
    outFile.open(fn.c_str(), std::ios::out);
Thomas Witkowski's avatar
Thomas Witkowski committed
291
292
//     if (!outFile.is_open())
//       throw runtime_error("init-file cannot be opened for writing");
293

294
295
    write(outFile);
  }
296
} // end namespace AMDiS