gc_pwl_c + + . cpp


gc_pwl_c + + . cpp


这个例子用PWL约束制定并求解了以下简狗万app足彩单模型:最大化sum c[j] * x[j] subject to sum A[i,j] * x[j] <= 0, for i = 0,…m - 1和y [j] < = 3 y [j] = pwl (x [j]), j = 0,…, n-1 x[j] free, y[j] >= 0,对于j = 0,…如果x = 0 = 1+|x|,如果x != 0Sum pwl(x[j]) <= b表示约束的x向量,同时也表示稀疏的x向量。这里b = 3意味着最多两个x[j]可以是非零的,如果是2,则x[j]的和<= 1 2。Pwl (x)从1跳到0,从0跳到1,如果x从- 0到0,然后到0,所以我们需要在x = 0处有三个点。X在两边有无限的边界,由两点(- 1,2)和(0,1)定义的片可以将X扩展到-无限。总之,我们可以使用5个点(- 1,2),(0,1),(0,0),(0,1)和(1,2)来定义y = pwl(x) */ #include "gurobi_c++.h" #include 使用命名空间std;Int main(Int argc, char *argv[]) {Int n = 5;Int m = 5;Double c[] = {0.5, 0.8, 0.5, 0.1, -1}; double A[][5] = { {0, 0, 0, 1, -1}, {0, 0, 1, 1, -1}, {1, 1, 0, 0, -1}, {1, 0, 1, 0, -1}, {1, 0, 0, 1, -1} }; int npts = 5; double xpts[] = {-1, 0, 0, 0, 1}; double ypts[] = {2, 1, 0, 1, 2}; GRBEnv* env = 0; GRBVar* x = 0; GRBVar* y = 0; try { // Env and model env = new GRBEnv(); GRBModel model = GRBModel(*env); model.set(GRB_StringAttr_ModelName, "gc_pwl_c++"); // Add variables, set bounds and obj coefficients x = model.addVars(n); for (int i = 0; i < n; i++) { x[i].set(GRB_DoubleAttr_LB, -GRB_INFINITY); x[i].set(GRB_DoubleAttr_Obj, c[i]); } y = model.addVars(n); // Set objective to maximize model.set(GRB_IntAttr_ModelSense, GRB_MAXIMIZE); // Add linear constraints for (int i = 0; i < m; i++) { GRBLinExpr le = 0; for (int j = 0; j < n; j++) { le += A[i][j] * x[j]; } model.addConstr(le <= 0); } GRBLinExpr le1 = 0; for (int j = 0; j < n; j++) { le1 += y[j]; } model.addConstr(le1 <= 3); // Add piecewise constraints for (int j = 0; j < n; j++) { model.addGenConstrPWL(x[j], y[j], npts, xpts, ypts); } // Optimize model model.optimize(); for (int j = 0; j < n; j++) { cout << "x[" << j << "] = " << x[j].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[] x; delete[] y; delete env; return 0; }