piecewise_c + + . cpp


/ * 2023年版权,Gurobi优狗万app足彩化,LLC * / / *这个例子考虑分离后,凸问题:减少f (x) - y + g (z)受到x + 2 y + 3 z < = 4 x + y > = 1 x, y, z < = 1 f (u) = exp (- u)和g (u) = 2 ^ 2 - 4 u,所有真正的u。制定和解决简单的LP模型近似与分段线性函数f和g。然后将模型转换成MIP否定近似为f,对应于一个非凸分段线性函数,解决了一遍。* / # include“gurobi_c + +。h”# include < cmath >使用名称空间性病;双f(双u){返回exp (- u);(双u){}双g返回2 *你* u - 4 *;}int主要(int命令行参数个数,char * argv[]){双* ptu =零;双* ptf =零;双* ptg =零;尝试{/ /创建环境GRBEnv env = GRBEnv (); // Create a new model GRBModel model = GRBModel(env); // Create variables double lb = 0.0, ub = 1.0; GRBVar x = model.addVar(lb, ub, 0.0, GRB_CONTINUOUS, "x"); GRBVar y = model.addVar(lb, ub, 0.0, GRB_CONTINUOUS, "y"); GRBVar z = model.addVar(lb, ub, 0.0, GRB_CONTINUOUS, "z"); // Set objective for y model.setObjective(-y); // Add piecewise-linear objective functions for x and z int npts = 101; ptu = new double[npts]; ptf = new double[npts]; ptg = new double[npts]; for (int i = 0; i < npts; i++) { ptu[i] = lb + (ub - lb) * i / (npts - 1); ptf[i] = f(ptu[i]); ptg[i] = g(ptu[i]); } model.setPWLObj(x, npts, ptu, ptf); model.setPWLObj(z, npts, ptu, ptg); // Add constraint: x + 2 y + 3 z <= 4 model.addConstr(x + 2 * y + 3 * z <= 4, "c0"); // Add constraint: x + y >= 1 model.addConstr(x + y >= 1, "c1"); // Optimize model as an LP model.optimize(); cout << "IsMIP: " << model.get(GRB_IntAttr_IsMIP) << endl; cout << x.get(GRB_StringAttr_VarName) << " " << x.get(GRB_DoubleAttr_X) << endl; cout << y.get(GRB_StringAttr_VarName) << " " << y.get(GRB_DoubleAttr_X) << endl; cout << z.get(GRB_StringAttr_VarName) << " " << z.get(GRB_DoubleAttr_X) << endl; cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl; cout << endl; // Negate piecewise-linear objective function for x for (int i = 0; i < npts; i++) { ptf[i] = -ptf[i]; } model.setPWLObj(x, npts, ptu, ptf); // Optimize model as a MIP model.optimize(); cout << "IsMIP: " << model.get(GRB_IntAttr_IsMIP) << endl; cout << x.get(GRB_StringAttr_VarName) << " " << x.get(GRB_DoubleAttr_X) << endl; cout << y.get(GRB_StringAttr_VarName) << " " << y.get(GRB_DoubleAttr_X) << endl; cout << z.get(GRB_StringAttr_VarName) << " " << z.get(GRB_DoubleAttr_X) << endl; cout << "Obj: " << model.get(GRB_DoubleAttr_ObjVal) << endl; } catch(GRBException e) { cout << "Error code = " << e.getErrorCode() << endl; cout << e.getMessage() << endl; } catch(...) { cout << "Exception during optimization" << endl; } delete[] ptu; delete[] ptf; delete[] ptg; return 0; }