Initfile.cc 8.81 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>
27

Praetorius, Simon's avatar
Praetorius, Simon committed
28 29
using namespace std;

30 31
namespace AMDiS {

32 33
  /// the small parser for the initfile. see description of 
  /// read(Initfile&,istream&)
34 35 36 37
  struct Parser {
    Parser(const string& line) 
    {
      size_t pos = line.find(':');
38
      if (pos == string::npos) {
39 40
	throw runtime_error("cannot find the delimiter ':' in line "
			    "'" + line + "'");
41
      }
42 43 44 45 46 47
      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)
48
        value = value.substr(0, pos);      
49 50 51 52 53
    }
    string name;
    string value;
  };

54

55
  Initfile* Initfile::singlett = NULL;
56 57 58 59 60 61 62 63 64 65
  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();
66
  }
67 68 69


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

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


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

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

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

Naumann, Andreas's avatar
Naumann, Andreas committed
150
      getline(in, swap);
151
    }
152
  }
153 154 155 156 157


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

Praetorius, Simon's avatar
Praetorius, Simon committed
176

177
      // if varname is found in parameter list then replace variable by value
178
      // otherwise throw tagNotFound exception
179 180
      std::string varParam;
      int error_code = checkedGet(varName, varParam);
181 182
      if (error_code > 2)
	throw TagNotFoundBreak("required tag '" + varName + "' for variable substitution not found");
183
      
184 185 186
      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
187
      posVar = inputSwap.find_first_of('$',posVarBegin);
188 189 190
    }

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

Praetorius, Simon's avatar
Praetorius, Simon committed
194 195 196 197
  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
198
    size_t posVar = inputSwap.find("$(");
Praetorius, Simon's avatar
Praetorius, Simon committed
199 200
    while (posVar != string::npos) {
      size_t posVarBegin, posVarEnd;
Praetorius, Simon's avatar
Praetorius, Simon committed
201 202
      posVarEnd = inputSwap.find_first_of(')',posVar + 2);
      posVarBegin = posVar + 1;
Praetorius, Simon's avatar
Praetorius, Simon committed
203 204 205
      std::string varName = inputSwap.substr(posVarBegin + 1 , posVarEnd - posVarBegin - 1);

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

      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
212
      posVar = inputSwap.find("$(",posVarBegin);
Praetorius, Simon's avatar
Praetorius, Simon committed
213 214 215 216
    }

    return inputSwap;
  }
217

Praetorius, Simon's avatar
Praetorius, Simon committed
218
  void Initfile::readArgv(std::string parameters, int debugInfo)
219
  {
Praetorius, Simon's avatar
Praetorius, Simon committed
220
    initIntern();
Praetorius, Simon's avatar
Praetorius, Simon committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    
    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
241
      }
242 243 244 245 246 247 248 249 250 251
    }
  }


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

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

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

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

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


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


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


  /// 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
292 293
//     if (!outFile.is_open())
//       throw runtime_error("init-file cannot be opened for writing");
294

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