示例#1
0
//This function reads the position where the user clicks to determine the desired action
pair< ActionType, vector<GridItem*> > Input::GetUserAction() const
{	
	vector<GridItem*> ReturnedPointers;
	int x,y;
	clicktype Clk;
	Clk=pWind->WaitMouseClick(x, y);	//Get the coordinates of the user click
	GridItem*tmp = NULL;
	tmp = Interface->getAction(GraphicsInfo(x, y));
	if (tmp == NULL)
		return make_pair(DSN_AREA,ReturnedPointers);
	else

	{
		ReturnedPointers.push_back(tmp);
		if (Clk == LEFT_CLICK)
		{
			
			return make_pair(tmp->Leftpress(), ReturnedPointers);
		}
		else if (Clk == RIGHT_CLICK)
		{
			return make_pair(tmp->RightPress(), ReturnedPointers);
		}
		else if (Clk == NO_CLICK)
		{
			tmp->hover();
			GetUserAction();
		}
	}

}
示例#2
0
文件: worhp.cpp 项目: osm3000/pagmo
/**
 * Run the WORHP algorithm.
 *
 * @param[in,out] pop input/output pagmo::population to be evolved.
 */
void worhp::evolve(pagmo::population& pop) const {
	if (pop.size() == 0) {
		return;
	}

	const auto& prob = pop.problem();

	if (prob.get_i_dimension() != 0) {
		pagmo_throw(value_error,
		            "The problem has an integer part and WORHP is not suitable to solve it.");
	}

	if (prob.get_f_dimension() != 1) {
		pagmo_throw(value_error,
		            "The problem is not single objective and WORHP is not suitable to solve it");
	}

	// We check the screen output again as the user may have changed it
	if (m_screen_output) {
		SetWorhpPrint(default_output);
	} else {
		SetWorhpPrint(no_screen_output);
	}

	OptVar opt;
	Control control;
	Params params;
	Workspace workspace;

	opt.initialised = false;
	control.initialised = false;
	params.initialised = false;
	workspace.initialised = false;


	opt.n = prob.get_dimension(); // number of variables
	opt.m = prob.get_c_dimension(); // number of constraints
	auto n_eq = prob.get_c_dimension() - prob.get_ic_dimension(); // number of equality constraints

	// specify nonzeros of derivative matrixes
	workspace.DF.nnz = opt.n; // dense
	workspace.DG.nnz = opt.n * opt.m; // dense
	workspace.HM.nnz = opt.n;


	WorhpInit(&opt, &workspace, &params, &control);
	assert(control.status == FirstCall);
	params = m_params;

    // Specify a derivative free case
	params.UserDF = false;
	params.UserDG = false;
	params.UserHM = false;
	params.initialised = true;

	// Initialization of variables
	const auto best_idx = pop.get_best_idx();
	pagmo::decision_vector x = pop.get_individual(best_idx).cur_x;

	for (int i = 0; i < opt.n; ++i) {
		opt.X[i] = x[i];
		opt.Lambda[i] = 0;
		opt.XL[i] = prob.get_lb()[i];
		opt.XU[i] = prob.get_ub()[i];
	}

	// Equality constraints
	for (auto i = 0u; i < n_eq; ++i) {
		opt.Mu[i] = 0;
		opt.GL[i] = 0;
		opt.GU[i] = 0;
	}

	// Inequality constraints
	for (auto i = n_eq; i < unsigned(opt.m); ++i) {
		opt.Mu[i] = 0;
		opt.GL[i] = -params.Infty;
		opt.GU[i] = 0;
	}

	// Define HM as a diagonal LT-CS-matrix, but only if needed by WORHP
	// Not sure if this is needed at all
	if (workspace.HM.NeedStructure) {
		for(int i = 0; i < workspace.HM.nnz; ++i) 
		{
			workspace.HM.row[i] = i + 1;
			workspace.HM.col[i] = i + 1;
		}
	}

	while (control.status < TerminateSuccess && control.status > TerminateError) {
		if (GetUserAction(&control, callWorhp)) {
			Worhp(&opt, &workspace, &params, &control);
		}

		if (GetUserAction(&control, iterOutput)) 
		{
			IterationOutput(&opt, &workspace, &params, &control);
			DoneUserAction(&control, iterOutput);
		}

		
		if (GetUserAction(&control, evalF)) {
			for (int i = 0; i < opt.n; ++i) {
				x[i] = opt.X[i];
			}
			auto f = prob.objfun(x);
			opt.F = workspace.ScaleObj * f[0];
			DoneUserAction(&control, evalF);
		}

		if (GetUserAction(&control, evalG)) {
			for (int i = 0; i < opt.n; ++i) {
				x[i] = opt.X[i];
			}
			auto g = prob.compute_constraints(x);
			for (int i = 0; i < opt.m; ++i) {
				opt.G[i] = g[i];
			}
			DoneUserAction(&control, evalG);
		}

		if (GetUserAction(&control, fidif)) {
			WorhpFidif(&opt, &workspace, &params, &control);
		}
	}

	for (int i = 0; i < opt.n; ++i) {
		x[i] = opt.X[i];
	}
	pop.set_x(best_idx, x);

	StatusMsg(&opt, &workspace, &params, &control);
	WorhpFree(&opt, &workspace, &params, &control);
}
示例#3
0
  int WorhpInterface::solve(void* mem) const {
    auto m = static_cast<WorhpMemory*>(mem);

    if (m->lbg && m->ubg) {
      for (casadi_int i=0; i<ng_; ++i) {
        casadi_assert(!(m->lbg[i]==-inf && m->ubg[i] == inf),
                        "WorhpInterface::evaluate: Worhp cannot handle the case when both "
                        "LBG and UBG are infinite."
                        "You have that case at non-zero " + str(i)+ "."
                        "Reformulate your problem eliminating the corresponding constraint.");
      }
    }

    // Pass inputs to WORHP data structures
    casadi_copy(m->x, nx_, m->worhp_o.X);
    casadi_copy(m->lbx, nx_, m->worhp_o.XL);
    casadi_copy(m->ubx, nx_, m->worhp_o.XU);
    casadi_copy(m->lam_x, nx_, m->worhp_o.Lambda);
    if (m->worhp_o.m>0) {
      casadi_copy(m->lam_g, ng_, m->worhp_o.Mu);
      casadi_copy(m->lbg, ng_, m->worhp_o.GL);
      casadi_copy(m->ubg, ng_, m->worhp_o.GU);
    }

    // Replace infinite bounds with m->worhp_p.Infty
    double inf = numeric_limits<double>::infinity();
    for (casadi_int i=0; i<nx_; ++i)
      if (m->worhp_o.XL[i]==-inf) m->worhp_o.XL[i] = -m->worhp_p.Infty;
    for (casadi_int i=0; i<nx_; ++i)
      if (m->worhp_o.XU[i]== inf) m->worhp_o.XU[i] =  m->worhp_p.Infty;
    for (casadi_int i=0; i<ng_; ++i)
      if (m->worhp_o.GL[i]==-inf) m->worhp_o.GL[i] = -m->worhp_p.Infty;
    for (casadi_int i=0; i<ng_; ++i)
      if (m->worhp_o.GU[i]== inf) m->worhp_o.GU[i] =  m->worhp_p.Infty;

    if (verbose_) casadi_message("WorhpInterface::starting iteration");

    bool firstIteration = true;

    // Reverse Communication loop
    while (m->worhp_c.status < TerminateSuccess &&  m->worhp_c.status > TerminateError) {
      if (GetUserAction(&m->worhp_c, callWorhp)) {
        Worhp(&m->worhp_o, &m->worhp_w, &m->worhp_p, &m->worhp_c);
      }


      if (GetUserAction(&m->worhp_c, iterOutput)) {

        if (!firstIteration) {
          firstIteration = true;

          if (!fcallback_.is_null()) {
            m->iter = m->worhp_w.MajorIter;
            m->iter_sqp = m->worhp_w.MinorIter;
            m->inf_pr = m->worhp_w.NormMax_CV;
            m->inf_du = m->worhp_p.ScaledKKT;
            m->alpha_pr = m->worhp_w.ArmijoAlpha;

            // Inputs
            fill_n(m->arg, fcallback_.n_in(), nullptr);
            m->arg[NLPSOL_X] = m->worhp_o.X;
            m->arg[NLPSOL_F] = &m->worhp_o.F;
            m->arg[NLPSOL_G] = m->worhp_o.G;
            m->arg[NLPSOL_LAM_P] = nullptr;
            m->arg[NLPSOL_LAM_X] = m->worhp_o.Lambda;
            m->arg[NLPSOL_LAM_G] = m->worhp_o.Mu;

            // Outputs
            fill_n(m->res, fcallback_.n_out(), nullptr);
            double ret_double;
            m->res[0] = &ret_double;

            m->fstats.at("callback_fun").tic();
            // Evaluate the callback function
            fcallback_(m->arg, m->res, m->iw, m->w, 0);
            m->fstats.at("callback_fun").toc();
            casadi_int ret = static_cast<casadi_int>(ret_double);

            if (ret) m->worhp_c.status = TerminateError;
          }
        }


        IterationOutput(&m->worhp_o, &m->worhp_w, &m->worhp_p, &m->worhp_c);
        DoneUserAction(&m->worhp_c, iterOutput);
      }

      if (GetUserAction(&m->worhp_c, evalF)) {
        m->arg[0] = m->worhp_o.X;
        m->arg[1] = m->p;
        m->res[0] = &m->worhp_o.F;
        calc_function(m, "nlp_f");
        m->f = m->worhp_o.F; // Store cost, before scaling
        m->worhp_o.F *= m->worhp_w.ScaleObj;
        DoneUserAction(&m->worhp_c, evalF);
      }

      if (GetUserAction(&m->worhp_c, evalG)) {
        m->arg[0] = m->worhp_o.X;
        m->arg[1] = m->p;
        m->res[0] = m->worhp_o.G;
        calc_function(m, "nlp_g");
        DoneUserAction(&m->worhp_c, evalG);
      }

      if (GetUserAction(&m->worhp_c, evalDF)) {
        m->arg[0] = m->worhp_o.X;
        m->arg[1] = m->p;
        m->res[0] = nullptr;
        m->res[1] = m->worhp_w.DF.val;
        calc_function(m, "nlp_grad_f");
        casadi_scal(nx_, m->worhp_w.ScaleObj, m->worhp_w.DF.val);
        DoneUserAction(&m->worhp_c, evalDF);
      }

      if (GetUserAction(&m->worhp_c, evalDG)) {
        m->arg[0] = m->worhp_o.X;
        m->arg[1] = m->p;
        m->res[0] = nullptr;
        m->res[1] = m->worhp_w.DG.val;
        calc_function(m, "nlp_jac_g");
        DoneUserAction(&m->worhp_c, evalDG);
      }

      if (GetUserAction(&m->worhp_c, evalHM)) {
        m->arg[0] = m->worhp_o.X;
        m->arg[1] = m->p;
        m->arg[2] = &m->worhp_w.ScaleObj;
        m->arg[3] = m->worhp_o.Mu;
        m->res[0] = m->worhp_w.HM.val;
        calc_function(m, "nlp_hess_l");
        // Diagonal values
        double *dval = m->w;
        casadi_fill(dval, nx_, 0.);

        // Remove diagonal
        const casadi_int* colind = hesslag_sp_.colind();
        const casadi_int* row = hesslag_sp_.row();
        casadi_int ind=0;
        for (casadi_int c=0; c<nx_; ++c) {
          for (casadi_int el=colind[c]; el<colind[c+1]; ++el) {
            if (row[el]==c) {
              dval[c] = m->worhp_w.HM.val[el];
            } else {
              m->worhp_w.HM.val[ind++] = m->worhp_w.HM.val[el];
            }
          }
        }

        // Add diagonal entries at the end
        casadi_copy(dval, nx_, m->worhp_w.HM.val+ind);
        DoneUserAction(&m->worhp_c, evalHM);
      }

      if (GetUserAction(&m->worhp_c, fidif)) {
        WorhpFidif(&m->worhp_o, &m->worhp_w, &m->worhp_p, &m->worhp_c);
      }
    }

    // Copy outputs
    casadi_copy(m->worhp_o.X, nx_, m->x);
    casadi_copy(m->worhp_o.G, ng_, m->g);
    casadi_copy(m->worhp_o.Lambda, nx_, m->lam_x);
    casadi_copy(m->worhp_o.Mu, ng_, m->lam_g);

    StatusMsg(&m->worhp_o, &m->worhp_w, &m->worhp_p, &m->worhp_c);

    m->return_code = m->worhp_c.status;
    m->return_status = return_codes(m->worhp_c.status);
    m->success = m->return_code > TerminateSuccess;
    return 0;
  }
