51 std::map<std::string, std::string> uvars)
53 , objectives_(objectives)
54 , constraints_(constraints)
58 namespace fs = std::filesystem;
60 simTmpDir_ = args->getArg<std::string>(
"simtmpdir");
62 if (getenv(
"SIMTMPDIR") ==
nullptr) {
63 std::cout <<
"Environment variable SIMTMPDIR not defined!"
73 std::vector<std::string> dict;
74 for (
auto parameter : params) {
75 std::ostringstream tmp;
77 tmp << parameter.first <<
"=" << parameter.second;
79 dict.push_back(tmp.str());
81 std::ostringstream value;
83 value << parameter.second;
85 std::pair<std::string, std::string>(parameter.first, value.str()));
95 MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
97 MPI_Comm_size(MPI_COMM_WORLD, &world_size);
99 unsigned num_coworkers_worker_ = 0;
100 num_coworkers_worker_ = args->getArg<
size_t>(
"num-coworkers");
102 unsigned group_start = 0;
104 unsigned worker_group = ((my_rank % world_size) - 2) / num_coworkers_worker_;
106 unsigned leader_ = group_start + 2 + worker_group * num_coworkers_worker_;
107 leader_ = leader_ % world_size;
113 std::ostringstream tmp;
116 tmp <<
simTmpDir_ <<
"/" << hash <<
"_" << leader_;
120 std::string tmplDir = args->getArg<std::string>(
"templates");
121 if (tmplDir.empty()) {
122 if (getenv(
"TEMPLATES") ==
nullptr) {
124 "Environment variable TEMPLATES not defined!");
126 tmplDir = getenv(
"TEMPLATES");
132 if (!fs::exists(tmplFile)) {
134 "The template file '" + tmplFile +
"' doesn't exit");
138 uvars[uvar.first] = uvar.second;
153 struct stat fileInfo;
155 if (stat(infile.c_str(), &fileInfo) == 0) {
156 std::cout <<
"-> Simulation input file (" << infile
157 <<
") already exist from previous run.." << std::endl;
166 namespace fs = std::filesystem;
168 for (
auto &p: fs::directory_iterator(path)) {
169 fs::path source = p.path();
171 target +=source.filename();
174 fs::create_symlink(source, target);
175 }
catch (fs::filesystem_error &e) {
176 std::cerr << e.what() <<
"\n"
177 <<
"in OpalSimulation::createSymlink()" << std::endl;
185 std::string restartfile = args->getArg<std::string>(
"restartfile",
"",
false);
187 if (restartfile.empty())
return;
189 namespace fs = std::filesystem;
190 if ( !fs::exists(restartfile) ) {
191 std::cerr <<
"H5 file '" + restartfile +
"' doesn't exist." <<
"\n"
192 <<
"in OpalSimulation::copyH5_m()" << std::endl;
198 fs::path srcfile(restartfile);
200 fs::copy_file(srcfile, targetfile);
201 }
catch (fs::filesystem_error &ex) {
202 std::cerr << ex.what() <<
"\n"
203 <<
"in OpalSimulation::copyH5_m()" << std::endl;
209 namespace fs = std::filesystem;
212 std::string restartfile = args->getArg<std::string>(
"restartfile",
"",
false);
215 std::ostringstream tmp;
225 if (getenv(
"FIELDMAPS") ==
nullptr) {
227 "Environment variable FIELDMAPS not defined!");
239 if (!fs::exists(dataDir)) {
241 "Directory '" + dataDir +
"' doesn't exist");
244 if (!restartfile.empty() &&
252 namespace fs = std::filesystem;
255 MPI_Comm_rank(
comm_, &rank);
256 if (rank != 0)
return;
265 fs::perms::owner_all |
266 fs::perms::group_read |
267 fs::perms::group_exec |
268 fs::perms::others_read |
269 fs::perms::others_exec);
271 }
catch (fs::filesystem_error &e) {
272 std::cerr << e.what() <<
"\n"
273 <<
"in OpalSimulation::setupSimulation" << std::endl;
280 fs::create_directory(dataDir);
281 fs::permissions(dataDir,
282 fs::perms::owner_all |
283 fs::perms::group_read |
284 fs::perms::group_exec |
285 fs::perms::others_read |
286 fs::perms::others_exec);
288 }
catch (fs::filesystem_error &e) {
289 std::cerr << e.what() <<
"\n"
290 <<
"in OpalSimulation::setupSimulation" << std::endl;
296 gs_->writeInputFile(infile);
298 std::string fieldmapPath = getenv(
"FIELDMAPS");
301 if (getenv(
"DISTRIBUTIONS") !=
nullptr) {
302 std::string distPath = getenv(
"DISTRIBUTIONS");
316 MPI_Comm_rank(MPI_COMM_WORLD, &world_pid);
318 std::ostringstream fname;
319 fname <<
"sim.out." << world_pid;
320 std::ofstream file(fname.str().c_str());
322 std::ofstream err(fname.str().c_str());
325 std::cout.rdbuf(file.rdbuf());
326 std::cerr.rdbuf(err.rdbuf());
337 namespace fs = std::filesystem;
346 pwd_ = fs::current_path().native();
351 std::cout <<
"Cannot chdir to "
353 std::cout <<
"Continuing 1, disregarding this simulation.."
359 std::ostringstream inputFileName;
361 char *inputfile =
new char[inputFileName.str().size()+1] ;
362 strcpy(inputfile, inputFileName.str().c_str());
366 int restartStep= args->getArg<
int>(
"restartstep",
367 std::numeric_limits<int>::min(),
false);
368 std::string restartfile = args->getArg<std::string>(
"restartfile",
"",
false);
371 if ( restartStep > -2 && restartfile.empty() ) {
373 "Restart specified but no restart H5 file available.");
376 char exe_name[] =
"opal";
377 char nocomm[] =
"--nocomminit";
378 char info[] =
"--info";
380 char warn[] =
"--warn";
382 char *
arg[] = { exe_name, inputfile, nocomm, info, info0, warn, warn0 };
388 std::cout.setstate(std::ios::failbit);
405 std::cerr <<
"Opal exception during simulation run: \n"
406 << ex->
where() <<
"\n"
407 << ex->
what() << std::endl;
408 std::cerr <<
"Continuing, disregarding this simulation.."
418 std::cerr <<
"Classic exception during simulation run: \n"
419 << ex->
where() <<
"\n"
420 << ex->
what() << std::endl;
421 std::cerr <<
"Continuing, disregarding this simulation.."
423 }
catch(std::exception &ex) {
427 std::cerr <<
"Exception occured during simulation run: \n"
428 << ex.
what() << std::endl
429 <<
"Continuing, disregarding this simulation.." << std::endl;
434 std::cerr <<
"Unknown exception occured during simulation run.\n"
435 <<
"Continuing, disregarding this simulation.." << std::endl;
442 err = chdir(
pwd_.c_str());
444 std::cerr <<
"Cannot chdir to "
445 <<
pwd_ << std::endl;
451 std::map<std::string, std::vector<double> > ret;
454 for (
const std::string &var : statVariables) {
459 std::cout <<
"failed to read data: " << e.what() <<
" in " << e.where() << std::endl;
463 std::vector<double> values;
464 values.reserve(column.size());
466 for (
const auto& val: column) {
469 ret.insert(std::make_pair(var, values));
484 std::cout <<
"Cannot chdir to "
486 std::cout <<
"Continuing, with cleanup.."
493 struct stat fileInfo;
496 if (stat(fn.c_str(), &fileInfo) != 0) {
499 Expressions::Named_t::iterator namedIt;
502 if (namedIt->first ==
"dummy")
continue;
512 objective->
evaluate(variable_dictionary);
514 std::vector<double> values;
515 values.push_back(std::get<0>(result));
516 bool is_valid = std::get<1>(result);
520 std::pair<std::string, reqVarInfo_t>(namedIt->first, tmps));
534 constraint->
evaluate(variable_dictionary);
536 std::vector<double> values;
537 values.push_back(std::get<0>(result));
538 bool is_valid = std::get<1>(result);
541 std::string constr_str = constraint->
toString();
543 std::string lhs_constr_str = (split.size() > 0) ? split[0] : std::string();
544 std::string rhs_constr_str = (split.size() > 1) ? split[1] : std::string();
548 const std::unique_ptr<Expressions::Expr_t> lhs(
550 const std::unique_ptr<Expressions::Expr_t> rhs(
556 values.push_back(std::get<0>(lhs_res));
557 values.push_back(std::get<0>(rhs_res));
561 std::pair<std::string, reqVarInfo_t>(namedIt->first, tmps));
565 std::cout <<
"Evaluation of objective or constraint " << namedIt->first <<
" threw an exception ('" << e.what() <<
"' in " << e.where() <<
")!" << std::endl;
568 std::cout <<
"Evaluation of objective or constraint " << namedIt->first <<
" threw an exception ('" << e.what() <<
"' in " << e.where() <<
")!" << std::endl;
570 }
catch(std::exception &e) {
571 std::cout <<
"Evaluation of objective or constraint " << namedIt->first <<
" threw an exception ('" << e.what() <<
"')!" << std::endl;
574 std::cout <<
"Evaluation of objective or constraint " << namedIt->first <<
" threw an exception!" << std::endl;
580 err = chdir(
pwd_.c_str());
582 std::cout <<
"Cannot chdir to "
588 const std::string& filename,
591 std::set<std::string> req_vars = expression->
getReqVars();
594 for (
auto req_it = req_vars.begin(); req_it!=req_vars.end();) {
600 double value = std::stod((*it).second);
601 dictionary.insert(std::pair<std::string, double>(*req_it, value));
602 req_it = req_vars.erase(req_it);
605 if (req_vars.empty())
return;
608 const std::unique_ptr<SDDSReader> sddsr(
new SDDSReader(filename));
611 for (std::string req_var : req_vars) {
612 if (dictionary.count(req_var) != 0)
continue;
615 sddsr->getValue(-1 , req_var, value);
616 dictionary.insert(std::pair<std::string, double>(req_var, value));
623 std::vector<double> tmp_values;
624 tmp_values.push_back(0.0);
627 std::pair<std::string, reqVarInfo_t>(namedObjective.first, tmps));
632 namespace fs = std::filesystem;
635 MPI_Comm_rank(
comm_, &my_rank);
640 }
catch(fs::filesystem_error &ex) {
641 std::cout <<
"Can't remove directory '" <<
simulationDirName_ <<
"', (" << ex.what() <<
")" << std::endl;
648 namespace fs = std::filesystem;
650 if ( keep.empty() ) {
657 MPI_Comm_rank(
comm_, &my_rank);
663 fs::directory_iterator it{p};
664 while (it != fs::directory_iterator{}) {
665 std::string extension =
Util::toUpper(it->path().extension().string());
668 extension.erase(0, 1);
670 auto result = std::find(keep.begin(), keep.end(), extension);
672 if ( result == keep.end() && ! fs::is_directory(it->path())) {
673 fs::remove(it->path());
679 fs::directory_iterator it{p};
680 while (it != fs::directory_iterator{}) {
681 if (fs::is_directory(it->path()) && fs::is_empty(it->path())) {
682 fs::remove(it->path());
687 }
catch(fs::filesystem_error &ex) {
689 <<
"', (" << ex.what() <<
")" << std::endl;
int run_opal(char *[], std::string inputfile, int restartStep, int infoLevel, int warnLevel, MPI_Comm comm)
std::map< std::string, client::function::type > functionDictionary_t
std::map< std::string, double > variableDictionary_t
namedVariableCollection_t Param_t
std::shared_ptr< CmdArguments > CmdArguments_t
std::map< std::string, Expressions::Expr_t * > Named_t
type of an expressions with a name
std::tuple< double, bool > Result_t
int seed
The current random seed.
std::string toUpper(const std::string &str)
std::vector< std::string > split_any_of(const std::string &s, const std::string &delims, bool compress)
std::string trim_chars(const std::string &s, const std::string &chars)
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
std::unique_ptr< GenerateOpalSimulation > gs_
object to generate simulation input files
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
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.
functionDictionary_t getRegFuncs() const
const std::string & toString() const
Expressions::Result_t evaluate(const variableDictionary_t &vars)
evaluate an expression given a value dictionary of free variables
const std::set< std::string > & getReqVars() const
static std::string generate(std::vector< std::string > arguments, size_t world_pid=0)
T getVariantValue(const ast::variant_t &val, ast::dataType type) const
Convert value from variant (only numeric types) to a value of type T.
const ast::columnData_t & getColumnData(const std::string &columnName) const
ast::dataType getColumnType(const std::string &col_name) const