27#include "boost/variant.hpp"
28#include "boost/smart_ptr.hpp"
29#include "boost/algorithm/string.hpp"
31#include "boost/filesystem.hpp"
32#include "boost/filesystem/operations.hpp"
44 std::map<std::string, std::string> uvars)
46 , objectives_(objectives)
47 , constraints_(constraints)
51 namespace fs = boost::filesystem;
53 simTmpDir_ = args->getArg<std::string>(
"simtmpdir");
55 if(getenv(
"SIMTMPDIR") ==
nullptr) {
56 std::cout <<
"Environment variable SIMTMPDIR not defined!"
66 std::vector<std::string> dict;
67 for(
auto parameter : params) {
68 std::ostringstream tmp;
70 tmp << parameter.first <<
"=" << parameter.second;
72 dict.push_back(tmp.str());
74 std::ostringstream value;
76 value << parameter.second;
78 std::pair<std::string, std::string>(parameter.first, value.str()));
88 MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
90 MPI_Comm_size(MPI_COMM_WORLD, &world_size);
92 unsigned num_coworkers_worker_ = 0;
93 num_coworkers_worker_ = args->getArg<
size_t>(
"num-coworkers");
95 unsigned group_start = 0;
97 unsigned worker_group = ((my_rank % world_size) - 2) / num_coworkers_worker_;
99 unsigned leader_ = group_start + 2 + worker_group * num_coworkers_worker_;
100 leader_ = leader_ % world_size;
106 std::ostringstream tmp;
109 tmp <<
simTmpDir_ <<
"/" << hash <<
"_" << leader_;
113 std::string tmplDir = args->getArg<std::string>(
"templates");
114 if (tmplDir.empty()) {
115 if(getenv(
"TEMPLATES") ==
nullptr) {
117 "Environment variable TEMPLATES not defined!");
119 tmplDir = getenv(
"TEMPLATES");
125 if (!fs::exists(tmplFile))
127 "The template file '" + tmplFile +
"' doesn't exit");
130 uvars[uvar.first] = uvar.second;
145 struct stat fileInfo;
147 if(stat(infile.c_str(), &fileInfo) == 0) {
148 std::cout <<
"-> Simulation input file (" << infile
149 <<
") already exist from previous run.." <<
std::endl;
158 namespace fs = boost::filesystem;
160 for (
auto &p: fs::directory_iterator(path)) {
161 fs::path source = p.path();
163 target +=source.filename();
166 fs::create_symlink(source, target);
167 }
catch (fs::filesystem_error &
e) {
168 std::cerr <<
e.what() <<
"\n"
169 <<
"in OpalSimulation::createSymlink()" <<
std::endl;
177 std::string restartfile = args->getArg<std::string>(
"restartfile",
"",
false);
179 if (restartfile.empty())
return;
181 namespace fs = boost::filesystem;
182 if ( !fs::exists(restartfile) ) {
183 std::cerr <<
"H5 file '" + restartfile +
"' doesn't exist." <<
"\n"
184 <<
"in OpalSimulation::copyH5_m()" <<
std::endl;
190 fs::path srcfile(restartfile);
192 fs::copy_file(srcfile, targetfile);
193 }
catch (fs::filesystem_error &ex) {
194 std::cerr << ex.what() <<
"\n"
195 <<
"in OpalSimulation::copyH5_m()" <<
std::endl;
201 namespace fs = boost::filesystem;
204 std::string restartfile = args->getArg<std::string>(
"restartfile",
"",
false);
207 std::ostringstream tmp;
217 if (getenv(
"FIELDMAPS") ==
nullptr) {
219 "Environment variable FIELDMAPS not defined!");
231 if (!fs::exists(dataDir)) {
233 "Directory '" + dataDir +
"' doesn't exist");
236 if (!restartfile.empty() &&
244 namespace fs = boost::filesystem;
247 MPI_Comm_rank(
comm_, &rank);
248 if (rank != 0)
return;
263 }
catch (fs::filesystem_error &
e) {
264 std::cerr <<
e.what() <<
"\n"
265 <<
"in OpalSimulation::setupSimulation" <<
std::endl;
272 fs::create_directory(dataDir);
273 fs::permissions(dataDir,
280 }
catch (fs::filesystem_error &
e) {
281 std::cerr <<
e.what() <<
"\n"
282 <<
"in OpalSimulation::setupSimulation" <<
std::endl;
288 gs_->writeInputFile(infile);
290 std::string fieldmapPath = getenv(
"FIELDMAPS");
293 if (getenv(
"DISTRIBUTIONS") !=
nullptr) {
294 std::string distPath = getenv(
"DISTRIBUTIONS");
308 MPI_Comm_rank(MPI_COMM_WORLD, &world_pid);
310 std::ostringstream fname;
311 fname <<
"sim.out." << world_pid;
312 std::ofstream file(fname.str().c_str());
314 std::ofstream err(fname.str().c_str());
317 std::cout.rdbuf(file.rdbuf());
318 std::cerr.rdbuf(err.rdbuf());
329 namespace fs = boost::filesystem;
338 pwd_ = fs::current_path().native();
343 std::cout <<
"Cannot chdir to "
345 std::cout <<
"Continuing 1, disregarding this simulation.."
351 std::ostringstream inputFileName;
353 char *inputfile =
new char[inputFileName.str().size()+1] ;
354 strcpy(inputfile, inputFileName.str().c_str());
358 int restartStep= args->getArg<
int>(
"restartstep",
360 std::string restartfile = args->getArg<std::string>(
"restartfile",
"",
false);
363 if ( restartStep > -2 && restartfile.empty() ) {
365 "Restart specified but no restart H5 file available.");
368 char exe_name[] =
"opal";
369 char nocomm[] =
"--nocomminit";
370 char info[] =
"--info";
372 char warn[] =
"--warn";
374 char *
arg[] = { exe_name, inputfile, nocomm,
info, info0,
warn, warn0 };
380 std::cout.setstate(std::ios::failbit);
397 std::cerr <<
"Opal exception during simulation run: \n"
398 << ex->
where() <<
"\n"
400 std::cerr <<
"Continuing, disregarding this simulation.."
410 std::cerr <<
"Classic exception during simulation run: \n"
411 << ex->
where() <<
"\n"
413 std::cerr <<
"Continuing, disregarding this simulation.."
415 }
catch(std::exception &ex) {
419 std::cerr <<
"Exception occured during simulation run: \n"
421 <<
"Continuing, disregarding this simulation.." <<
std::endl;
426 std::cerr <<
"Unknown exception occured during simulation run.\n"
427 <<
"Continuing, disregarding this simulation.." <<
std::endl;
434 err = chdir(
pwd_.c_str());
436 std::cerr <<
"Cannot chdir to "
443 std::map<std::string, std::vector<double> > ret;
446 for (
const std::string &var : statVariables) {
451 std::cout <<
"failed to read data: " <<
e.what() <<
" in " <<
e.where() <<
std::endl;
455 std::vector<double> values;
456 values.reserve(column.size());
458 for (
const auto& val: column) {
461 ret.insert(std::make_pair(var, values));
476 std::cout <<
"Cannot chdir to "
478 std::cout <<
"Continuing, with cleanup.."
485 struct stat fileInfo;
488 if(stat(fn.c_str(), &fileInfo) != 0) {
494 if (namedIt->first ==
"dummy")
continue;
504 objective->
evaluate(variable_dictionary);
506 std::vector<double> values;
507 values.push_back(boost::get<0>(result));
508 bool is_valid = boost::get<1>(result);
512 std::pair<std::string, reqVarInfo_t>(namedIt->first, tmps));
526 constraint->
evaluate(variable_dictionary);
528 std::vector<double> values;
529 values.push_back(boost::get<0>(result));
530 bool is_valid = boost::get<1>(result);
533 std::string constr_str = constraint->
toString();
534 std::vector<std::string> split;
535 boost::split(split, constr_str, boost::is_any_of(
"<>!="),
536 boost::token_compress_on);
537 std::string lhs_constr_str = split[0];
538 std::string rhs_constr_str = split[1];
539 boost::trim_left_if(rhs_constr_str, boost::is_any_of(
"="));
542 boost::scoped_ptr<Expressions::Expr_t> lhs(
544 boost::scoped_ptr<Expressions::Expr_t> rhs(
550 values.push_back(boost::get<0>(lhs_res));
551 values.push_back(boost::get<0>(rhs_res));
555 std::pair<std::string, reqVarInfo_t>(namedIt->first, tmps));
559 std::cout <<
"Evaluation of objective or constraint " << namedIt->first <<
" threw an exception ('" <<
e.what() <<
"' in " <<
e.where() <<
")!" <<
std::endl;
562 std::cout <<
"Evaluation of objective or constraint " << namedIt->first <<
" threw an exception ('" <<
e.what() <<
"' in " <<
e.where() <<
")!" <<
std::endl;
564 }
catch(std::exception &
e) {
565 std::cout <<
"Evaluation of objective or constraint " << namedIt->first <<
" threw an exception ('" <<
e.what() <<
"')!" <<
std::endl;
568 std::cout <<
"Evaluation of objective or constraint " << namedIt->first <<
" threw an exception!" <<
std::endl;
574 err = chdir(
pwd_.c_str());
576 std::cout <<
"Cannot chdir to "
582 const std::string& filename,
585 std::set<std::string> req_vars = expression->
getReqVars();
588 for (
auto req_it = req_vars.begin(); req_it!=req_vars.end();) {
594 double value = std::stod((*it).second);
595 dictionary.insert(std::pair<std::string, double>(*req_it, value));
596 req_it = req_vars.erase(req_it);
599 if(req_vars.empty())
return;
602 boost::scoped_ptr<SDDSReader> sddsr(
new SDDSReader(filename));
605 for(std::string req_var : req_vars) {
606 if(dictionary.count(req_var) != 0)
continue;
609 sddsr->getValue(-1 , req_var, value);
610 dictionary.insert(std::pair<std::string, double>(req_var, value));
617 std::vector<double> tmp_values;
618 tmp_values.push_back(0.0);
621 std::pair<std::string, reqVarInfo_t>(namedObjective.first, tmps));
626 namespace fs = boost::filesystem;
629 MPI_Comm_rank(
comm_, &my_rank);
634 }
catch(fs::filesystem_error &ex) {
642 namespace fs = boost::filesystem;
644 if ( keep.empty() ) {
651 MPI_Comm_rank(
comm_, &my_rank);
657 fs::directory_iterator it{p};
658 while (it != fs::directory_iterator{}) {
659 std::string extension =
Util::toUpper(fs::extension(it->path().filename()));
662 extension.erase(0, 1);
664 auto result =
std::find(keep.begin(), keep.end(), extension);
666 if ( result == keep.end() && ! fs::is_directory(it->path())) {
667 fs::remove(it->path());
673 fs::directory_iterator it{p};
674 while (it != fs::directory_iterator{}) {
675 if (fs::is_directory(it->path()) && fs::is_empty(it->path())) {
676 fs::remove(it->path());
681 }
catch(fs::filesystem_error &ex) {
683 <<
"', (" << ex.what() <<
")" <<
std::endl;
int run_opal(char *[], std::string inputfile, int restartStep, int infoLevel, int warnLevel, MPI_Comm comm)
T::PETE_Expr_t::PETE_Return_t min(const PETE_Expr< T > &expr, NDIndex< D > &loc)
Inform & endl(Inform &inf)
namedVariableCollection_t Param_t
boost::shared_ptr< CmdArguments > CmdArguments_t
std::map< std::string, client::function::type > functionDictionary_t
std::map< std::string, double > variableDictionary_t
std::map< std::string, Expressions::Expr_t * > Named_t
type of an expressions with a name
const T * find(const T table[], const std::string &name)
Look up name.
boost::tuple< double, bool > Result_t
constexpr double e
The value of.
std::string::iterator iterator
int seed
The current random seed.
std::string toUpper(const std::string &str)
boost::function< boost::tuple< double, bool >(arguments_t)> type
std::vector< variant_t > columnData_t
The global OPAL structure.
static OpalData * getInstance()
The abstract base class for all exceptions in CLASSIC.
std::string pwd_
holds current directory (for restoring)
void invalidBunch()
mark a solution as invalid
virtual ~OpalSimulation()
std::map< std::string, std::vector< double > > getData(const std::vector< std::string > &statVariables)
void getVariableDictionary(variableDictionary_t &dictionary, const std::string &filename, const Expressions::Expr_t *const expression)
get variables for expression evaluation from SDDS file. Can throw SDDSParserException
reqVarContainer_t requestedVars_
holds solutions returned to the optimizer
void setupSimulation()
create directories, input files, fieldmaps...
void copyH5_m()
copy H5 file
void redirectOutToFile()
redirect stdout and stderr to file
Expressions::Named_t objectives_
std::streambuf * strm_err_
stream buffer to redirect stderr
std::string simulationDirName_
full path of simulation directory (where simulation will be run)
std::set< std::string > dvarNames_
Expressions::Named_t constraints_
std::map< std::string, std::string > userVariables_
variable dictionary holding requested optimizer values
boost::scoped_ptr< GenerateOpalSimulation > gs_
object to generate simulation input files
std::string simTmpDir_
temporary directory for simulation data (environment var SIMTMPDIR)
std::streambuf * strm_buffer_
stream buffer to redirect output
void createSymlink_m(const std::string &path)
create symbolic links
std::string simulationName_
identification of the simulation (corresponding to output filename)
bool hasResultsAvailable()
check if we already have simulated the current set of design vars
void setupFSStructure()
create directories, input files, symlinks...
void collectResults()
Parse SDDS stat file and build up requested variable dictionary.
void restoreOut()
restore stdout and stderr to default
int id_m
job id (SAMPLE command)
OpalSimulation(Expressions::Named_t objectives, Expressions::Named_t constraints, Param_t params, std::string name, MPI_Comm comm, CmdArguments_t args, std::map< std::string, std::string > uvars)
The base class for all OPAL exceptions.
virtual const std::string & what() const
Return the message string for the exception.
virtual const std::string & where() const
Return the name of the method or function which detected the exception.
std::string toString() const
functionDictionary_t getRegFuncs() const
Expressions::Result_t evaluate(variableDictionary_t vars)
evaluate an expression given a value dictionary of free variables
std::set< std::string > getReqVars() const
static std::string generate(std::vector< std::string > arguments, size_t world_pid=0)
ast::columnData_t getColumnData(const std::string &columnName)
ast::datatype getColumnType(const std::string &col_name)
T getBoostVariantValue(const ast::variant_t &val, int datatype) const
Convert value from boost variant (only numeric types) to a value of type T.