OpalSimulation.cpp 13.2 KB
Newer Older
adelmann's avatar
adelmann committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
#include <iostream>
#include <sstream>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <dirent.h>
#include <cstdlib>
#include <vector>

#include "Simulation/OpalSimulation.h"

#include "Util/SDDSReader.h"
#include "Util/OptPilotException.h"
#include "Util/HashNameGenerator.h"

#include "Expression/SumErrSq.h"
#include "Expression/FromFile.h"

#include "boost/variant.hpp"
#include "boost/smart_ptr.hpp"
#include "boost/algorithm/string.hpp"

#ifdef BOOST_FILESYSTEM
    #include "boost/filesystem/operations.hpp"
#endif

// access to OPAL lib
adelmann's avatar
adelmann committed
30
#include "opal.h"
adelmann's avatar
adelmann committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#include "Utilities/OpalException.h"
#include "Utilities/Options.h"


OpalSimulation::OpalSimulation(Expressions::Named_t objectives,
                               Expressions::Named_t constraints,
                               Param_t params, std::string name,
                               MPI_Comm comm, CmdArguments_t args)
               : Simulation(args)
               , objectives_(objectives)
               , constraints_(constraints)
               , comm_(comm)
{
    if(getenv("SIMTMPDIR") == NULL) {
        std::cout << "Environment variable SIMTMPDIR not defined!"
                  << std::endl;
        simTmpDir_ = getenv("PWD");
    } else
        simTmpDir_ = getenv("SIMTMPDIR");
    simulationName_ = name;

    // prepare design variables given by the optimizer for generating the
    // input file
    std::vector<std::string> dict;
55
    for(auto parameter : params) {
adelmann's avatar
adelmann committed
56 57
        std::ostringstream tmp;
        tmp.precision(15);
58
        tmp << parameter.first << "=" << parameter.second;
adelmann's avatar
adelmann committed
59 60 61 62
        dict.push_back(tmp.str());

        std::ostringstream value;
        value.precision(15);
63
        value << parameter.second;
adelmann's avatar
adelmann committed
64
        userVariables_.insert(
65
            std::pair<std::string, std::string>(parameter.first, value.str()));
adelmann's avatar
adelmann committed
66 67 68 69 70 71 72 73 74 75 76
    }


    int my_rank=0;
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);

    // hash the dictionary to get a short unique directory name for temporary
    // simulation data
    std::string hash = HashNameGenerator::generate(dict);
    std::ostringstream tmp;
    tmp.precision(15);
77
    tmp << simTmpDir_ << "/" << hash ; // ADA << "_" << my_rank;
adelmann's avatar
adelmann committed
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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    simulationDirName_ = tmp.str();

    if(getenv("TEMPLATES") == NULL) {
        throw OptPilotException("OpalSimulation::OpalSimulation",
            "Environment variable TEMPLATES not defined!");
    }
    std::string tmplDir = getenv("TEMPLATES");
    std::string tmplFile = tmplDir + "/" + simulationName_ + ".tmpl";
    // data file is assumed to be located in the root directory
    std::string dataFile = simulationName_ + ".data";
    gs_.reset(new GenerateOpalSimulation(tmplFile, dataFile, userVariables_));
}


OpalSimulation::~OpalSimulation() {
    requestedVars_.clear();
    userVariables_.clear();
}


bool OpalSimulation::hasResultsAvailable() {

    std::string infile = simulationDirName_ + "/" + simulationName_ + ".in";
    struct stat fileInfo;

    if(stat(infile.c_str(), &fileInfo) == 0) {
        std::cout << "-> Simulation input file (" << infile
                  << ") already exist from previous run.." << std::endl;
        return true;
    }

    return false;
}


