Initfile.cc 8.91 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) 
  {
88
    const unsigned line_length = 512;
Naumann, Andreas's avatar
Naumann, Andreas committed
89 90 91 92
    //char swap[line_length];
    std::string swap;
    std::getline(in, swap);
    //in.getline(swap, line_length);
93
    while (in.good() || in.gcount() > 0) {
94
      std::string whitespaces = " \t\r\f\n";
95
      std::string delimiter = "\r\n";
96 97
      std::string sw(swap);
      size_t pos0 = sw.find_first_not_of(whitespaces);
98

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

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

Naumann, Andreas's avatar
Naumann, Andreas committed
152 153
      //in.getline(swap, line_length);
      getline(in, swap);
154
    }
155
  }
156 157 158 159 160


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

Praetorius, Simon's avatar
Praetorius, Simon committed
179

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

    return inputSwap;
194
  }
Praetorius, Simon's avatar
Praetorius, Simon committed
195
  
196

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

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

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

    return inputSwap;
  }
220

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


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

256 257 258
    val = 1;
    get("WAIT", val, 0);
    msgWait = val;
259

260 261 262
    val = 1;
    get("parameter information", val, 0);
    paramInfo = val;
263

264 265 266 267 268 269
    val = 0;
    get("break on missing tag", val, 0);
    breakOnMissingTag = val;

    if (msgInfo == 0)
      paramInfo = 0;
270
  }
271 272 273 274 275 276 277


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


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


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

298 299
    write(outFile);
  }
300
} // end namespace AMDiS