gc_pwl_cs.cs


gc_pwl_cs.cs


这个例子用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) */使用System;使用Gurobi;public class gc_pwl_cs {public static void Main() {try {int n = 5;Int m = 5; double[] c = new double[] { 0.5, 0.8, 0.5, 0.1, -1 }; double[,] A = new double[,] { {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} }; double[] xpts = new double[] {-1, 0, 0, 0, 1}; double[] ypts = new double[] {2, 1, 0, 1, 2}; // Env and model GRBEnv env = new GRBEnv(); GRBModel model = new GRBModel(env); model.ModelName = "gc_pwl_cs"; // Add variables, set bounds and obj coefficients GRBVar[] x = model.AddVars(n, GRB.CONTINUOUS); for (int i = 0; i < n; i++) { x[i].LB = -GRB.INFINITY; x[i].Obj = c[i]; } GRBVar[] y = model.AddVars(n, GRB.CONTINUOUS); // Set objective to maximize model.ModelSense = GRB.MAXIMIZE; // Add linear constraints for (int i = 0; i < m; i++) { GRBLinExpr le = 0.0; for (int j = 0; j < n; j++) { le.AddTerm(A[i,j], x[j]); } model.AddConstr(le, GRB.LESS_EQUAL, 0, "cx" + i); } GRBLinExpr le1 = 0.0; for (int j = 0; j < n; j++) { le1.AddTerm(1.0, y[j]); } model.AddConstr(le1, GRB.LESS_EQUAL, 3, "cy"); // Add piecewise constraints for (int j = 0; j < n; j++) { model.AddGenConstrPWL(x[j], y[j], xpts, ypts, "pwl" + j); } // Optimize model model.Optimize(); for (int j = 0; j < n; j++) { Console.WriteLine("x[" + j + "] = " + x[j].X); } Console.WriteLine("Obj: " + model.ObjVal); // Dispose of model and environment model.Dispose(); env.Dispose(); } catch (GRBException e) { Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message); } } }