int main(int ac, char** av) { eoParser parser(ac, av); if (parser.userNeedsHelp()) { parser.printHelp(std::cout); exit(1); } make_help(parser); make_verbose(parser); eo::log << eo::setlevel(eo::debug); eo::log << eo::warnings; eo::log << "We are writing on the default output stream" << std::endl; //eo::log << eo::file("test.txt") << "In FILE" << std::endl; std::ofstream ofs("logtest.txt"); //eo::log << ofs << "In FILE" << std::endl; eo::log.redirect(ofs); eo::log << "In FILE" << std::endl; eo::log.redirect("logtest2.txt"); eo::log << "In FILE 2" << std::endl; std::ostringstream oss; //eo::log << oss << "In STRINGSTREAM"; eo::log.redirect(oss); eo::log << oss << "In STRINGSTREAM"; //ofs << oss; std::cout << "Content of ostringstream: " << oss.str() << std::endl; //eo::log << std::cout << "on COUT" << std::endl; eo::log.redirect(std::cout); eo::log << "on COUT" << std::endl; eo::log << eo::setlevel("errors"); eo::log << eo::setlevel(eo::errors); eo::log << eo::quiet << "1) in quiet mode" << std::endl; eo::log << eo::setlevel(eo::warnings) << eo::warnings << "2) in warnings mode" << std::endl; eo::log << eo::setlevel(eo::logging); eo::log << eo::errors; eo::log << "3) in errors mode"; eo::log << std::endl; eo::log << eo::debug << 4 << ')' << "4) in debug mode\n"; return 0; }
void metawindow() /* Show the meta server menu window */ { int i, height; char *header; static int lastHeight = 0; if (!metaWin) { height = 250 + metaHeight * (W_Textheight + 8) + 4 * (metaHeight - 1); metaWin = W_MakeWindow("Netrek Server List", 0, 0, 716, height, NULL, 2, foreColor); W_SetBackgroundImage(metaWin, "Misc/map_back.png"); logo = W_ReadImage(metaWin, "netrek-green-white-300px.png"); metaList = W_MakeMenu("metalist", 50, 200, LINE, metaHeight, metaWin, 1); lastHeight = metaHeight; make_help(); } else { if (metaHeight > lastHeight) { W_ReinitMenu(metaList, LINE, metaHeight); W_ResizeMenu(metaList, LINE, metaHeight); lastHeight = metaHeight; } // FIXME: handle metaList growing beyond metaWin } header = "Server Status Type Age"; W_WriteText(metaList, 0, 0, W_Cyan, header, -1, 0); for (i = 0; i < metaHeight; i++) redraw(i); /* Give the window the right name */ W_RenameWindow(metaWin, metaWindowName); /* Add additional options */ W_WriteText(metaList, 0, metaHeight-B_REFRESH, W_Yellow, "Refresh (r)", -1, 0); add_redraw(); W_WriteText(metaList, 0, metaHeight-B_HELP, W_Yellow, "Help & Tips (h)", -1, 0); W_WriteText(metaList, 0, metaHeight-B_QUIT, W_Yellow, "Quit (q)", -1, 0); /* Map window */ W_MapWindow(metaList); W_MapWindow(metaWin); }
int main(int ac, char** av) { eoParser parser(ac, av); unsigned int popSize = parser.getORcreateParam((unsigned int)100, "popSize", "Population Size", 'P', "Evolution Engine").value(); unsigned int dimSize = parser.getORcreateParam((unsigned int)10, "dimSize", "Dimension Size", 'd', "Evolution Engine").value(); uint32_t seedParam = parser.getORcreateParam((uint32_t)0, "seed", "Random number seed", 0).value(); if (seedParam == 0) { seedParam = time(0); } make_parallel(parser); make_help(parser); rng.reseed( seedParam ); eoUniformGenerator< double > gen(-5, 5); eoInitFixedLength< EOT > init( dimSize, gen ); eoEvalFuncPtr< EOT, double, const std::vector< double >& > mainEval( real_value ); eoEvalFuncCounter< EOT > eval( mainEval ); eoPop< EOT > pop( popSize, init ); //apply< EOT >( eval, pop ); eoPopLoopEval< EOT > popEval( eval ); popEval( pop, pop ); eo::log << eo::quiet << "DONE!" << std::endl; #ifdef ENABLE_OPENMP #pragma omp parallel { if ( 0 == omp_get_thread_num() ) //Warning: omp_get_thread_num doestn't work with pragma and required openMP { eo::log << "num of threads: " << omp_get_num_threads() << std::endl; //Warning: omp_get_num_threads doestn't work with pragma and required openMP } } return 0; #endif }
int main ( int argc, char* argv[] ) { time_t time_start = std::time(NULL); eoParserLogger parser(argc, argv); make_verbose(parser); #ifndef NDEBUG struct rlimit limit; getrlimit(RLIMIT_AS, &limit); eo::log << eo::logging << "Maximum size of the process virtual memory (soft,hard)=" << limit.rlim_cur << ", " << limit.rlim_max << std::endl; getrlimit(RLIMIT_DATA, &limit); eo::log << eo::logging << "Maximum size of the process data segment (soft,hard)=" << limit.rlim_cur << ", " << limit.rlim_max << std::endl; #endif eo::log << eo::logging << "Parameters:" << std::endl; std::string domain = parser.createParam( (std::string)"domain-zeno-time.pddl", "domain", "PDDL domain file", 'D', "Problem", true ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "domain" << domain << std::endl; std::string instance = parser.createParam( (std::string)"zeno10.pddl", "instance", "PDDL instance file", 'I', "Problem", true ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "instance" << instance << std::endl; unsigned int pop_size = parser.createParam( (unsigned int)100, "popSize", "Population Size", 'P', "Evolution Engine").value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "pop_size" << pop_size << std::endl; eoValueParam<unsigned int> & param_seed = parser.createParam( (unsigned int)0, "seed", "Random number seed", 'S' ); if ( param_seed.value() == 0) { param_seed.value()=time(0); } unsigned int seed = param_seed.value(); rng.reseed( seed ); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "seed" << seed << std::endl; unsigned int l_max_init_coef = parser.createParam( (unsigned int)2, "lmax-initcoef", "l_max will be set to the size of the chrono partition * this coefficient", 'C', "Initialization" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "l_max_init_coef" << l_max_init_coef << std::endl; unsigned int l_min = parser.createParam( (unsigned int)1, "lmin", "Minimum number of goals in a decomposition", 'l', "Initialization" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "l_min" << l_min << std::endl; unsigned int toursize = parser.createParam( (unsigned int)5, "tournament", "Size of the deterministic tournament for the selection", 't', "Selection" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "toursize" << toursize << std::endl; double offsprings = parser.createParam( (double)700, "offsprings", "Number of offsprings to produces", 'f', "Selection" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "offsprings" << offsprings << std::endl; unsigned int fitness_weight = parser.createParam( (unsigned int)10, "fitness-weight", "Unknown weight in the feasible and unfeasible fitness computation", 'W', "Evaluation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "fitness_weight" << fitness_weight << std::endl; unsigned int fitness_penalty = parser.createParam( (unsigned int)2, "fitness-penalty", "Penalty in the unfeasible fitnesses computation", 'w', "Evaluation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "fitness_penalty" << fitness_penalty << std::endl; unsigned int b_max_init = parser.createParam( (unsigned int)1e4, "bmax-init", "Number of allowed expanded nodes for the initial computation of b_max", 'B', "Evaluation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "b_max_init" << b_max_init << std::endl; unsigned int b_max_fixed = parser.createParam( (unsigned int)0, "bmax-fixed", "Fixed number of allowed expanded nodes. Overrides bmaxinit if != 0", 'b', "Evaluation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "b_max_fixed" << b_max_fixed << std::endl; double b_max_last_weight = parser.createParam( (double)3, "bmax-last-weight", "Weighting for the b_max used during the last search towards the end goal (must be strictly positive)", 'T', "Evaluation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "b_max_last_weight" << b_max_last_weight << std::endl; if( b_max_last_weight <= 0 ) { std::cout << "bmax-last-weight must be strictly positive (=" << b_max_last_weight << ") type --help for usage." << std::endl; exit(1); } double b_max_ratio = parser.createParam( 0.01, "bmax-ratio","Satisfying proportion of feasible individuals for the computation of b_max", 'J', "Evaluation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "b_max_ratio" << b_max_ratio << std::endl; double b_max_increase_coef = parser.createParam( (double)2, "bmax-increase-coef", "Multiplier increment for the computation of b_max", 'K', "Evaluation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "b_max_increase_coef" << b_max_increase_coef << std::endl; unsigned int maxtry_candidate = 0; unsigned int maxtry_mutex = 0; std::string plan_file = parser.createParam( (std::string)"plan.soln", "plan-file", "Plan file backup", 'F', "Misc" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "plan-file" << plan_file << std::endl; unsigned int radius = parser.createParam( (unsigned int)2, "radius", "Number of neighbour goals to consider for the addGoal mutation", 'R', "Variation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "radius" << radius << std::endl; double proba_change = parser.createParam( (double)0.8, "proba-change", "Probability to change an atom for the changeAtom mutation", 'c', "Variation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "proba_change" << proba_change << std::endl; double proba_del_atom = parser.createParam( (double)0.8, "proba-del-atom", "Average probability to delete an atom for the delAtom mutation", 'd', "Variation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "proba_del_atom" << proba_del_atom << std::endl; double w_delgoal = parser.createParam( (double)1, "w-delgoal", "Relative weight defining the probability to call the delGoal mutation", 'a', "Variation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "w_delgoal" << w_delgoal << std::endl; double w_addgoal = parser.createParam( (double)3, "w-addgoal", "Relative weight defining the probability to call the addGoal mutation", 'A', "Variation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "w_addgoal" << w_addgoal << std::endl; double w_delatom = parser.createParam( (double)1, "w-delatom", "Relative weight defining the probability to call the delAtom mutation", 'g', "Variation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "w_delatom" << w_delatom << std::endl; double w_addatom = parser.createParam( (double)1, "w-addatom", "Relative weight defining the probability to call the addAtom mutation", 'G', "Variation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "w_addatom" << w_addatom << std::endl; double proba_cross = parser.createParam( (double)0.2, "proba-cross", "Probability to apply a cross-over", 'c', "Variation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "proba_cross" << proba_cross << std::endl; double proba_mut = parser.createParam( (double)0.8, "proba-mut", "Probability to apply one of the mutation", 'm', "Variation" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "proba_mut" << proba_mut << std::endl; unsigned int max_seconds = parser.createParam( (unsigned int)0, "max-seconds", "Maximum number of user seconds in CPU for the whole search, set it to 0 to deactivate (1800 = 30 minutes)", 'i', "Stopping criterions" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "max_seconds" << max_seconds << std::endl; unsigned int mingen = parser.createParam( (unsigned int)10, "gen-min", "Minimum number of iterations", 'n', "Stopping criterions" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "mingen" << mingen << std::endl; unsigned int steadygen = parser.createParam( (unsigned int)50, "gen-steady", "Number of iterations without improvement", 's', "Stopping criterions" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "steadygen" << steadygen << std::endl; unsigned int maxgens = parser.createParam( (unsigned int)1000, "gen-max", "Maximum number of iterations", 'x', "Stopping criterions" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "maxgens" << maxgens << std::endl; unsigned int maxruns = parser.createParam( (unsigned int)0, "runs-max", "Maximum number of runs, if x==0: unlimited multi-starts, if x>1: will do <x> multi-start", 'r', "Stopping criterions" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "maxruns" << maxruns << std::endl; #ifndef NDEBUG eoValueParam<std::string>& dirNameParam = parser.createParam(std::string("Res"), "resDir", "Directory to store DISK outputs", '\0', "Output - Disk"); eoValueParam<bool>& eraseParam = parser.createParam(true, "eraseDir", "erase files in dirName if any", '\0', "Output - Disk"); eoValueParam<unsigned>& saveFrequencyParam = parser.createParam(unsigned(0), "saveFrequency", "Save every F generation (0 = only final state, absent = never)", '\0', "Persistence" ); #endif std::string plusOrComma = parser.createParam(std::string("Comma"), "plusOrComma", "Plus (parents+offspring) or Comma (only offspring) for replacement", '\0', "Evolution Engine").value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "plusOrComma" << plusOrComma << std::endl; unsigned replaceTourSize = parser.createParam(unsigned(1), "replaceTourSize", "Size of Replacement Tournament (1->deterministic (hum, pas logique ;-(", '\0', "Evolution Engine" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "replaceTourSize" << replaceTourSize << std::endl; bool removeDuplicates = parser.createParam(false, "removeDuplicates", "Does not allow duplicates in replacement (if possible)", '\0', "Evolution Engine").value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "removeDuplicates" << removeDuplicates << std::endl; bool weakElitism = parser.createParam(true, "weakElitism", "Weak Elitism in replacement", '\0', "Evolution Engine").value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "weakElitism" << weakElitism << std::endl; make_help( parser ); #ifndef NDEBUG eo::log << eo::progress << "Load the instance..." << std::endl; eo::log.flush(); #endif daex::pddlLoad pddl( domain, instance, SOLVER_YAHSP, HEURISTIC_H1 ); #ifndef NDEBUG eo::log << eo::progress << "Load the instance...OK" << std::endl; eo::log << eo::progress << "Initialization..."; eo::log.flush(); #endif daex::Init init( pddl.chronoPartitionAtom(), l_max_init_coef, l_min ); #ifndef NDEBUG eo::log << eo::logging << std::endl; eo::log << eo::logging << "\tChrono partition size: " << pddl.chronoPartitionAtom().size() << std::endl; eo::log << eo::logging << "\tl_max: " << init.l_max() << std::endl; eo::log << eo::debug << "\tChrono partition dates(#atoms): "; for( daex::ChronoPartition::const_iterator it = pddl.chronoPartitionAtom().begin(), end = pddl.chronoPartitionAtom().end(); it != end; ++it ) { eo::log << eo::debug << it->first << "(" << it->second.size() << ") "; } eo::log << eo::debug << std::endl; #endif eoPop<daex::Decomposition> pop = eoPop<daex::Decomposition>( pop_size, init ); unsigned int b_max_in=1, b_max_last, goodguys=0, popsize = pop.size(); #ifndef NDEBUG unsigned int eval_count = 0; #endif TimeVal best_makespan = INT_MAX; std::string dump_sep = "."; unsigned int dump_file_count = 1; std::string metadata = "domain " + domain + "\n" + IPC_PLAN_COMMENT + "instance " + instance; daex::Decomposition empty_decompo; bool found = false; if( b_max_fixed == 0 ) { #ifndef NDEBUG eo::log << eo::progress << "Apply an incremental computation strategy to fix bmax:" << std::endl; #endif while( (((double)goodguys/(double)popsize) < b_max_ratio) && (b_max_in < b_max_init) ) { goodguys=0; b_max_last = static_cast<unsigned int>( std::floor( b_max_in * b_max_last_weight ) ); daeYahspEval eval_yahsp( init.l_max(), b_max_in, b_max_last, fitness_weight, fitness_penalty ); daex::evalBestMakespanPlanDump eval_bestfile( eval_yahsp, plan_file, best_makespan, false, dump_sep, dump_file_count, metadata ); #ifndef NDEBUG eoEvalFuncCounter<daex::Decomposition> eval_counter( eval_bestfile, "Eval.\t" ); eval_counter.value( eval_count ); eoPopLoopEval<daex::Decomposition> eval_y( eval_counter ); #else eoPopLoopEval<daex::Decomposition> eval_y( eval_bestfile ); #endif eval_y( pop, pop ); #ifndef NDEBUG eoBestFitnessStat<daex::Decomposition> best_statTEST("Best"); best_statTEST(pop); eo::log << eo::logging << "\tbest_fitness " << best_statTEST.value(); #endif for (size_t i = 0; i < popsize; ++i) { if (pop[i].fitness().is_feasible()) goodguys++; else pop[i].invalidate(); } if ((goodguys == 0) && (!found)) { empty_decompo.invalidate(); #ifndef NDEBUG eval_counter(empty_decompo); #else eval_bestfile(empty_decompo); #endif if (empty_decompo.fitness().is_feasible()){ found = true; } } best_makespan = eval_bestfile.best(); dump_file_count = eval_bestfile.file_count(); #ifndef NDEBUG eo::log << eo::logging << "\tb_max_in " << b_max_in << "\tfeasible_ratio " << ((double)goodguys/(double)popsize); eo::log << "\tbest_makespan " << best_makespan; if(found) { eo::log << "\tfeasible empty decomposition"; } eo::log << std::endl; eval_count = eval_counter.value(); #endif b_max_fixed = b_max_in; b_max_in = (unsigned int)ceil(b_max_in*b_max_increase_coef); } } b_max_in = b_max_fixed; b_max_last = static_cast<unsigned int>( std::floor( b_max_in * b_max_last_weight ) ); daeYahspEval eval_yahsp( init.l_max(), b_max_in, b_max_last, fitness_weight, fitness_penalty ); eoPopLoopEval<daex::Decomposition> eval_y( eval_yahsp ); eval_y( pop, pop ); #ifndef NDEBUG eo::log << eo::logging << std::endl << "\tb_max for intermediate goals, b_max_in: " << b_max_in << std::endl; eo::log << eo::logging << "\tb_max for final goal, b_max_last: " << b_max_last << std::endl; eo::log << eo::progress << "OK" << std::endl; eo::log << eo::progress << "Creating evaluators..."; eo::log.flush(); #endif eoEvalFunc<daex::Decomposition> * p_eval; daex::evalBestMakespanPlanDump eval_bestfile( eval_yahsp, plan_file, best_makespan, false, dump_sep, dump_file_count, metadata ); #ifndef NDEBUG eoEvalFuncCounter<daex::Decomposition> eval_counter( eval_bestfile, "Eval.\t" ); eval_counter.value( eval_count ); #endif if( max_seconds == 0 ) { #ifndef NDEBUG p_eval = & eval_counter; #else p_eval = & eval_bestfile; #endif } else { eoEvalUserTimeThrowException<daex::Decomposition> * p_eval_maxtime #ifndef NDEBUG = new eoEvalUserTimeThrowException<daex::Decomposition>( eval_counter, max_seconds ); #else = new eoEvalUserTimeThrowException<daex::Decomposition>( eval_bestfile, max_seconds ); #endif p_eval = p_eval_maxtime; }
int main ( int argc, char* argv[] ) { // WALLOCK TIME COUNTER eo::mpi::Node::init( argc, argv ); time_t time_start = std::time(NULL); /************** * PARAMETERS * **************/ // EO eoParser parser(argc, argv); make_verbose(parser); make_parallel(parser); eoState state; // log some EO parameters eo::log << eo::logging << "Parameters:" << std::endl; eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "verbose" << eo::log.getLevelSelected() << std::endl; eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "parallelize-loop" << eo::parallel.isEnabled() << std::endl; eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "parallelize-dynamic" << eo::parallel.isDynamic() << std::endl; eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "parallelize-prefix" << eo::parallel.prefix() << std::endl; eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "parallelize-nthreads" << eo::parallel.nthreads() << std::endl; // GENERAL PARAMETERS // createParam (ValueType _defaultValue, std::string _longName, std::string _description, char _shortHand=0, std::string _section="", bool _required=false) std::string domain = parser.createParam( (std::string)"domain-zeno-time.pddl", "domain", "PDDL domain file", 'D', "Problem", true ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "domain" << domain << std::endl; std::string instance = parser.createParam( (std::string)"zeno10.pddl", "instance", "PDDL instance file", 'I', "Problem", true ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "instance" << instance << std::endl; std::string plan_file = parser.createParam( (std::string)"plan.soln", "plan-file", "Plan file backup", 'F', "Misc" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "plan-file" << plan_file << std::endl; // pop size unsigned int pop_size = parser.createParam( (unsigned int)100, "popSize", "Population Size", 'P', "Evolution Engine").value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "pop_size" << pop_size << std::endl; // multi-start unsigned int maxruns = parser.createParam( (unsigned int)0, "runs-max", "Maximum number of runs, if x==0: unlimited multi-starts, if x>1: will do <x> multi-start", 'r', "Stopping criterions" ).value(); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "maxruns" << maxruns << std::endl; // b_max estimation bool insemination = parser.createParam(true, "insemination", "Use the insemination heuristic to estimate b_max at init", '\0', "Initialization").value(); // seed eoValueParam<unsigned int> & param_seed = parser.createParam( (unsigned int)0, "seed", "Random number seed", 'S' ); // if one want to initialize on current time if ( param_seed.value() == 0) { // change the parameter itself, that will be dumped in the status file // param_seed.value( time(0) ); param_seed.value()=time(0); // EO compatibility fixed by CC on 2010.12.24 } unsigned int seed = param_seed.value(); rng.reseed( seed ); eo::log << eo::logging << FORMAT_LEFT_FILL_W_PARAM << "seed" << seed << std::endl; // Parameters makers daex::do_make_eval_param( parser ); daex::do_make_init_param( parser ); daex::do_make_variation_param( parser, pop_size); daex::do_make_checkpoint_param( parser ); daex::do_make_replace_param( parser ); // special case of stopping criteria parameters daex::do_make_continue_param( parser ) ; // Those parameters are needed during restarts (see below) unsigned int mingen = parser.valueOf<unsigned int>("gen-min"); unsigned int steadygen = parser.valueOf<unsigned int>("gen-steady"); unsigned int maxgens = parser.valueOf<unsigned int>("gen-max"); make_help( parser ); /*********** * PARSING * ***********/ // PDDL #ifndef NDEBUG eo::log << eo::progress << "Load the instance..." << std::endl; eo::log.flush(); #endif daex::pddlLoad pddl( domain, instance, SOLVER_YAHSP, HEURISTIC_H1, eo::parallel.nthreads(), std::vector<std::string>()); #ifndef NDEBUG eo::log << eo::progress << "Load the instance...OK" << std::endl; eo::log << eo::progress << "Initialization..."; eo::log.flush(); #endif /****************** * INITIALIZATION * ******************/ daex::Init<daex::Decomposition>& init = daex::do_make_init_op<daex::Decomposition>( parser, state, pddl ); daex::Goal::atoms( & pddl.atoms() ); // randomly generate the population with the init operator eoPop<daex::Decomposition> pop = eoPop<daex::Decomposition>( pop_size, init ); // eoPop<daex::Decomposition> pop = eoPop<daex::Decomposition>( 10, init ); // used to pass the eval count through the several eoEvalFuncCounter evaluators unsigned int eval_count = 0; TimeVal best_makespan = MAXTIME; #ifndef SINGLE_EVAL_ITER_DUMP std::string dump_sep = "."; unsigned int dump_file_count = 1; std::string metadata = "domain " + domain + "\n" + IPC_PLAN_COMMENT + "instance " + instance; #endif unsigned int b_max_fixed = parser.valueOf<unsigned int>("bmax-fixed"); if( b_max_fixed == 0 ) { // b_max_fixed = 2048; // 128 b_max_fixed = daex::estimate_bmax_insemination( parser, pddl, pop, init.l_max() ); } unsigned b_max_in = b_max_fixed; double b_max_last_weight = parser.valueOf<double>("bmax-last-weight"); unsigned int b_max_last = static_cast<unsigned int>( std::floor( b_max_in * b_max_last_weight ) ); #ifndef NDEBUG eo::log << eo::logging << std::endl << "\tb_max for intermediate goals, b_max_in: " << b_max_in << std::endl; eo::log << eo::logging << "\tb_max for final goal, b_max_last: " << b_max_last << std::endl; #endif /************** * EVALUATION * **************/ #ifndef NDEBUG eo::log << eo::progress << "Creating evaluators..."; eo::log.flush(); #endif // do_make_eval returns a pair: the evaluator instance // and a pointer on a func counter that may be null of we are in release mode std::pair< eoEvalFunc<daex::Decomposition>&, eoEvalFuncCounter<daex::Decomposition>* > eval_pair = daex::do_make_eval_op<daex::Decomposition>( parser, state, init.l_max(), eval_count, b_max_in, b_max_last, plan_file, best_makespan, dump_sep, dump_file_count, metadata ); eoEvalFunc<daex::Decomposition>& eval = eval_pair.first; #ifndef NDEBUG // in debug mode, we should have a func counter assert( eval_pair.second != NULL ); eoEvalFuncCounter<daex::Decomposition>& eval_counter = * eval_pair.second; eo::log << eo::progress << "OK" << std::endl; eo::log << eo::progress << "Evaluating the first population..."; eo::log.flush(); #endif // a first evaluation of generated pop eoPopLoopEval<daex::Decomposition> pop_eval( eval ); pop_eval( pop, pop ); #ifndef NDEBUG eo::log << eo::progress << "OK" << std::endl; #endif /******************** * EVOLUTION ENGINE * ********************/ #ifndef NDEBUG eo::log << eo::progress << "Algorithm instanciation..."; eo::log.flush(); #endif // STOPPING CRITERIA eoCombinedContinue<daex::Decomposition> continuator = daex::do_make_continue_op<daex::Decomposition>( parser, state ); // Direct access to continuators are needed during restarts (see below) eoSteadyFitContinue<daex::Decomposition> & steadyfit = *( dynamic_cast<eoSteadyFitContinue<daex::Decomposition>* >( continuator[0] ) ); eoGenContinue<daex::Decomposition> & maxgen = *( dynamic_cast< eoGenContinue<daex::Decomposition>* >( continuator[1] ) ); // CHECKPOINTING eoCheckPoint<daex::Decomposition> & checkpoint = daex::do_make_checkpoint_op( continuator, parser, state, pop #ifndef NDEBUG , eval_counter #endif ); // SELECTION AND VARIATION // daex::MutationDelGoal<daex::Decomposition> delgoal; // FIXME Erreur de segmentation ici : delgoal devrait être un pointeur alloué. daex::MutationDelGoal<daex::Decomposition>* delgoal = new daex::MutationDelGoal<daex::Decomposition>; eoGeneralBreeder<daex::Decomposition> & breed = daex::do_make_variation_op<daex::Decomposition>( parser, state, pddl, delgoal ); // REPLACEMENT eoReplacement<daex::Decomposition> & replacor = daex::do_make_replace_op<daex::Decomposition>( parser, state ); unsigned int offsprings = parser.valueOf<unsigned int>("offsprings"); // ALGORITHM eoEasyEA<daex::Decomposition> dae( checkpoint, eval, breed, replacor, offsprings ); #ifndef NDEBUG eo::log << eo::progress << "OK" << std::endl; //eo::log << eo::progress << "Note: dual fitness is printed as two numbers: a value followed by a boolean (0=unfeasible, 1=feasible)" << std::endl; eo::log.flush(); eo::log << eo::debug << "Legend: \n\t- already valid, no eval\n\tx plan not found\n\t* plan found\n\ta add atom\n\tA add goal\n\td delete atom\n\tD delete goal\n\tC crossover" << std::endl; #endif /******************** * MULTI-START RUNS * ********************/ // best decomposition of all the runs, in case of multi-start // start at the best element of the init daex::Decomposition best = pop.best_element(); std::cout << "[Bench] Beginning serialization..." << std::endl; daex::Decomposition read; // Serializes in json int benchNb = 10; std::stringstream ss; eoserial::Object* jsonBest; time_t before_serialize = time(0); for (int i = 0; i < benchNb; ++i) { jsonBest = best.pack(); ss.clear(); ss.str(std::string()); jsonBest->print( ss ); delete jsonBest; } // std::cout<< "\n\n" << jsonBest << std::endl; time_t after_serialize = time(0); std::cout << "[Bench] Serialization took " << after_serialize - before_serialize << " seconds." << std::endl; std::cout<< "\n\nParsing..." << std::endl; time_t before_deserialize = time(0); for (int i = 0; i < benchNb; ++i) { eoserial::Object* received = eoserial::Parser::parse( ss.str() ); // Deserializes from json read.unpack( received ); delete received; } time_t after_deserialize = time(0); // std::cout<<"\n\nParsing finished, this is what I read :" << std::endl; // std::cout << received << std::endl; std::cout << "[Bench] Deserialization took " << after_deserialize - before_deserialize << " seconds." << std::endl; std::cout << "\n\nEnd of main, test is finished.\n" << std::endl; }
void help(int scr) { int v,k; int more=0; int cont=0; int q=0; make_help(); WINDOW *w1; w1=newwin (scr+2,62,7,(nrcols-62)/2); wrefresh (w1); werase (w1); WINDOW *w; w=newwin (scr,60,8,(nrcols-60)/2); wsetcolor (w,12,0); for (int h=0;h<=scr+2;h++) mvwprintw (w,h,0," "); wsetcolor (w,12,0); le_border (w,60,scr); wsetcolor (w,13,1); mvwprintw (w,0,1," Help "); wsetcolor (w,12,0); mvwprintw (w,scr-1,46," ESC - quit "); wrefresh(w); noecho(); timeout (1); k=0; do { if (more < 0) {k--; more++; cont=1;} if (more > 0) {k++; more--; cont=1;} if (k < 0) k=0; if (k > help_lines-(scr-5)) k=help_lines-(scr-5); wsetcolor (w,12,0); for (int i=0;i<=scr-5;i++) { mvwprintw (w,2+i,2," "); mvwprintw (w,2+i,2,"%s",help_s[i+k]); } wsetcolor (w,12,0); mvwaddch (w,0,28,ACS_HLINE); mvwaddch (w,scr-1,28,ACS_HLINE); wsetcolor (w,12,1); if (k>0) mvwaddch (w,0,28,ACS_UARROW); if (k<help_lines-(scr-5)) mvwaddch (w,scr-1,28,ACS_DARROW); wrefresh(w); do { messages(); v=getch(); if ((try_again) && (v==ERR)) playnext(); } while ((v==ERR) && (cont==0)); cont=0; if (v == 'q') q=1; if (v == 27) { v=getch(); if (v==ERR) q=1; if (v==91) { v=getch(); if (v==65) k--; if (v==66) k++; if (v==53) more=-scr+4; if (v==54) more=scr-4; } } if (quit==1) q=1; while (v!=ERR) v=getch(); } while (q==0); werase (w); reread=1; }
static int answer_to_connection(void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t * upload_data_size, void **con_cls) { struct agent_core_t *core = (struct agent_core_t *)cls; struct http_priv_t *http; struct http_request request; struct connection_info_struct *con_info; (void)version; GET_PRIV(core, http); if (*con_cls == NULL) { ALLOC_OBJ(con_info); *con_cls = con_info; return (MHD_YES); } con_info = *con_cls; assert(core->config->userpass); log_request(connection, http, method, url); if (!strcmp(method, "OPTIONS")) { /* We need this for preflight requests (CORS). */ return (http_reply(connection, 200, NULL)); } else if (!strcmp(method, "GET") || !strcmp(method, "HEAD") || !strcmp(method, "DELETE")) { if (check_auth(connection, core, con_info)) return (MHD_YES); if (!strcmp(method, "DELETE")) request.method = M_DELETE; else request.method = M_GET; request.connection = connection; request.url = url; request.ndata = 0; if (find_listener(&request, http)) return (MHD_YES); } else if (!strcmp(method, "POST") || !strcmp(method, "PUT")) { if (*upload_data_size != 0) { if (*upload_data_size + con_info->progress >= RCV_BUFFER) { warnlog(http->logger, "Client input exceeded buffer size " "of %u bytes. Dropping client.", RCV_BUFFER); return (MHD_NO); } memcpy(con_info->answerstring + con_info->progress, upload_data, *upload_data_size); con_info->progress += *upload_data_size; *upload_data_size = 0; return (MHD_YES); } else if ((char *)con_info->answerstring != NULL) { if (check_auth(connection, core, con_info)) return (MHD_YES); if (!strcmp(method, "POST")) request.method = M_POST; else request.method = M_PUT; request.connection = connection; request.url = url; request.ndata = con_info->progress; request.data = con_info->answerstring; /* * FIXME */ ((char *)request.data)[con_info->progress] = '\0'; if (find_listener(&request, http)) return (MHD_YES); } } if (request.method == M_GET && !strcmp(url, "/")) { if (http->help_page == NULL) http->help_page = make_help(http); assert(http->help_page); return (http_reply(connection, 200, http->help_page)); } return (http_reply(connection, 500, "Failed")); }
int main(int ac, char** av) { // (0) parser + eo routines eoParser parser(ac, av); std::string section("Algorithm parameters"); unsigned int r_max = parser.createParam((unsigned int)100, "run-number", "Number of run", 'r', section).value(); // r unsigned int p_min = parser.createParam((unsigned int)10, "population-min", "Population min", 'p', section).value(); // p unsigned int p_max = parser.createParam((unsigned int)1000, "population-max", "Population max", 'P', section).value(); // P unsigned int p_step = parser.createParam((unsigned int)50, "population-step", "Population step", 't', section).value(); // t unsigned int s_size = parser.createParam((unsigned int)2, "dimension-size", "Dimension size", 'd', section).value(); // d AtomType mean_value = parser.createParam((AtomType)0, "mean", "Mean value", 'm', section).value(); // m AtomType covar1_value = parser.createParam((AtomType)1.0, "covar1", "Covar value 1", '1', section).value(); // 1 AtomType covar2_value = parser.createParam((AtomType)0.5, "covar2", "Covar value 2", '2', section).value(); // 2 AtomType covar3_value = parser.createParam((AtomType)1.0, "covar3", "Covar value 3", '3', section).value(); // 3 std::string results_directory = parser.createParam((std::string)"means_distances_results", "results-directory", "Results directory", 'R', section).value(); // R std::string files_description = parser.createParam((std::string)"files_description.txt", "files-description", "Files description", 'F', section).value(); // F if (parser.userNeedsHelp()) { parser.printHelp(std::cout); exit(1); } make_verbose(parser); make_help(parser); assert(r_max >= 1); assert(s_size >= 2); eo::log << eo::quiet; ::mkdir( results_directory.c_str(), 0755 ); for ( unsigned int p_size = p_min; p_size <= p_max; p_size += p_step ) { assert(p_size >= p_min); std::ostringstream desc_file; desc_file << results_directory << "/" << files_description; std::ostringstream cur_file; cur_file << results_directory << "/pop_" << p_size << ".txt"; eo::log << eo::file( desc_file.str() ) << cur_file.str().c_str() << std::endl; eo::log << eo::file( cur_file.str() ); eo::log << eo::logging << "run_number p_size s_size mean(0) mean(1) new-mean(0) new-mean(1) distance" << std::endl; eo::log << eo::quiet; for ( unsigned int r = 1; r <= r_max; ++r) { eoState state; // (1) Population init and sampler eoRndGenerator< double >* gen = new eoUniformGenerator< double >(-5, 5); state.storeFunctor(gen); eoInitFixedLength< EOT >* init = new eoInitFixedLength< EOT >( s_size, *gen ); state.storeFunctor(init); // create an empty pop and let the state handle the memory // fill population thanks to eoInit instance eoPop< EOT >& pop = state.takeOwnership( eoPop< EOT >( p_size, *init ) ); // (2) distribution initial parameters #ifdef WITH_BOOST Vector mean( s_size, mean_value ); #else #ifdef WITH_EIGEN Vector mean( s_size ); mean = Vector::Constant( s_size, mean_value); #endif #endif Matrix varcovar( s_size, s_size ); varcovar( 0, 0 ) = covar1_value; varcovar( 0, 1 ) = covar2_value; varcovar( 1, 1 ) = covar3_value; Distrib distrib( mean, varcovar ); // Prepare bounder class to set bounds of sampling. // This is used by edoSampler. edoBounder< EOT >* bounder = new edoBounderRng< EOT >(EOT(pop[0].size(), -5), EOT(pop[0].size(), 5), *gen); state.storeFunctor(bounder); // Prepare sampler class with a specific distribution edoSampler< Distrib >* sampler = new edoSamplerNormalMulti< EOT >( *bounder ); state.storeFunctor(sampler); // (4) sampling phase pop.clear(); for (unsigned int i = 0; i < p_size; ++i) { EOT candidate_solution = (*sampler)( distrib ); pop.push_back( candidate_solution ); } // (6) estimation phase edoEstimator< Distrib >* estimator = new edoEstimatorNormalMulti< EOT >(); state.storeFunctor(estimator); distrib = (*estimator)( pop ); // (8) euclidianne distance estimation Vector new_mean = distrib.mean(); Matrix new_varcovar = distrib.varcovar(); AtomType distance = 0; for ( unsigned int d = 0; d < s_size; ++d ) { distance += pow( mean[ d ] - new_mean[ d ], 2 ); } distance = sqrt( distance ); eo::log << r << " " << p_size << " " << s_size << " " << mean(0) << " " << mean(1) << " " << new_mean(0) << " " << new_mean(1) << " " << distance << std::endl ; } } return 0; }
static int answer_to_connection (void *cls, struct MHD_Connection *connection, const char *url, const char *method, const char *version, const char *upload_data, size_t *upload_data_size, void **con_cls) { struct agent_core_t *core = (struct agent_core_t *)cls; struct http_priv_t *http; struct agent_plugin_t *plug; struct http_request request; struct connection_info_struct *con_info = NULL; int ret; (void)version; plug = plugin_find(core,"http"); http = (struct http_priv_t *) plug->data; assert(plug); assert(http); if (NULL == *con_cls) { con_info = malloc (sizeof (struct connection_info_struct)); assert(con_info); con_info->answerstring[0] = '\0'; con_info->progress = 0; con_info->authed = 0; *con_cls = con_info; return MHD_YES; } con_info = *con_cls; assert(core->config->userpass); log_request(connection, http, method, url); if (0 == strcmp (method, "GET") || !strcmp(method, "HEAD") || !strcmp(method,"DELETE")) { ret = check_auth(connection, core, con_info); if (ret == 1) return MHD_YES; if (!strcmp(method,"DELETE")) { request.method = M_DELETE; } else { request.method = M_GET; } request.connection = connection; request.url = url; request.ndata = 0; if (find_listener(&request, http)) return MHD_YES; } if (!strcmp(method, "POST") || !strcmp(method, "PUT")) { if (*upload_data_size != 0) { if (*upload_data_size + con_info->progress >= RCV_BUFFER) { warnlog(http->logger, "Client input exceeded buffer size of %u bytes. Dropping client.", RCV_BUFFER); return MHD_NO; } memcpy(con_info->answerstring + con_info->progress, upload_data, *upload_data_size); con_info->progress += *upload_data_size; *upload_data_size = 0; return MHD_YES; } else if (NULL != con_info->answerstring){ ret = check_auth(connection, core, con_info); if (ret == 1) return MHD_YES; if (!strcmp(method,"POST")) { request.method = M_POST; } else { request.method = M_PUT; } request.connection = connection; request.url = url; request.ndata = con_info->progress; request.data = con_info->answerstring; /* * FIXME */ ((char *)request.data)[con_info->progress] = '\0'; if (find_listener(&request, http)) return MHD_YES; } } if (request.method == M_GET && !strcmp(url, "/")) { if (http->help_page == NULL) http->help_page = make_help(http); assert (http->help_page); return send_response_ok(connection, http->help_page); } return send_response_fail (connection, "Failed\n"); }
int main(int ac, char** av) { // (0) parser + eo routines eoParser parser(ac, av); std::string section("Algorithm parameters"); unsigned int p_size = parser.createParam((unsigned int)100, "popSize", "Population Size", 'P', section).value(); // P unsigned int s_size = parser.createParam((unsigned int)2, "dimension-size", "Dimension size", 'd', section).value(); // d AtomType mean_value = parser.createParam((AtomType)0, "mean", "Mean value", 'm', section).value(); // m AtomType covar1_value = parser.createParam((AtomType)1.0, "covar1", "Covar value 1", '1', section).value(); AtomType covar2_value = parser.createParam((AtomType)0.5, "covar2", "Covar value 2", '2', section).value(); AtomType covar3_value = parser.createParam((AtomType)1.0, "covar3", "Covar value 3", '3', section).value(); std::ostringstream ss; ss << p_size << "_" << std::fixed << std::setprecision(1) << mean_value << "_" << covar1_value << "_" << covar2_value << "_" << covar3_value << "_gen"; std::string gen_filename = ss.str(); if( parser.userNeedsHelp() ) { parser.printHelp(std::cout); exit(1); } make_verbose(parser); make_help(parser); assert(p_size > 0); assert(s_size > 0); eoState state; // (1) Population init and sampler eoRndGenerator< double >* gen = new eoUniformGenerator< double >(-5, 5); state.storeFunctor(gen); eoInitFixedLength< EOT >* init = new eoInitFixedLength< EOT >( s_size, *gen ); state.storeFunctor(init); // create an empty pop and let the state handle the memory // fill population thanks to eoInit instance eoPop< EOT >& pop = state.takeOwnership( eoPop< EOT >( p_size, *init ) ); // (2) distribution initial parameters Vector mean( s_size ); for (unsigned int i = 0; i < s_size; ++i) { mean( i ) = mean_value; } Matrix varcovar( s_size, s_size ); varcovar( 0, 0 ) = covar1_value; varcovar( 0, 1 ) = covar2_value; varcovar( 1, 1 ) = covar3_value; Distrib distrib( mean, varcovar ); // (3a) distribution output preparation edoDummyContinue< Distrib >* distrib_dummy_continue = new edoDummyContinue< Distrib >(); state.storeFunctor(distrib_dummy_continue); edoCheckPoint< Distrib >* distrib_continue = new edoCheckPoint< Distrib >( *distrib_dummy_continue ); state.storeFunctor(distrib_continue); edoDistribStat< Distrib >* distrib_stat = new edoStatNormalMulti< EOT >(); state.storeFunctor(distrib_stat); distrib_continue->add( *distrib_stat ); edoFileSnapshot* distrib_file_snapshot = new edoFileSnapshot( "TestResDistrib", 1, gen_filename ); state.storeFunctor(distrib_file_snapshot); distrib_file_snapshot->add(*distrib_stat); distrib_continue->add(*distrib_file_snapshot); // (3b) distribution output (*distrib_continue)( distrib ); // Prepare bounder class to set bounds of sampling. // This is used by edoSampler. edoBounder< EOT >* bounder = new edoBounderRng< EOT >( EOT(pop[0].size(), -5), EOT(pop[0].size(), 5), *gen ); state.storeFunctor(bounder); // Prepare sampler class with a specific distribution edoSampler< Distrib >* sampler = new edoSamplerNormalMulti< EOT >( *bounder ); state.storeFunctor(sampler); // (4) sampling phase pop.clear(); for( unsigned int i = 0; i < p_size; ++i ) { EOT candidate_solution = (*sampler)( distrib ); pop.push_back( candidate_solution ); } // (5) population output eoContinue< EOT >* pop_cont = new eoGenContinue< EOT >( 2 ); // never reached fitness state.storeFunctor(pop_cont); eoCheckPoint< EOT >* pop_continue = new eoCheckPoint< EOT >( *pop_cont ); state.storeFunctor(pop_continue); edoPopStat< EOT >* pop_stat = new edoPopStat<EOT>; state.storeFunctor(pop_stat); pop_continue->add(*pop_stat); edoFileSnapshot* pop_file_snapshot = new edoFileSnapshot( "TestResPop", 1, gen_filename ); state.storeFunctor(pop_file_snapshot); pop_file_snapshot->add(*pop_stat); pop_continue->add(*pop_file_snapshot); (*pop_continue)( pop ); // (6) estimation phase edoEstimator< Distrib >* estimator = new edoEstimatorNormalMulti< EOT >(); state.storeFunctor(estimator); distrib = (*estimator)( pop ); // (7) distribution output (*distrib_continue)( distrib ); // (8) euclidianne distance estimation Vector new_mean = distrib.mean(); Matrix new_varcovar = distrib.varcovar(); AtomType distance = 0; for( unsigned int d = 0; d < s_size; ++d ) { distance += pow( mean[ d ] - new_mean[ d ], 2 ); } distance = sqrt( distance ); eo::log << eo::logging << "mean: " << mean << std::endl << "new mean: " << new_mean << std::endl << "distance: " << distance << std::endl ; return 0; }
int make(int argc, char **argv) { Environment e; init(e); std::vector<std::string> args; args.reserve(argc+1); int c; bool passthrough = false; static struct option longopts[] = { { "help", no_argument, nullptr, 'h' }, { "verbose", no_argument, nullptr, 'v' }, { "test", no_argument, nullptr, 1 }, { "dry-run", no_argument, nullptr, 2 }, { nullptr, 0, nullptr, 0}, }; args.push_back(""); // place-holder. while ((c = getopt_long(argc, argv, "d:ef:i:prstuvwy", longopts, nullptr)) != -1) { std::string flag = "-"; flag.push_back(c); switch(c) { default: make_help(); return EX_USAGE; case 'h': make_help(); return 0; case 1: e.set("test", 1); break; case 2: passthrough = true; break; case 'd': case 'f': case 'i': args.push_back(std::move(flag)); args.push_back(optarg); break; case 'e': case 'p': case 't': case 'u': case 'v': case 'w': case 'y': args.push_back(std::move(flag)); break; case 'r': case 's': args.push_back(std::move(flag)); passthrough = true; break; } } argc -= optind; argv += optind; std::transform(argv, argv+argc, std::back_inserter(args), [](const char *cp){ return std::string(cp); }); e.startup(true); read_file(e, root() / "Startup"); e.startup(false); auto path = which(e, "Make"); if (path.empty()) { fputs("### MPW Shell - Command \"Make\" was not found.\n", stderr); return -1; } e.set("command", path); args[0] = path; if (passthrough) { launch_mpw(e, args, fdmask()); exit(EX_OSERR); } return read_make(e, args); }
//Main Program int main(int argc, char* argv[]) { try { std::cout << "Metaheuristic for the (SMP)² compiled at " << __DATE__ << " " << __TIME__; std::cout << std::endl << std::endl; // Read and set user parameters // Initialize parser eoParser parser(argc, argv); std::cout << "Loading Problem ... " << std::endl; std::string fileName = "../../problems/Test4-10-5.dat"; std::cout << fileName; // needed, so rng works in other classes .... rng.rand(); // create a problem instance and load the file SMP2 p(fileName); std::cout << " ... loaded. " << std::endl << std::endl; /*{ // define Problem evaluation cuntions SMP2_Eval problem_eval; // Initialize the problem to a semi-greedy solution p.GRASPInit(0.1); // evaluate the radomized solutions problem_eval(p); p.printSolution(); std::cout << "Initial Fitness: " << p.fitness() << std::endl; // define the adjecent Swap Neighborhood and a Neighbor SMP2_Flip_Neighbor n1; SMP2_AdjElementFlip_Neighborhood nh; // initialize Incremental Evaluation SMP2_ElementFlip_IncrEval neighbor_eval(p); // initialize the nighrborhood nh.init(p, n1); /*std::cout << "First possible Flip: "; n1.print(); // calculate new fitness with incrementa evaluation neighbor_eval(p, n1); std::cout << "New Fitness should be: " << n1 << std::endl<<std::endl; */ /*// get result using full evaluation for comparision and error detection std::cout << "Performing Flip." << std::endl; n1.move(p); p.printSolution(); p.fullEvaluation(); std::cout << "New Fitness is: " << p.fitness() << std::endl << std::endl; // show the next possible moves: std::cout << "Next possible moves in neighborhood are: " << std::endl; neighbor_eval(p, n1); std::cout << n1 << " -> "; n1.print(); while(nh.cont(p)) { nh.next(p,n1); neighbor_eval(p,n1); std::cout << n1 << "-> "; n1.print(); } } // */ // Test if the the RCL with Alpha = 1 return the same results as a purely random assignment { // Make some experiments with Greedy-Initilaization and compare them to RandomInitialization int trys = 1000; double alpha = 1.1; double ResRandom = 0; double ResGreedy = 0; for (alpha = 0.0; alpha <= 1; alpha = alpha + 0.025) { ResGreedy = 0; for (int i = 0; i < trys; i++) { p.GRASPInit(alpha); p.fullEvaluation(); ResGreedy += p.fitness(); } std::cout << "Average Greedy Result: " << ResGreedy / trys << " (alpha = " << alpha << ")" << std::endl; } // */ // do it for a manual alpha = 1, since the adding up (above) does not work to good on doubles and does not consider the entire RCL // this value for alpha = 1 is compared with the random construction to validate the implementation // for alpha = 1 the Greedy-Construction should behave like a purely random assignment ResGreedy = 0; alpha = 1.0001; for (int i = 0; i < trys; i++) { p.GRASPInit(alpha); p.fullEvaluation(); ResGreedy += p.fitness(); } std::cout << "Average Greedy Result: " << ResGreedy / trys << " (alpha = " << alpha << ")" << std::endl; for (int i = 0; i < trys; i++) { p.RandomInit(); p.fullEvaluation(); ResRandom += p.fitness(); } std::cout << "Average Random Result: " << ResRandom / trys << std::endl; } // */ /* Test if file could be read .... */ // test if matrix could be read // FIXME: Write a test for this... /*{ int ** DSM = p.GetDSM(); std::cout << DSM[2][2] << std::endl; // test if pathDef could be read bool ** PathDef = p.GetPathDef(); std::cout << PathDef[1][0] << PathDef[1][1] << PathDef[1][2] << std::endl; // test if pathProb could be read double * PathProb = p.GetPathProb(); std::cout << PathProb[0] << " + " << PathProb[1] << " = " << PathProb[0] + PathProb[1] << std::endl; // test if interCost could be read double * interCost= p.GetInterCosts(); std::cout << interCost[0] << " + " << interCost[1] << std::endl; // test if interMax could be read int * interMax= p.GetInterMaxSize(); std::cout << interMax[0] << " + " << interMax[1] << std::endl; // test if intraCost could be read double * intraCost= p.GetIntraCosts(); std::cout << intraCost[0] << " + " << interCost[1] << std::endl; // test if intraMax could be read int * intraMax= p.GetIntraMaxSize(); std::cout << intraMax[0] << " + " << intraMax[1] << std::endl; } //*/ // Test evaluation fuction and caclulate a known optimal solution for Test4-10-5.dat // FIXME: Write a test for this... { // initialize some solution std::cout << "Initialize to optimal solution ... Objective Fuction Value should be 69.71 " << std::endl; p.solution[0] = 0; //A p.solution[1] = 1; //B p.solution[2] = 2; //C p.solution[3] = 1; //D p.solution[4] = 1; //E p.solution[5] = 1; //F p.solution[6] = 0; //G p.solution[7] = 0; //H p.solution[8] = 2; //I p.solution[9] = 0; //J // print new solution p.printSolution(); p.fullEvaluation(); p.printFitness(); std::cout << std::endl << std::endl; // randomly initililze and print solution and fitness p.RandomInit(); p.printSolution(); p.fullEvaluation(); p.printFitness(); } //*/ make_help(parser); } catch(std::exception& e) { std::cout << e.what() << std::endl; } return EXIT_SUCCESS; }
int the_main(int argc, char **argv) { eoParser parser(argc, argv); // random seed eoValueParam<uint32_t>& seedParam = parser.createParam(uint32_t(0), "seed", "Random number seed", 'S'); if (seedParam.value() == 0) seedParam.value() = time(0); rng.reseed(seedParam.value()); // pSize global variable ! eoValueParam<unsigned> pSizeParam = parser.createParam(unsigned(10), "parentSize", "Parent size",'P'); pSize = pSizeParam.value(); eoHowMany oRate = parser.createParam(eoHowMany(1.0), "offsrpringRate", "Offsrpring rate (% or absolute)",'O').value(); eoHowMany fRate = parser.createParam(eoHowMany(1.0), "fertileRate", "Fertility rate (% or absolute)",'F').value(); double nicheSize = parser.createParam(0.1, "nicheSize", "Paramter Sigma for Sharing",'\0').value(); eoParamParamType & peakParam = parser.createParam(eoParamParamType("2(1,2)"), "peaks", "Description of the peaks: N(nb1,nb2,...,nbN)", 'p').value(); // the number of peaks: first item of the paramparam unsigned peakNumber = atoi(peakParam.first.c_str()); if (peakNumber < 2) { std::cerr << "WARNING, nb of peaks must be larger than 2, using 2" << std::endl; peakNumber = 2; } std::vector<unsigned> nbIndiPerPeak(peakNumber); unsigned i, sum=0; // the second item is a vector<string> containing all values if (!peakParam.second.size()) // no other parameter : equal peaks { std::cerr << "WARNING, no nb of indis per peaks, using equal nbs" << std::endl; for (i=0; i<peakNumber; i++) nbIndiPerPeak[i] = pSize/peakNumber; } else // parameters passed by user if (peakParam.second.size() != peakNumber) { std::cerr << "ERROR, not enough nb of indis per peaks" << std::endl; exit(1); } else // now we have in peakParam.second all numbers { for (i=0; i<peakNumber; i++) sum += ( nbIndiPerPeak[i] = atoi(peakParam.second[i].c_str()) ); // now normalize for (i=0; i<peakNumber; i++) nbIndiPerPeak[i] = nbIndiPerPeak[i] * pSize / sum; } // compute exact total sum = 0; for (i=0; i<peakNumber; i++) sum += nbIndiPerPeak[i]; if (sum != pSize) { pSize = pSizeParam.value() = sum; std::cerr << "WARNING, adjusting pSize to " << pSize << std::endl; } make_help(parser); // hard-coded directory name ... std::cout << "Testing the Sharing\n"; std::cout << " There will be " << peakNumber << " peaks"; std::cout << " with respective pops "; for (i=0; i<peakNumber; i++) std::cout << nbIndiPerPeak[i] << ", "; std::cout << "\n Peaks are at distance 1 from one-another (dim 1),\n"; std::cout << " fitness of each peak is nb of peak, and\n"; std::cout << " fitness of individuals = uniform[fitness of peak +- 0.01]\n\n"; std::cout << "The resulting file (in dir ResSelect), contains \n"; std::cout << " the empirical proba. for each indi to be selected." << std::endl; system("mkdir ResSelect"); // initialize parent population parentsOrg.resize(pSize); // all peaks of equal size in fitness, with different nn of individuals unsigned index=0; for (unsigned nbP=0; nbP<peakNumber; nbP++) for (i=0; i<nbIndiPerPeak[nbP]; i++) { parentsOrg[index].fitness(nbP+1 + 0.02*eo::rng.uniform() - 0.01); parentsOrg[index].xdist = nbP+1 + 0.02*eo::rng.uniform() - 0.01; index++; } std::cout << "Initial population\n" << parentsOrg << std::endl; char fileName[1024]; // the selection procedures under test // eoDetSelect<Dummy> detSelect(oRate); // testSelectMany(detSelect, "detSelect"); // Sharing using the perf2Worth construct // need a distance for that eoDummyDistance dist; eoSharingSelect<Dummy> newSharingSelect(nicheSize, dist); sprintf(fileName,"Niche_%g",nicheSize); testSelectOne<Dummy>(newSharingSelect, oRate, fRate, fileName); return 1; }
int main (int argc, char *argv[]) { /************************* * Initialisation de MPI * *************************/ boost::mpi::environment env(argc, argv, MPI_THREAD_MULTIPLE, true); boost::mpi::communicator world; /**************************** * Il faut au moins 4 nœuds * ****************************/ const size_t ALL = world.size(); const size_t RANK = world.rank(); /************************ * Initialisation de EO * ************************/ eoParser parser(argc, argv); eoState state; // keeps all things allocated dim::core::State state_dim; // keeps all things allocated /***************************** * Definition des paramètres * *****************************/ bool sync = parser.createParam(bool(true), "sync", "sync", 0, "Islands Model").value(); bool smp = parser.createParam(bool(true), "smp", "smp", 0, "Islands Model").value(); unsigned nislands = parser.createParam(unsigned(4), "nislands", "Number of islands (see --smp)", 0, "Islands Model").value(); // a double alphaP = parser.createParam(double(0.2), "alpha", "Alpha Probability", 'a', "Islands Model").value(); double alphaF = parser.createParam(double(0.01), "alphaF", "Alpha Fitness", 'A', "Islands Model").value(); // b double betaP = parser.createParam(double(0.01), "beta", "Beta Probability", 'b', "Islands Model").value(); // d double probaSame = parser.createParam(double(100./(smp ? nislands : ALL)), "probaSame", "Probability for an individual to stay in the same island", 'd', "Islands Model").value(); // I bool initG = parser.createParam(bool(true), "initG", "initG", 'I', "Islands Model").value(); bool update = parser.createParam(bool(true), "update", "update", 'U', "Islands Model").value(); bool feedback = parser.createParam(bool(true), "feedback", "feedback", 'F', "Islands Model").value(); bool migrate = parser.createParam(bool(true), "migrate", "migrate", 'M', "Islands Model").value(); unsigned nmigrations = parser.createParam(unsigned(1), "nmigrations", "Number of migrations to do at each generation (0=all individuals are migrated)", 0, "Islands Model").value(); unsigned stepTimer = parser.createParam(unsigned(1000), "stepTimer", "stepTimer", 0, "Islands Model").value(); bool deltaUpdate = parser.createParam(bool(true), "deltaUpdate", "deltaUpdate", 0, "Islands Model").value(); bool deltaFeedback = parser.createParam(bool(true), "deltaFeedback", "deltaFeedback", 0, "Islands Model").value(); double sensitivity = 1 / parser.createParam(double(1.), "sensitivity", "sensitivity of delta{t} (1/sensitivity)", 0, "Islands Model").value(); std::string rewardStrategy = parser.createParam(std::string("avg"), "rewardStrategy", "Strategy of rewarding: best or avg", 0, "Islands Model").value(); std::vector<double> rewards(smp ? nislands : ALL, 1.); std::vector<double> timeouts(smp ? nislands : ALL, 1.); for (size_t i = 0; i < (smp ? nislands : ALL); ++i) { std::ostringstream ss; ss << "reward" << i; rewards[i] = parser.createParam(double(1.), ss.str(), ss.str(), 0, "Islands Model").value(); ss.str(""); ss << "timeout" << i; timeouts[i] = parser.createParam(double(1.), ss.str(), ss.str(), 0, "Islands Model").value(); } /********************************* * Déclaration des composants EO * *********************************/ unsigned chromSize = parser.getORcreateParam(unsigned(0), "chromSize", "The length of the bitstrings", 'n',"Problem").value(); eoInit<EOT>& init = dim::do_make::genotype(parser, state, EOT(), 0); eoEvalFunc<EOT>* ptEval = NULL; ptEval = new SimulatedEval( rewards[RANK] ); state.storeFunctor(ptEval); eoEvalFuncCounter<EOT> eval(*ptEval); unsigned popSize = parser.getORcreateParam(unsigned(100), "popSize", "Population Size", 'P', "Evolution Engine").value(); dim::core::Pop<EOT>& pop = dim::do_make::detail::pop(parser, state, init); double targetFitness = parser.getORcreateParam(double(1000), "targetFitness", "Stop when fitness reaches",'T', "Stopping criterion").value(); unsigned maxGen = parser.getORcreateParam(unsigned(0), "maxGen", "Maximum number of generations () = none)",'G',"Stopping criterion").value(); dim::continuator::Base<EOT>& continuator = dim::do_make::continuator<EOT>(parser, state, eval); dim::core::IslandData<EOT> data(smp ? nislands : -1); std::string monitorPrefix = parser.getORcreateParam(std::string("result"), "monitorPrefix", "Monitor prefix filenames", '\0', "Output").value(); dim::utils::CheckPoint<EOT>& checkpoint = dim::do_make::checkpoint<EOT>(parser, state, continuator, data, 1, stepTimer); /************** * EO routine * **************/ make_parallel(parser); make_verbose(parser); make_help(parser); if (!smp) // no smp enabled use mpi instead { /**************************************** * Distribution des opérateurs aux iles * ****************************************/ eoMonOp<EOT>* ptMon = NULL; if (sync) { ptMon = new DummyOp; } else { ptMon = new SimulatedOp( timeouts[RANK] ); } state.storeFunctor(ptMon); /********************************** * Déclaration des composants DIM * **********************************/ dim::core::ThreadsRunner< EOT > tr; dim::evolver::Easy<EOT> evolver( /*eval*/*ptEval, *ptMon, false ); dim::feedbacker::Base<EOT>* ptFeedbacker = NULL; if (feedback) { if (sync) { ptFeedbacker = new dim::feedbacker::sync::Easy<EOT>(alphaF); } else { ptFeedbacker = new dim::feedbacker::async::Easy<EOT>(alphaF, sensitivity, deltaFeedback); } } else { ptFeedbacker = new dim::algo::Easy<EOT>::DummyFeedbacker(); } state_dim.storeFunctor(ptFeedbacker); dim::vectorupdater::Base<EOT>* ptUpdater = NULL; if (update) { dim::vectorupdater::Reward<EOT>* ptReward = NULL; if (rewardStrategy == "best") { ptReward = new dim::vectorupdater::Best<EOT>(alphaP, betaP); } else { ptReward = new dim::vectorupdater::Average<EOT>(alphaP, betaP, sensitivity, sync ? false : deltaUpdate); } state_dim.storeFunctor(ptReward); ptUpdater = new dim::vectorupdater::Easy<EOT>(*ptReward); } else { ptUpdater = new dim::algo::Easy<EOT>::DummyVectorUpdater(); } state_dim.storeFunctor(ptUpdater); dim::memorizer::Easy<EOT> memorizer; dim::migrator::Base<EOT>* ptMigrator = NULL; if (migrate) { if (sync) { ptMigrator = new dim::migrator::sync::Easy<EOT>(); } else { ptMigrator = new dim::migrator::async::Easy<EOT>(nmigrations); } } else { ptMigrator = new dim::algo::Easy<EOT>::DummyMigrator(); } state_dim.storeFunctor(ptMigrator); dim::algo::Easy<EOT> island( evolver, *ptFeedbacker, *ptUpdater, memorizer, *ptMigrator, checkpoint, monitorPrefix ); if (!sync) { tr.addHandler(*ptFeedbacker).addHandler(*ptMigrator).add(island); } /*************** * Rock & Roll * ***************/ /****************************************************************************** * Création de la matrice de transition et distribution aux iles des vecteurs * ******************************************************************************/ dim::core::MigrationMatrix probabilities( ALL ); dim::core::InitMatrix initmatrix( initG, probaSame ); if ( 0 == RANK ) { initmatrix( probabilities ); std::cout << probabilities; data.proba = probabilities(RANK); for (size_t i = 1; i < ALL; ++i) { world.send( i, 100, probabilities(i) ); } std::cout << "Island Model Parameters:" << std::endl << "alphaP: " << alphaP << std::endl << "alphaF: " << alphaF << std::endl << "betaP: " << betaP << std::endl << "probaSame: " << probaSame << std::endl << "initG: " << initG << std::endl << "update: " << update << std::endl << "feedback: " << feedback << std::endl << "migrate: " << migrate << std::endl << "sync: " << sync << std::endl << "stepTimer: " << stepTimer << std::endl << "deltaUpdate: " << deltaUpdate << std::endl << "deltaFeedback: " << deltaFeedback << std::endl << "sensitivity: " << sensitivity << std::endl << "chromSize: " << chromSize << std::endl << "popSize: " << popSize << std::endl << "targetFitness: " << targetFitness << std::endl << "maxGen: " << maxGen << std::endl ; } else { world.recv( 0, 100, data.proba ); } /****************************************** * Get the population size of all islands * ******************************************/ world.barrier(); dim::utils::print_sum(pop); FitnessInit fitInit; apply<EOT>(fitInit, pop); if (sync) { island( pop, data ); } else { tr( pop, data ); } world.abort(0); return 0 ; } // smp /********************************** * Déclaration des composants DIM * **********************************/ dim::core::ThreadsRunner< EOT > tr; std::vector< dim::core::Pop<EOT> > islandPop(nislands); std::vector< dim::core::IslandData<EOT> > islandData(nislands); dim::core::MigrationMatrix probabilities( nislands ); dim::core::InitMatrix initmatrix( initG, probaSame ); initmatrix( probabilities ); std::cout << probabilities; FitnessInit fitInit; for (size_t i = 0; i < nislands; ++i) { std::cout << "island " << i << std::endl; islandPop[i].append(popSize, init); apply<EOT>(fitInit, islandPop[i]); islandData[i] = dim::core::IslandData<EOT>(nislands, i); std::cout << islandData[i].size() << " " << islandData[i].rank() << std::endl; islandData[i].proba = probabilities(i); apply<EOT>(eval, islandPop[i]); /**************************************** * Distribution des opérateurs aux iles * ****************************************/ eoMonOp<EOT>* ptMon = NULL; ptMon = new SimulatedOp( timeouts[islandData[i].rank()] ); state.storeFunctor(ptMon); eoEvalFunc<EOT>* __ptEval = NULL; __ptEval = new SimulatedEval( rewards[islandData[i].rank()] ); state.storeFunctor(__ptEval); dim::evolver::Base<EOT>* ptEvolver = new dim::evolver::Easy<EOT>( /*eval*/*__ptEval, *ptMon, false ); state_dim.storeFunctor(ptEvolver); dim::feedbacker::Base<EOT>* ptFeedbacker = new dim::feedbacker::smp::Easy<EOT>(islandPop, islandData, alphaF); state_dim.storeFunctor(ptFeedbacker); dim::vectorupdater::Reward<EOT>* ptReward = NULL; if (rewardStrategy == "best") { ptReward = new dim::vectorupdater::Best<EOT>(alphaP, betaP); } else { ptReward = new dim::vectorupdater::Average<EOT>(alphaP, betaP, sensitivity, sync ? false : deltaUpdate); } state_dim.storeFunctor(ptReward); dim::vectorupdater::Base<EOT>* ptUpdater = new dim::vectorupdater::Easy<EOT>(*ptReward); state_dim.storeFunctor(ptUpdater); dim::memorizer::Base<EOT>* ptMemorizer = new dim::memorizer::Easy<EOT>(); state_dim.storeFunctor(ptMemorizer); dim::migrator::Base<EOT>* ptMigrator = new dim::migrator::smp::Easy<EOT>(islandPop, islandData, monitorPrefix); state_dim.storeFunctor(ptMigrator); dim::utils::CheckPoint<EOT>& checkpoint = dim::do_make::checkpoint<EOT>(parser, state, continuator, islandData[i], 1, stepTimer); dim::algo::Base<EOT>* ptIsland = new dim::algo::smp::Easy<EOT>( *ptEvolver, *ptFeedbacker, *ptUpdater, *ptMemorizer, *ptMigrator, checkpoint, islandPop, islandData, monitorPrefix ); state_dim.storeFunctor(ptIsland); ptEvolver->size(nislands); ptFeedbacker->size(nislands); ptReward->size(nislands); ptUpdater->size(nislands); ptMemorizer->size(nislands); ptMigrator->size(nislands); ptIsland->size(nislands); ptEvolver->rank(i); ptFeedbacker->rank(i); ptReward->rank(i); ptUpdater->rank(i); ptMemorizer->rank(i); ptMigrator->rank(i); ptIsland->rank(i); tr.add(*ptIsland); } tr(pop, data); return 0 ; }