void OpalSimulation::setupSimulation() {

    // only on processor in comm group has to setup files
    int rank = 0;
    MPI_Comm_rank(comm_, &rank);
    if(rank == 0) {

        mkdir((const char*)(simulationDirName_.c_str()), 0777);

        std::string infile = simulationDirName_ + "/" +
                             simulationName_ + ".in";
        gs_->writeInputFile(infile);

        // linking fieldmaps
        if(getenv("FIELDMAPS") == NULL) {
            throw OptPilotException("OpalSimulation::OpalSimulation",
                "Environment variable FIELDMAPS not defined!");
        }
        std::string fieldmapPath = getenv("FIELDMAPS");
132
	
adelmann's avatar
adelmann committed
133 134
        struct dirent **files;
        int count = scandir(fieldmapPath.c_str(), &files, 0, alphasort);
135

adelmann's avatar
adelmann committed
136
        for(int i=0; i<count; i++) {
kraus's avatar
kraus committed
137 138
            if (files[i]->d_name == std::string(".") ||
                files[i]->d_name == std::string("..")) continue;
adelmann's avatar
adelmann committed
139 140
            std::string source = fieldmapPath + "/" + files[i]->d_name;
            std::string target = simulationDirName_ + '/' + files[i]->d_name;
141 142 143 144 145 146 147 148 149 150 151
	    int err = symlink(source.c_str(), target.c_str());
	    if (err != 0) {
	      // FIXME properly handle error
	      std::cout << "Cannot symlink fieldmap "
			<< source.c_str() << " to "
			<< target.c_str() << " error no " << err << std::endl;
	      std::cout << "fieldmapPath " << fieldmapPath << " i= " << i << std::endl;
	      std::cout << "target       " << simulationDirName_ + '/' + files[i]->d_name << std::endl;

	    }
	}
adelmann's avatar
adelmann committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    }

    MPI_Barrier(comm_);
}


void OpalSimulation::redirectOutToFile() {

    // backup stdout and err file handles
    strm_buffer_ = std::cout.rdbuf();
    strm_err_ = std::cerr.rdbuf();

    int world_pid = 0;
    MPI_Comm_rank(MPI_COMM_WORLD, &world_pid);

    std::ostringstream fname;
    fname << "sim.out." << world_pid;
    std::ofstream file(fname.str().c_str());
    fname << ".err";
    std::ofstream err(fname.str().c_str());

    // and redirect stdout and err to new files
    std::cout.rdbuf(file.rdbuf());
    std::cerr.rdbuf(err.rdbuf());
}


void OpalSimulation::restoreOut() {
    std::cout.rdbuf(strm_buffer_);
    std::cerr.rdbuf(strm_err_);
}