示例#4
0
  void WorhpInternal::evaluate(){
    log("WorhpInternal::evaluate");
    
    if (gather_stats_) {
      Dictionary iterations;
      iterations["iter_sqp"] = std::vector<int>();
      iterations["inf_pr"] = std::vector<double>();
      iterations["inf_du"] = std::vector<double>();
      iterations["obj"] = std::vector<double>();
      iterations["alpha_pr"] = std::vector<double>();
      stats_["iterations"] = iterations;
    }
    
    // Prepare the solver
    reset();
    
    if (inputs_check_) checkInputs();
    checkInitialBounds();
  
    // Reset the counters
    t_eval_f_ = t_eval_grad_f_ = t_eval_g_ = t_eval_jac_g_ = t_eval_h_ = t_callback_fun_ = t_callback_prepare_ = t_mainloop_ = 0;
    
    n_eval_f_ = n_eval_grad_f_ = n_eval_g_ = n_eval_jac_g_ = n_eval_h_ = 0;
  
    // Get inputs
    log("WorhpInternal::evaluate: Reading user inputs");
    const DMatrix& x0 = input(NLP_SOLVER_X0);    
    const DMatrix& lbx = input(NLP_SOLVER_LBX);
    const DMatrix& ubx = input(NLP_SOLVER_UBX);
    const DMatrix& lam_x0 = input(NLP_SOLVER_LAM_X0);
    const DMatrix& lbg = input(NLP_SOLVER_LBG);
    const DMatrix& ubg = input(NLP_SOLVER_UBG);
    const DMatrix& lam_g0 = input(NLP_SOLVER_LAM_G0);

    double inf = numeric_limits<double>::infinity();  

    for (int i=0;i<nx_;++i) {
      casadi_assert_message(lbx.at(i)!=ubx.at(i),"WorhpSolver::evaluate: Worhp cannot handle the case when LBX == UBX. You have that case at non-zero " << i << " , which has value " << ubx.at(i) << ". Reformulate your problem by using a parameter for the corresponding variable.");
    }
  
    for (int i=0;i<lbg.size();++i) {
      casadi_assert_message(!(lbg.at(i)==-inf && ubg.at(i) == inf),"WorhpSolver::evaluate: Worhp cannot handle the case when both LBG and UBG are infinite. You have that case at non-zero " << i << ". Reformulate your problem eliminating the corresponding constraint.");
    }

    // Pass inputs to WORHP data structures
    x0.getArray(worhp_o_.X,worhp_o_.n);
    lbx.getArray(worhp_o_.XL,worhp_o_.n);
    ubx.getArray(worhp_o_.XU,worhp_o_.n);
    lam_x0.getArray(worhp_o_.Lambda,worhp_o_.n);
    if (worhp_o_.m>0){
      lam_g0.getArray(worhp_o_.Mu,worhp_o_.m);
      lbg.getArray(worhp_o_.GL,worhp_o_.m);
      ubg.getArray(worhp_o_.GU,worhp_o_.m);
    }

    // Replace infinite bounds with worhp_p_.Infty
    for(int i=0; i<nx_; ++i) if(worhp_o_.XL[i]==-inf) worhp_o_.XL[i] = -worhp_p_.Infty;
    for(int i=0; i<nx_; ++i) if(worhp_o_.XU[i]== inf) worhp_o_.XU[i] =  worhp_p_.Infty;
    for(int i=0; i<ng_; ++i) if(worhp_o_.GL[i]==-inf) worhp_o_.GL[i] = -worhp_p_.Infty;
    for(int i=0; i<ng_; ++i) if(worhp_o_.GU[i]== inf) worhp_o_.GU[i] =  worhp_p_.Infty;
  
    log("WorhpInternal::starting iteration");

    double time1 = clock();
  
    // Reverse Communication loop
    while(worhp_c_.status < TerminateSuccess &&  worhp_c_.status > TerminateError) {
      if (GetUserAction(&worhp_c_, callWorhp)) {
        Worhp(&worhp_o_, &worhp_w_, &worhp_p_, &worhp_c_);
      }


      if (GetUserAction(&worhp_c_, iterOutput)) {
            
        if (!worhp_w_.FirstIteration) {
          if (gather_stats_) {
            Dictionary & iterations = stats_["iterations"];
            static_cast<std::vector<int> &>(iterations["iter_sqp"]).push_back(worhp_w_.MinorIter);
            static_cast<std::vector<double> &>(iterations["inf_pr"]).push_back(worhp_w_.NormMax_CV);
            static_cast<std::vector<double> &>(iterations["inf_du"]).push_back(worhp_w_.ScaledKKT);
            static_cast<std::vector<double> &>(iterations["obj"]).push_back(worhp_o_.F);
            static_cast<std::vector<double> &>(iterations["alpha_pr"]).push_back(worhp_w_.ArmijoAlpha);
          }
        
          if (!callback_.isNull()) {
            double time1 = clock();
            // Copy outputs
            if (!output(NLP_SOLVER_X).isEmpty())
              output(NLP_SOLVER_X).setArray(worhp_o_.X,worhp_o_.n);
            if (!output(NLP_SOLVER_F).isEmpty())
              output(NLP_SOLVER_F).set(worhp_o_.F);
            if (!output(NLP_SOLVER_G).isEmpty())
              output(NLP_SOLVER_G).setArray(worhp_o_.G,worhp_o_.m);
            if (!output(NLP_SOLVER_LAM_X).isEmpty()) 
              output(NLP_SOLVER_LAM_X).setArray(worhp_o_.Lambda,worhp_o_.n);
            if (!output(NLP_SOLVER_LAM_G).isEmpty())
              output(NLP_SOLVER_LAM_G).setArray(worhp_o_.Mu,worhp_o_.m);
              
            Dictionary iteration;
            iteration["iter"] = worhp_w_.MajorIter;
            iteration["iter_sqp"] = worhp_w_.MinorIter;
            iteration["inf_pr"] = worhp_w_.NormMax_CV;
            iteration["inf_du"] = worhp_w_.ScaledKKT;
            iteration["obj"] = worhp_o_.F;
            iteration["alpha_pr"] = worhp_w_.ArmijoAlpha;
            stats_["iteration"] = iteration;

            double time2 = clock();
            t_callback_prepare_ += double(time2-time1)/CLOCKS_PER_SEC;
            time1 = clock();
            int ret = callback_(ref_,user_data_);
            time2 = clock();
            t_callback_fun_ += double(time2-time1)/CLOCKS_PER_SEC;
            
            if(ret) worhp_c_.status = TerminatedByUser;
            
          }
        }

    
        IterationOutput(&worhp_o_, &worhp_w_, &worhp_p_, &worhp_c_);
        DoneUserAction(&worhp_c_, iterOutput);
      }

      if (GetUserAction(&worhp_c_, evalF)) {
        eval_f(worhp_o_.X, worhp_w_.ScaleObj, worhp_o_.F);
        DoneUserAction(&worhp_c_, evalF);
      }

      if (GetUserAction(&worhp_c_, evalG)) {
        eval_g(worhp_o_.X, worhp_o_.G);
        DoneUserAction(&worhp_c_, evalG);
      }

      if (GetUserAction(&worhp_c_, evalDF)) {
        eval_grad_f(worhp_o_.X, worhp_w_.ScaleObj, worhp_w_.DF.val);
        DoneUserAction(&worhp_c_, evalDF);
      }

      if (GetUserAction(&worhp_c_, evalDG)) {
        eval_jac_g(worhp_o_.X,worhp_w_.DG.val);
        DoneUserAction(&worhp_c_, evalDG);
      }

      if (GetUserAction(&worhp_c_, evalHM)) {
        eval_h(worhp_o_.X, worhp_w_.ScaleObj, worhp_o_.Mu, worhp_w_.HM.val);
        DoneUserAction(&worhp_c_, evalHM);
      }
    
      if (GetUserAction(&worhp_c_, fidif)) {
        WorhpFidif(&worhp_o_, &worhp_w_, &worhp_p_, &worhp_c_);
      }
    }

    double time2 = clock();
    t_mainloop_ += double(time2-time1)/CLOCKS_PER_SEC;
  
    // Copy outputs
    output(NLP_SOLVER_X).setArray(worhp_o_.X,worhp_o_.n,DENSE);
    output(NLP_SOLVER_F).set(worhp_o_.F);
    output(NLP_SOLVER_G).setArray(worhp_o_.G,worhp_o_.m,DENSE);
    output(NLP_SOLVER_LAM_X).setArray(worhp_o_.Lambda,worhp_o_.n);
    output(NLP_SOLVER_LAM_G).setArray(worhp_o_.Mu,worhp_o_.m,DENSE);
  
    StatusMsg(&worhp_o_, &worhp_w_, &worhp_p_, &worhp_c_);
 
    if (hasOption("print_time") && bool(getOption("print_time"))) {
      // Write timings
      cout << "time spent in eval_f: " << t_eval_f_ << " s.";
      if (n_eval_f_>0)
        cout << " (" << n_eval_f_ << " calls, " << (t_eval_f_/n_eval_f_)*1000 << " ms. average)";
      cout << endl;
      cout << "time spent in eval_grad_f: " << t_eval_grad_f_ << " s.";
      if (n_eval_grad_f_>0)
        cout << " (" << n_eval_grad_f_ << " calls, " << (t_eval_grad_f_/n_eval_grad_f_)*1000 << " ms. average)";
      cout << endl;
      cout << "time spent in eval_g: " << t_eval_g_ << " s.";
      if (n_eval_g_>0)
        cout << " (" << n_eval_g_ << " calls, " << (t_eval_g_/n_eval_g_)*1000 << " ms. average)";
      cout << endl;
      cout << "time spent in eval_jac_g: " << t_eval_jac_g_ << " s.";
      if (n_eval_jac_g_>0)
        cout << " (" << n_eval_jac_g_ << " calls, " << (t_eval_jac_g_/n_eval_jac_g_)*1000 << " ms. average)";
      cout << endl;
      cout << "time spent in eval_h: " << t_eval_h_ << " s.";
      if (n_eval_h_>1)
        cout << " (" << n_eval_h_ << " calls, " << (t_eval_h_/n_eval_h_)*1000 << " ms. average)";
      cout << endl;
      cout << "time spent in main loop: " << t_mainloop_ << " s." << endl;
      cout << "time spent in callback function: " << t_callback_fun_ << " s." << endl;
      cout << "time spent in callback preparation: " << t_callback_prepare_ << " s." << endl;
    }
  
    stats_["t_eval_f"] = t_eval_f_;
    stats_["t_eval_grad_f"] = t_eval_grad_f_;
    stats_["t_eval_g"] = t_eval_g_;
    stats_["t_eval_jac_g"] = t_eval_jac_g_;
    stats_["t_eval_h"] = t_eval_h_;
    stats_["t_mainloop"] = t_mainloop_;
    stats_["t_callback_fun"] = t_callback_fun_;
    stats_["t_callback_prepare"] = t_callback_prepare_;
    stats_["n_eval_f"] = n_eval_f_;
    stats_["n_eval_grad_f"] = n_eval_grad_f_;
    stats_["n_eval_g"] = n_eval_g_;
    stats_["n_eval_jac_g"] = n_eval_jac_g_;
    stats_["n_eval_h"] = n_eval_h_;
    stats_["iter_count"] = worhp_w_.MajorIter;
    
    stats_["return_code"] = worhp_c_.status;
    stats_["return_status"] = flagmap[worhp_c_.status];
    
  }