diff --git a/optimizer/Optimizer/EA/Variator.h b/optimizer/Optimizer/EA/Variator.h index 214344d80a313c9f5a7929a5567cc57d473f29c6..02bd37a5e32df6f99806539dd936e320c06a9313 100644 --- a/optimizer/Optimizer/EA/Variator.h +++ b/optimizer/Optimizer/EA/Variator.h @@ -13,6 +13,9 @@ #include "Optimizer/EA/Population.h" #include "Optimizer/Optimizer.h" +#include "boost/property_tree/ptree.hpp" +#include "boost/property_tree/json_parser.hpp" + template< class ind_t , template <class> class CrossoverOperator @@ -69,9 +72,68 @@ public: /// create an initial population void initial_population(size_t sizeInitial) { - for(size_t i = 0; i < sizeInitial; i++) - new_individual(); - + + std::string fname = args_->getArg<std::string>("start-population", "", false); + + if ( fname.empty() ) { + for(size_t i = 0; i < sizeInitial; i++) + new_individual(); + } else { + typedef boost::property_tree::ptree ptree_t; + ptree_t tree; + + boost::property_tree::read_json(fname, tree); + + if ( tree.get<std::string>("name").compare("opt-pilot") ) { + throw OptPilotException("Variator::initial_population", + "Json file not generated by opt-pilot."); + } + + std::size_t nDVars = 0; + for(auto& elem : tree.get_child("dvar-bounds")) { + // check if it is a design variable + if (std::find(dNames_m.begin(), dNames_m.end(), elem.first) == dNames_m.end()) { + throw OptPilotException("Variator::initial_population", + "The design variable '" + elem.first + "' is not in the list."); + } + ++nDVars; + } + + if ( nDVars != dVarBounds_m.size() ) { + throw OptPilotException("Variator::initial_population", + "The number of design variables do not agree."); + } + + + boost::property_tree::ptree& population = tree.get_child("population"); + + std::size_t size = 0; + Individual::genes_t dvars(nDVars); + for (auto& ind : population ) { + + if ( size > sizeInitial - 1 ) + break; + + /* just to be sure: It might be that the order of the design variables in the + * Json file is not the same as it reads in, therefore, we check and take the order + * of the container dNames_m. + */ + for (auto& dvar : population.get_child(ind.first).get_child("dvar")) { + auto it = std::find(dNames_m.begin(), dNames_m.end(), dvar.first); + std::size_t idx = std::distance(dNames_m.begin(), it); + //FIXME requires random access of Individual::genes_t + dvars[idx] = dvar.second.get_value<double>(); + } + + new_individual(dvars); + ++size; + } + + // fill with random individuals + for (std::size_t i = size; i < sizeInitial; ++i) { + new_individual(); + } + } } /// set an individual as individual: replace with a new individual @@ -171,6 +233,13 @@ public: protected: + + /// create a new individual + void new_individual(Individual::genes_t& dvars) { + boost::shared_ptr<ind_t> ind(new ind_t(dVarBounds_m, dNames_m, constraints_m)); + std::swap(ind->genes_m, dvars); + individualsToEvaluate_m.push( population_m->add_individual(ind) ); + } /// create a new individual void new_individual() {