void OpalSimulation::run() {
186
  
adelmann's avatar
adelmann committed
187 188 189 190 191 192 193 194 195
    // make sure input file is not already existing
    MPI_Barrier(comm_);
    if( hasResultsAvailable() ) return;
    MPI_Barrier(comm_);

    setupSimulation();

    pwd_ = getenv("PWD");
    pwd_ += "/";
196
    int err = chdir(simulationDirName_.c_str());
197

198 199 200
    if (err != 0) {
        std::cout << "Cannot chdir to "
                  << simulationDirName_.c_str() << std::endl;
201
        std::cout << "Continuing 1, disregarding this simulation.."
202 203 204
                  << std::endl;
        return;
    }
adelmann's avatar
adelmann committed
205 206 207 208 209 210 211 212 213 214 215 216 217

    // setup OPAL command line options
    std::ostringstream inputFileName;
    inputFileName << simulationName_ << ".in";

    char exe_name[] = "opal";
    char *inputfile = new char[inputFileName.str().size()+1] ;
    strcpy(inputfile, inputFileName.str().c_str());
    char nocomm[] = "--nocomminit";
    char info[] = "--info";
    char info0[] = "0";
    char warn[] = "--warn";
    char warn0[] = "0";
218
    char *arg[] = { exe_name, inputfile, nocomm, info, info0, warn, warn0 };
adelmann's avatar
adelmann committed
219 220

    int seed = Options::seed;
221

adelmann's avatar
adelmann committed
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
    try {

        //FIXME: this seems to crash OPAL in some cases
        //redirectOutToFile();
#ifdef SUPRESS_OUTPUT
        //XXX: hack to disable output to stdout and stderr
        std::cout.setstate(std::ios::failbit);
        // std::cerr.setstate(std::ios::failbit);
#endif

        // now we can run the simulation
        run_opal(arg, inputFileName.str(), -1, comm_);

        //restoreOut();
#ifdef SUPRESS_OUTPUT
        std::cout.clear();
        std::cerr.clear();
#endif

    } catch(OpalException *ex) {

        //restoreOut();
#ifdef SUPRESS_OUTPUT
        std::cout.clear();
        std::cerr.clear();
#endif

        std::cout << "Opal exception during simulation run: "
                  << ex->what() << std::endl;
251
        std::cout << "Continuing 2, disregarding this simulation.."
adelmann's avatar
adelmann committed
252 253 254 255 256 257 258 259 260 261 262 263
                  << std::endl;

    } catch(ClassicException *ex) {

        //restoreOut();
#ifdef SUPRESS_OUTPUT
        std::cout.clear();
        std::cerr.clear();
#endif

        std::cout << "Classic exception during simulation run: "
                  << ex->what() << std::endl;
264
        std::cout << "Continuing 3, disregarding this simulation.."
adelmann's avatar
adelmann committed
265 266 267 268 269 270
                  << std::endl;
    }

    Options::seed = seed;

    delete[] inputfile;
271 272 273 274 275
    err = chdir(pwd_.c_str());
    if (err != 0) {
        std::cout << "Cannot chdir to "
                  << simulationDirName_.c_str() << std::endl;
    }
adelmann's avatar
adelmann committed
276 277 278 279 280 281 282 283
}


void OpalSimulation::collectResults() {

    // clear old solutions
    requestedVars_.clear();

284 285 286 287 288 289 290 291 292
    int err = chdir(simulationDirName_.c_str());
    if (err != 0) {
        std::cout << "Cannot chdir to "
                  << simulationDirName_.c_str() << std::endl;
        std::cout << "Continuing, with cleanup.."
                  << std::endl;
        cleanUp();
        return;
    }
adelmann's avatar
adelmann committed
293 294 295 296 297 298 299 300 301

    std::string fn = simulationName_ + ".stat";
    struct stat fileInfo;

    // if no stat file, simulation parameters produced invalid bunch
    if(stat(fn.c_str(), &fileInfo) != 0) {
        invalidBunch();
    } else {

302
        for(auto namedObjective : objectives_) {
adelmann's avatar
adelmann committed
303

304
            Expressions::Expr_t *objective = namedObjective.second;
adelmann's avatar
adelmann committed
305 306 307 308

            // find out which variables we need in order to evaluate the
            // objective
            variableDictionary_t variable_dictionary;
309 310
            bool check = getVariableDictionary(variable_dictionary,fn,objective);
            if (check == false) break;
adelmann's avatar
adelmann committed
311 312 313 314 315 316 317 318 319 320 321 322

            // and evaluate the expression using the built dictionary of
            // variable values
            Expressions::Result_t result =
                objective->evaluate(variable_dictionary);

            std::vector<double> values;
            values.push_back(boost::get<0>(result));
            bool is_valid = boost::get<1>(result);

            reqVarInfo_t tmps = {EVALUATE, values, is_valid};
            requestedVars_.insert(
323
                std::pair<std::string, reqVarInfo_t>(namedObjective.first, tmps));
adelmann's avatar
adelmann committed
324 325 326 327

        }

        // .. and constraints
328
        for(auto namedConstraint : constraints_) {
adelmann's avatar
adelmann committed
329

330
            Expressions::Expr_t *constraint = namedConstraint.second;
adelmann's avatar
adelmann committed
331 332 333 334

            // find out which variables we need in order to evaluate the
            // objective
            variableDictionary_t variable_dictionary;
335 336
            bool check = getVariableDictionary(variable_dictionary,fn,constraint);
            if (check == false) break;
adelmann's avatar
adelmann committed
337 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

            Expressions::Result_t result =
                constraint->evaluate(variable_dictionary);

            std::vector<double> values;
            values.push_back(boost::get<0>(result));
            bool is_valid = boost::get<1>(result);

            //FIXME: hack to give feedback about values of LHS and RHS
            std::string constr_str = constraint->toString();
            std::vector<std::string> split;
            boost::split(split, constr_str, boost::is_any_of("<>!="),
                        boost::token_compress_on);
            std::string lhs_constr_str = split[0];
            std::string rhs_constr_str = split[1];
            boost::trim_left_if(rhs_constr_str, boost::is_any_of("="));

            functionDictionary_t funcs = constraint->getRegFuncs();
            boost::scoped_ptr<Expressions::Expr_t> lhs(
                new Expressions::Expr_t(lhs_constr_str, funcs));
            boost::scoped_ptr<Expressions::Expr_t> rhs(
                new Expressions::Expr_t(rhs_constr_str, funcs));

            Expressions::Result_t lhs_res = lhs->evaluate(variable_dictionary);
            Expressions::Result_t rhs_res = rhs->evaluate(variable_dictionary);

            values.push_back(boost::get<0>(lhs_res));
            values.push_back(boost::get<0>(rhs_res));

            reqVarInfo_t tmps = {EVALUATE, values, is_valid};
            requestedVars_.insert(
368
                    std::pair<std::string, reqVarInfo_t>(namedConstraint.first, tmps));
adelmann's avatar
adelmann committed
369 370 371 372 373

        }

    }

374 375 376 377 378
    err = chdir(pwd_.c_str());
    if (err != 0) {
        std::cout << "Cannot chdir to "
                  << simulationDirName_.c_str() << std::endl;
    }
adelmann's avatar
adelmann committed
379 380 381 382

    cleanUp();
}

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
bool OpalSimulation::getVariableDictionary(variableDictionary_t& dictionary,
                                           const std::string& filename,
                                           const Expressions::Expr_t* const expression) {

    std::set<std::string> req_vars = expression->getReqVars();
    if(req_vars.empty()) return true;

    boost::scoped_ptr<SDDSReader> sddsr(new SDDSReader(filename));
    try {
        sddsr->parseFile();
    } catch(OptPilotException &e) {
        std::cout << "Exception while parsing SDDS file: "
                  << e.what() << std::endl;
        
        //XXX: in this case we mark the bunch as invalid since
        //     broken stat files can crash opt (why do they
        //     exist?)
        invalidBunch();
        return false;
    }

    // get all the required variable values from the stat file
    for(std::string req_var : req_vars) {
        if(dictionary.count(req_var) != 0) continue;
        
        try {
            double value = 0.0;
            sddsr->getValue(-1 /*atTime*/, req_var, value);
            dictionary.insert(std::pair<std::string, double>(req_var, value));
        } catch(OptPilotException &e) {
            std::cout << "Exception while getting value "
                      << "from SDDS file: " << e.what()
                      << std::endl;
            return false;
        }
    }
    return true;
}
adelmann's avatar
adelmann committed
421 422 423

void OpalSimulation::invalidBunch() {

424
    for(auto namedObjective : objectives_) {
adelmann's avatar
adelmann committed
425 426 427 428
        std::vector<double> tmp_values;
        tmp_values.push_back(0.0);
        reqVarInfo_t tmps = {EVALUATE, tmp_values, false};
        requestedVars_.insert(
429
                std::pair<std::string, reqVarInfo_t>(namedObjective.first, tmps));
adelmann's avatar
adelmann committed
430 431 432 433 434 435 436 437 438 439 440 441 442
    }
}

void OpalSimulation::cleanUp() {

#ifdef BOOST_FILESYSTEM
    try {
        boost::filesystem::path p(simulationDirName_.c_str());
        boost::filesystem::remove_all(p);
    } catch(...) {
    }
#endif

443
}