public void BuildRMP(List <Pairing> initialPathSet) { //GetCoverMatrix() INumExpr obj_expr = RMP.NumExpr(); foreach (Pairing path in initialPathSet) { if (path.Route.Count <= 2) { continue; } ColumnPool.Add(path); //create obj function INumVar x = RMP.NumVar(0, 1, NumVarType.Float); DvarSet.Add(x); obj_expr = RMP.Sum(obj_expr, RMP.Prod(path.Cost_with_penalty, x)); CoverMatrix.Add(path.CoverAaray); } RMP.AddObjective(ObjectiveSense.Minimize, obj_expr); //s.t for (int i = 0; i < num_task; i++) { INumExpr ct = RMP.NumExpr(); for (int j = 0; j < DvarSet.Count; j++) { ct = RMP.Sum(ct, RMP.Prod(CoverMatrix[j][i], DvarSet[j])); } constraints[i] = RMP.AddGe(ct, 1); } }
void AddColumnsToRMP(List <Pairing> newPaths) { foreach (var path in newPaths) { if (path.Price > 0 && checkExsitColumn(ColumnPool, path)) { continue; } ColumnPool.Add(path); INumVar new_col = RMP.NumVar(0, 1, NumVarType.Float); //renew obj RMP.GetObjective().Expr = RMP.Sum(RMP.GetObjective().Expr, RMP.Prod(path.Cost_with_penalty, new_col)); //renew ct for (int i = 0; i < num_task; i++) { constraints[i].Expr = RMP.Sum(constraints[i].Expr, RMP.Prod(path.CoverAaray[i], new_col)); } DvarSet.Add(new_col); } }
private void initializeNumericVariables(Cplex plex, VariabilityModel vm) { foreach (NumericOption numOpt in vm.NumericOptions) { // Initialize with the numeric options as numeric variables with a range from min to max INumVar curr = plex.NumVar(numOpt.Min_value, numOpt.Max_value, NumVarType.Float); /* plex.IfThen( * plex.Eq(binOptsToCplexVars[vm.Root], 1), * plex.Or(new IConstraint[] { plex.Ge(curr, numOpt.Min_value), * plex.Le(curr, numOpt.Max_value)} * ) * ); */ numOptsToCplexVars[numOpt] = curr; List <double> values = numOpt.getAllValues(); IConstraint[] valueSet = new IConstraint[values.Count]; // Limit the values numeric options can have to the precomputed valid values for (int i = 0; i < values.Count; i++) { valueSet[i] = plex.Eq(curr, values.ElementAt(i)); } plex.Add(plex.Or(valueSet)); } }
// Step 7 public static void Main(string[] args) { if ( args.Length != 1 || args[0].ToCharArray()[0] != '-' ) { Usage(); return; } try { //Step 3 INumVar[][] var = new INumVar[1][]; IRange[][] rng = new IRange[1][]; // Step 8 // Step 11 // Step 9 // Step 10 cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception '" + e + "' caught"); } }
// Step 7 public static void Main(string[] args) { if (args.Length != 1 || args[0].ToCharArray()[0] != '-') { Usage(); return; } try { //Step 3 INumVar[][] var = new INumVar[1][]; IRange[][] rng = new IRange[1][]; // Step 8 // Step 11 // Step 9 // Step 10 cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception '" + e + "' caught"); } }
internal static void PopulateByRow (IMPModeler model, INumVar[][] var, IRange[][] rng) { // First define the variables, three continuous and one integer double[] xlb = {0.0, 0.0, 0.0, 2.0}; double[] xub = {40.0, System.Double.MaxValue, System.Double.MaxValue, 3.0}; NumVarType[] xt = {NumVarType.Float, NumVarType.Float, NumVarType.Float, NumVarType.Int}; INumVar[] x = model.NumVarArray(4, xlb, xub, xt); var[0] = x; // Objective Function: maximize x0 + 2*x1 + 3*x2 + x3 double[] objvals = {1.0, 2.0, 3.0, 1.0}; model.AddMaximize(model.ScalProd(x, objvals)); // Three constraints rng[0] = new IRange[3]; // - x0 + x1 + x2 + 10*x3 <= 20 rng[0][0] = model.AddLe(model.Sum(model.Prod(-1.0, x[0]), model.Prod( 1.0, x[1]), model.Prod( 1.0, x[2]), model.Prod(10.0, x[3])), 20.0); // x0 - 3*x1 + x2 <= 30 rng[0][1] = model.AddLe(model.Sum(model.Prod( 1.0, x[0]), model.Prod(-3.0, x[1]), model.Prod( 1.0, x[2])), 30.0); // x1 - 3.5*x3 = 0 rng[0][2] = model.AddEq(model.Sum(model.Prod( 1.0, x[1]), model.Prod(-3.5, x[3])), 0.0); }
public static Cplex BuildLPModel(IFTMDP Ida) { Cplex model = new Cplex(); INumVar[][] v = new INumVar[Ida.TimeHorizon][]; //V(t,x) for (int t = 0; t < Ida.TimeHorizon; t++) { v[t] = model.NumVarArray(Ida.SS.Count, -double.MaxValue, double.MaxValue); } IObjective RevenueUB = model.AddMinimize(model.Prod(1, v[0][Ida.SS.IndexOf(Ida.InitialState)])); //time->State->Active-> Expression for (int t = 0; t < Ida.TimeHorizon; t++) { foreach (IMDPState s in Ida.SS) { foreach (IMDPDecision a in Ida.GenDecisionSpace(s)) { INumExpr expr = v[t][Ida.SS.IndexOf(s)]; if (t < Ida.TimeHorizon - 1) { foreach (IMDPState k in Ida.GenStateSpace(s, a)) { expr = model.Sum(expr, model.Prod(-Ida.Prob(t, s, k, a), v[t + 1][Ida.SS.IndexOf(k)])); } } model.AddGe(expr, Ida.Reward(t, s, a)); } } } //model.SetOut(null); return(model); }
public static void Main(string[] args) { try { Cplex cplex = new Cplex(); INumVar[][] var = new INumVar[1][]; IRange[][] rng = new IRange[1][]; PopulateByRow(cplex, var, rng); if ( cplex.Solve() ) { double[] x = cplex.GetValues(var[0]); double[] slack = cplex.GetSlacks(rng[0]); System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine("Solution value = " + cplex.ObjValue); for (int j = 0; j < x.Length; ++j) { System.Console.WriteLine("Variable " + j + ": Value = " + x[j]); } for (int i = 0; i < slack.Length; ++i) { System.Console.WriteLine("Constraint " + i + ": Slack = " + slack[i]); } } cplex.ExportModel("mipex1.lp"); cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception caught '" + e + "' caught"); } }
private void initializeMinMaxObjective(VariabilityModel vm, Cplex plex, bool minimize, List <BinaryOption> wanted, List <BinaryOption> unwanted) { INumVar[] variables = new INumVar[vm.BinaryOptions.Count]; double[] weights = new double[vm.BinaryOptions.Count]; for (int i = 0; i < vm.BinaryOptions.Count; i++) { BinaryOption curr = vm.BinaryOptions.ElementAt(i); variables[i] = binOptsToCplexVars[curr]; if (wanted != null && wanted.Contains(curr)) { weights[i] = -100.0; } else if (unwanted != null && unwanted.Contains(curr)) { weights[i] = 1000.0; } else { weights[i] = minimize ? 100.0 : -100.0; } } ILinearNumExpr weightedVariables = plex.ScalProd(variables, weights); IObjective objective = plex.Minimize(weightedVariables); plex.Add(objective); }
internal static void PopulateByColumn(IMPModeler model, INumVar[][] var, IRange[][] rng) { IObjective obj = model.AddMaximize(); rng[0] = new IRange[2]; rng[0][0] = model.AddRange(-System.Double.MaxValue, 20.0, "c1"); rng[0][1] = model.AddRange(-System.Double.MaxValue, 30.0, "c2"); IRange r0 = rng[0][0]; IRange r1 = rng[0][1]; var[0] = new INumVar[3]; var[0][0] = model.NumVar(model.Column(obj, 1.0).And( model.Column(r0, -1.0).And( model.Column(r1, 1.0))), 0.0, 40.0, "x1"); var[0][1] = model.NumVar(model.Column(obj, 2.0).And( model.Column(r0, 1.0).And( model.Column(r1, -3.0))), 0.0, System.Double.MaxValue, "x2"); var[0][2] = model.NumVar(model.Column(obj, 3.0).And( model.Column(r0, 1.0).And( model.Column(r1, 1.0))), 0.0, System.Double.MaxValue, "x3"); }
public static void Main(string[] args) { if ( args.Length != 1 || args[0].ToCharArray()[0] != '-' ) { Usage(); return; } try { // Create the modeler/solver object Cplex cplex = new Cplex(); INumVar[][] var = new INumVar[1][]; IRange[][] rng = new IRange[1][]; // Evaluate command line option and call appropriate populate method. // The created ranges and variables are returned as element 0 of arrays // var and rng. switch ( args[0].ToCharArray()[1] ) { case 'r': PopulateByRow(cplex, var, rng); break; case 'c': PopulateByColumn(cplex, var, rng); break; case 'n': PopulateByNonzero(cplex, var, rng); break; default: Usage(); return; } // write model to file cplex.ExportModel("lpex1.lp"); // solve the model and display the solution if one was found if ( cplex.Solve() ) { double[] x = cplex.GetValues(var[0]); double[] dj = cplex.GetReducedCosts(var[0]); double[] pi = cplex.GetDuals(rng[0]); double[] slack = cplex.GetSlacks(rng[0]); cplex.Output().WriteLine("Solution status = " + cplex.GetStatus()); cplex.Output().WriteLine("Solution value = " + cplex.ObjValue); int nvars = x.Length; for (int j = 0; j < nvars; ++j) { cplex.Output().WriteLine("Variable " + j + ": Value = " + x[j] + " Reduced cost = " + dj[j]); } int ncons = slack.Length; for (int i = 0; i < ncons; ++i) { cplex.Output().WriteLine("Constraint " + i + ": Slack = " + slack[i] + " Pi = " + pi[i]); } } cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception '" + e + "' caught"); } }
private void AddCplexLEqual(Cplex model, dc_FGPair fg, INumVar slack) { INumExpr fi = fg.f.AddExpression(model); INumExpr gi = fg.g.Minorize(model); model.AddLe(fi, model.Sum(gi, slack)); }
protected void AddCol(int t, IALPDecision a)//Add a column into RMP model { if (var[t].ContainsKey(a)) { return; } //目标函数 Column col = RMPModel.Column(cost, Data.Rt(t, a)); //第一类约束 foreach (IALPResource re in Data.RS) { for (int k = t + 1; k < Data.TimeHorizon; k++) { col = col.And(RMPModel.Column(constraint1[k][Data.RS.IndexOf(re)], Data.Qti(t, re, a))); } if (a.UseResource(re)) { col = col.And(RMPModel.Column(constraint1[t][Data.RS.IndexOf(re)], 1)); } } //第二类约束 col = col.And(RMPModel.Column(constraint2[t], 1)); INumVar v = RMPModel.NumVar(col, 0, 1, NumVarType.Float); var[t].Add(a, v); }
static ILPMatrix PopulateByRow(IMPModeler model) { ILPMatrix lp = model.AddLPMatrix(); double[] lb = { 0.0, 0.0, 0.0 }; double[] ub = { 40.0, Double.MaxValue, Double.MaxValue }; INumVar[] x = model.NumVarArray(model.ColumnArray(lp, 3), lb, ub); INumVar y = model.IntVar(model.Column(lp), 0, 3); // - x0 + x1 + x2 + 10*y <= 20 // x0 - 3*x1 + x2 <= 30 double[] lhs = { -Double.MaxValue, -Double.MaxValue }; double[] rhs = { 20.0, 30.0 }; double[][] val = { new double[] { -1.0, 1.0, 1.0, 10.0 }, new double[] { 1.0, -3.0, 1.0 } }; int[][] ind = { new int[] { 0, 1, 2, 3 }, new int[] { 0, 1, 2 } }; lp.AddRows(lhs, rhs, ind, val); // x1 + 3.5*y = 0 lp.AddRow(model.Eq(model.Diff(x[1], model.Prod(3.5, y)), 0.0)); // Q = 0.5 ( 33*x0*x0 + 22*x1*x1 + 11*x2*x2 - 12*x0*x1 - 23*x1*x2 ) INumExpr x00 = model.Prod(33.0, model.Square(x[0])); INumExpr x11 = model.Prod(22.0, model.Square(x[1])); INumExpr x22 = model.Prod(11.0, model.Square(x[2])); INumExpr x01 = model.Prod(-12.0, model.Prod(x[0], x[1])); INumExpr x12 = model.Prod(-23.0, model.Prod(x[1], x[2])); INumExpr Q = model.Prod(0.5, model.Sum(x00, x11, x22, x01, x12)); // maximize x0 + 2*x1 + 3*x2 + Q double[] objvals = { 1.0, 2.0, 3.0 }; model.Add(model.Maximize(model.Diff(model.ScalProd(x, objvals), Q))); return(lp); }
//void RecordFeasibleSolution(TreeNode node, ref List<int> best_feasible_solution) //{ // best_feasible_solution.Clear(); //找到更好的可行解了,不需要之前的了 // ///方式2 // //已分支的变量固定为 1,直接添加 // foreach (var v in node.fixing_vars) // { // best_feasible_solution.Add(v); // } // //TODO:回溯剪枝掉的var也得判断其值 // //未分支的变量,判断其是否为 1(为不失一般性,写的函数功能是判断是否为整数) // foreach (var var_value in node.not_fixed_var_value_pairs) // { // if (Convert.ToInt32(var_value.Value) > 0 && ISInteger(var_value.Value)) // { // best_feasible_solution.Add(var_value.Key); // } // } //} #endregion// #region 列生成 /// <summary>在树节点"tree_node"章进行列生成 /// 求得当前树节点的最优目标值 /// </summary> /// <param name="tree_node"></param> public void CG(ref TreeNode tree_node) { //固定分支变量的值(==1)等于是另外加上变量的取值范围约束 FixVars(tree_node.fixing_vars); double cur_reducedCost = 0; //迭代生成列 for (;;) { this.OBJVALUE = SolveRMP(); //求解子问题,判断 检验数 < -1e-8 ? if (IsLPOpt(cur_reducedCost)) { break; } Console.WriteLine("检验数 = {0}", R_C_SPP.Reduced_Cost); cur_reducedCost = R_C_SPP.Reduced_Cost; double col_coef = 0; int[] aj; //ColumnPool = DeleteColumn(ColumnPool); foreach (Pairing column in R_C_SPP.New_Columns) { ColumnPool.Add(column); col_coef = column.ObjCoef; aj = column.CoverMatrix; INumVar column_var = masterModel.NumVar(0, 1, NumVarType.Float); //每加一列都要对模型进行修改,因为决策变量多了 // function Obj.Expr = masterModel.Sum(Obj.Expr, masterModel.Prod(col_coef, column_var)); // constrains for (int i = 0; i < realistic_trip_num; i++) { Constraint[i].Expr = masterModel.Sum(Constraint[i].Expr, masterModel.Prod(aj[i], column_var)); } //TODO 20191006 DvarSet.Add(column_var); A_Matrix.Add(aj); ObjCoefSet.Add(col_coef); } } //传递信息给tree_node tree_node.obj_value = this.OBJVALUE; tree_node.not_fixed_var_value_pairs.Clear(); for (int i = 0; i < DvarSet.Count; i++) { //将未分支的变量添加到待分支变量集合中 //!被回溯“扔掉”的变量不能再添加到fixed_vars中,须加上 && tree_node.fixed_vars.Contains(i) == false if (tree_node.fixing_vars.Contains(i) == false && tree_node.fixed_vars.Contains(i) == false) { tree_node.not_fixed_var_value_pairs.Add(i, masterModel.GetValue(DvarSet[i])); } } }
public static void Main( string[] args ) { try { string filename = "../../../../examples/data/facility.dat"; if (args.Length > 0) filename = args[0]; ReadData(filename); Cplex cplex = new Cplex(); INumVar[] open = cplex.BoolVarArray(_nbLocations); INumVar[][] supply = new INumVar[_nbClients][]; for(int i = 0; i < _nbClients; i++) supply[i] = cplex.BoolVarArray(_nbLocations); for(int i = 0; i < _nbClients; i++) cplex.AddEq(cplex.Sum(supply[i]), 1); for(int j = 0; j < _nbLocations; j++) { ILinearNumExpr v = cplex.LinearNumExpr(); for(int i = 0; i < _nbClients; i++) v.AddTerm(1.0, supply[i][j]); cplex.AddLe(v, cplex.Prod(_capacity[j], open[j])); } ILinearNumExpr obj = cplex.ScalProd(_fixedCost, open); for(int i = 0; i < _nbClients; i++) obj.Add(cplex.ScalProd(_cost[i], supply[i])); cplex.AddMinimize(obj); if (cplex.Solve()) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); double tolerance = cplex.GetParam(Cplex.Param.MIP.Tolerances.Integrality); System.Console.WriteLine("Optimal value: " + cplex.ObjValue); for(int j = 0; j < _nbLocations; j++) { if (cplex.GetValue(open[j]) >= 1 - tolerance) { System.Console.Write("Facility " + j +" is open, it serves clients "); for(int i = 0; i < _nbClients; i++) if (cplex.GetValue(supply[i][j]) >= 1 - tolerance) System.Console.Write(" " + i); System.Console.WriteLine(); } } } cplex.End(); } catch(ILOG.Concert.Exception exc) { System.Console.WriteLine("Concert exception '" + exc + "' caught"); } catch (System.IO.IOException exc) { System.Console.WriteLine("Error reading file " + args[0] + ": " + exc); } catch (InputDataReader.InputDataReaderException exc) { System.Console.WriteLine(exc); } }
public static void Main(string[] args) { try { Cplex cplex = new Cplex(); INumVar[][] var = new INumVar[1][]; IRange[][] rng = new IRange[1][]; PopulateByRow(cplex, var, rng); Cplex.BasisStatus[] cstat = { Cplex.BasisStatus.AtUpper, Cplex.BasisStatus.Basic, Cplex.BasisStatus.Basic }; Cplex.BasisStatus[] rstat = { Cplex.BasisStatus.AtLower, Cplex.BasisStatus.AtLower }; cplex.SetBasisStatuses(var[0], cstat, rng[0], rstat); if (cplex.Solve()) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine("Solution value = " + cplex.ObjValue); System.Console.WriteLine("Iteration count = " + cplex.Niterations); double[] x = cplex.GetValues(var[0]); double[] dj = cplex.GetReducedCosts(var[0]); double[] pi = cplex.GetDuals(rng[0]); double[] slack = cplex.GetSlacks(rng[0]); int nvars = x.Length; for (int j = 0; j < nvars; ++j) { System.Console.WriteLine("Variable " + j + ": Value = " + x[j] + " Reduced cost = " + dj[j]); } int ncons = slack.Length; for (int i = 0; i < ncons; ++i) { System.Console.WriteLine("Constraint " + i + ": Slack = " + slack[i] + " Pi = " + pi[i]); } } cplex.End(); } catch (ILOG.Concert.Exception exc) { System.Console.WriteLine("Concert exception '" + exc + "' caught"); } }
private INumVar[] populateArray(INumVar current, List <ConfigurationOption> others) { INumVar[] alternativeGroup = new INumVar[1 + others.Count]; alternativeGroup[0] = current; for (int i = 1; i <= others.Count; i++) { alternativeGroup[i] = binOptsToCplexVars[(BinaryOption)others.ElementAt(i - 1)]; } return(alternativeGroup); }
static void Main(string[] args) { Console.WriteLine("hi justin"); Cplex cpl = new Cplex(); INumVar x = cpl.NumVar(0, 1); Console.WriteLine("upper bound: " + Convert.ToString(x.UB)); Console.ReadKey(); }
public static void Main(string[] args) { try { Cplex cplex = new Cplex(); INumVar[] inside = cplex.NumVarArray(_nbProds, 10.0, Double.MaxValue); INumVar[] outside = cplex.NumVarArray(_nbProds, 0.0, Double.MaxValue); INumVar costVar = cplex.NumVar(0.0, Double.MaxValue); cplex.AddEq(costVar, cplex.Sum(cplex.ScalProd(inside, _insideCost), cplex.ScalProd(outside, _outsideCost))); IObjective obj = cplex.AddMinimize(costVar); // Must meet demand for each product for (int p = 0; p < _nbProds; p++) { cplex.AddEq(cplex.Sum(inside[p], outside[p]), _demand[p]); } // Must respect capacity constraint for each resource for (int r = 0; r < _nbResources; r++) { cplex.AddLe(cplex.ScalProd(_consumption[r], inside), _capacity[r]); } cplex.Solve(); if (cplex.GetStatus() != Cplex.Status.Optimal) { System.Console.WriteLine("No optimal solution found"); return; } // New constraint: cost must be no more than 10% over minimum double cost = cplex.ObjValue; costVar.UB = 1.1 * cost; // New objective: minimize outside production obj.Expr = cplex.Sum(outside); cplex.Solve(); System.Console.WriteLine("Solution status = " + cplex.GetStatus()); DisplayResults(cplex, costVar, inside, outside); System.Console.WriteLine("----------------------------------------"); cplex.End(); } catch (ILOG.Concert.Exception exc) { System.Console.WriteLine("Concert exception '" + exc + "' caught"); } }
internal static void DisplayResults(Cplex cplex, INumVar[] inside, INumVar[] outside) { System.Console.WriteLine("cost: " + cplex.ObjValue); for(int p = 0; p < _nbProds; p++) { System.Console.WriteLine("P" + p); System.Console.WriteLine("inside: " + cplex.GetValue(inside[p])); System.Console.WriteLine("outside: " + cplex.GetValue(outside[p])); } }
public static void Main(string[] args) { try { // create CPLEX optimizer/modeler and turn off presolve to make // the output more interesting Cplex cplex = new Cplex(); cplex.SetParam(Cplex.Param.Preprocessing.Presolve, false); // build model INumVar[][] var = new INumVar[1][]; IRange[][] rng = new IRange[1][]; PopulateByRow(cplex, var, rng); // setup branch priorities INumVar[] ordvar = { var[0][1], var[0][3] }; int[] ordpri = { 8, 7 }; cplex.SetPriorities(ordvar, ordpri); // setup branch directions cplex.SetDirection(ordvar[0], Cplex.BranchDirection.Up); cplex.SetDirection(ordvar[1], Cplex.BranchDirection.Down); // write priority order to file cplex.WriteOrder("mipex3.ord"); // optimize and output solution information if (cplex.Solve()) { double[] x = cplex.GetValues(var[0]); double[] slack = cplex.GetSlacks(rng[0]); System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine("Solution value = " + cplex.ObjValue); for (int j = 0; j < x.Length; ++j) { System.Console.WriteLine("Variable " + j + ": Value = " + x[j]); } for (int i = 0; i < slack.Length; ++i) { System.Console.WriteLine("Constraint " + i + ": Slack = " + slack[i]); } } cplex.ExportModel("mipex3.lp"); cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception caught: " + e); } }
internal static void Report2(Cplex patSolver, INumVar[] Use) { System.Console.WriteLine(); System.Console.WriteLine("Reduced cost is " + patSolver.ObjValue); System.Console.WriteLine(); if (patSolver.ObjValue <= -RC_EPS) { for (int i = 0; i < Use.Length; i++) System.Console.WriteLine(" Use" + i + " = " + patSolver.GetValue(Use[i])); System.Console.WriteLine(); } }
private void countConstraint(Cplex plex, List <BinaryOption> options, double count) { INumVar[] blacklistedVars = new INumVar[options.Count]; for (int i = 0; i < options.Count; i++) { blacklistedVars[i] = binOptsToCplexVars[options.ElementAt(i)]; } plex.Add(plex.Eq( plex.Constant(count), plex.Sum(blacklistedVars) )); }
public static void Main(string[] args) { try { Cplex cplex = new Cplex(); INumVar[][] var = new INumVar[1][]; IRange[][] rng = new IRange[1][]; PopulateByRow(cplex, var, rng); Cplex.BasisStatus[] cstat = { Cplex.BasisStatus.AtUpper, Cplex.BasisStatus.Basic, Cplex.BasisStatus.Basic }; Cplex.BasisStatus[] rstat = { Cplex.BasisStatus.AtLower, Cplex.BasisStatus.AtLower }; cplex.SetBasisStatuses(var[0], cstat, rng[0], rstat); if ( cplex.Solve() ) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine("Solution value = " + cplex.ObjValue); System.Console.WriteLine("Iteration count = " + cplex.Niterations); double[] x = cplex.GetValues(var[0]); double[] dj = cplex.GetReducedCosts(var[0]); double[] pi = cplex.GetDuals(rng[0]); double[] slack = cplex.GetSlacks(rng[0]); int nvars = x.Length; for (int j = 0; j < nvars; ++j) { System.Console.WriteLine("Variable " + j + ": Value = " + x[j] + " Reduced cost = " + dj[j]); } int ncons = slack.Length; for (int i = 0; i < ncons; ++i) { System.Console.WriteLine("Constraint " + i + ": Slack = " + slack[i] + " Pi = " + pi[i]); } } cplex.End(); } catch (ILOG.Concert.Exception exc) { System.Console.WriteLine("Concert exception '" + exc + "' caught"); } }
/// <summary>建立最初的RMP /// 依据初始解 /// </summary> /// <param name="IS"></param> public void Build_RMP(InitialSolution IS) { initialPath_num = IS.PathSet.Count; trip_num = TripList.Count; realistic_trip_num = NetWork.num_Physical_trip; DvarSet = new List <INumVar>(); CoefSet = new List <double>(); A_Matrix = new List <int[]>(); PathSet = new List <Pairing>(); //virtualVarSet = new List<INumVar>(); //for (int virtual_x = 0; virtual_x < realistic_trip_num; virtual_x++) { // virtualVarSet.Add(masterModel.NumVar(0, 1, NumVarType.Float)); //} CoefSet = IS.Coefs; A_Matrix = IS.A_Matrix; PathSet = IS.PathSet; foreach (var p in PathSet) { ColumnPool.Add(p); } int i, j; Obj = masterModel.AddMinimize(); Constraint = new IRange[realistic_trip_num]; /**按行建模**/ //vars and obj function for (j = 0; j < initialPath_num; j++) { INumVar var = masterModel.NumVar(0, 1, NumVarType.Float); DvarSet.Add(var); Obj.Expr = masterModel.Sum(Obj.Expr, masterModel.Prod(CoefSet[j], DvarSet[j])); } //constraints for (i = 0; i < realistic_trip_num; i++) { INumExpr expr = masterModel.NumExpr(); for (j = 0; j < initialPath_num; j++) { expr = masterModel.Sum(expr, masterModel.Prod(A_Matrix[j][i], DvarSet[j]));//在从初始解传值给A_Matrix,已经针对网络复制作了处理 } Constraint[i] = masterModel.AddGe(expr, 1); } }
// This function creates the following model: // Minimize // obj: x1 + x2 + x3 + x4 + x5 + x6 // Subject To // c1: x1 + x2 + x5 = 8 // c2: x3 + x5 + x6 = 10 // q1: [ -x1^2 + x2^2 + x3^2 ] <= 0 // q2: [ -x4^2 + x5^2 ] <= 0 // Bounds // x2 Free // x3 Free // x5 Free // End // which is a second order cone program in standard form. private static IObjective Createmodel(Cplex cplex, ICollection <INumVar> vars, ICollection <IRange> rngs, IDictionary <INumVar, IRange> cone) { System.Double pinf = System.Double.PositiveInfinity; System.Double ninf = System.Double.NegativeInfinity; INumVar x1 = cplex.NumVar(0, pinf, "x1"); INumVar x2 = cplex.NumVar(ninf, pinf, "x2"); INumVar x3 = cplex.NumVar(ninf, pinf, "x3"); INumVar x4 = cplex.NumVar(0, pinf, "x4"); INumVar x5 = cplex.NumVar(ninf, pinf, "x5"); INumVar x6 = cplex.NumVar(0, pinf, "x6"); IObjective obj = cplex.AddMinimize(cplex.Sum(cplex.Sum(cplex.Sum(x1, x2), cplex.Sum(x3, x4)), cplex.Sum(x5, x6)), "obj"); IRange c1 = cplex.AddEq(cplex.Sum(x1, cplex.Sum(x2, x5)), 8, "c1"); IRange c2 = cplex.AddEq(cplex.Sum(x3, cplex.Sum(x5, x6)), 10, "c2"); IRange q1 = cplex.AddLe(cplex.Sum(cplex.Prod(-1, cplex.Prod(x1, x1)), cplex.Sum(cplex.Prod(x2, x2), cplex.Prod(x3, x3))), 0, "q1"); cone[x1] = q1; cone[x2] = NOT_CONE_HEAD; cone[x3] = NOT_CONE_HEAD; IRange q2 = cplex.AddLe(cplex.Sum(cplex.Prod(-1, cplex.Prod(x4, x4)), cplex.Prod(x5, x5)), 0, "q2"); cone[x4] = q2; cone[x5] = NOT_CONE_HEAD; cone[x6] = NOT_IN_CONE; vars.Add(x1); vars.Add(x2); vars.Add(x3); vars.Add(x4); vars.Add(x5); vars.Add(x6); rngs.Add(c1); rngs.Add(c2); rngs.Add(q1); rngs.Add(q2); return(obj); }
public static void Main(string[] args) { try { // setup files to transfer model to server string mfile = "Model.dat"; string sfile = "Solution.dat"; // build model INumVar[][] var = new INumVar[1][]; IRange[][] rng = new IRange[1][]; CplexModeler model = new CplexModeler(); PopulateByRow(model, var, rng); FileStream mstream = new FileStream(mfile, FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(mstream, new ModelData(model, var[0])); mstream.Close(); // start server Server server = new Server(mfile, sfile); SolutionData sol = null; FileStream sstream = new FileStream(sfile, FileMode.Open); sol = (SolutionData)formatter.Deserialize(sstream); sstream.Close(); System.Console.WriteLine("Solution status = " + sol.status); if (sol.status.Equals(Cplex.CplexStatus.Optimal)) { System.Console.WriteLine("Solution value = " + sol.obj); int ncols = var[0].Length; for (int j = 0; j < ncols; ++j) { System.Console.WriteLine("Variable " + j + ": Value = " + sol.vals[j]); } } } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception '" + e + "' caught"); } catch (System.Exception t) { System.Console.WriteLine("terminating due to exception " + t); } }
public static void Main(string[] args) { try { // create CPLEX optimizer/modeler and turn off presolve to make // the output more interesting Cplex cplex = new Cplex(); cplex.SetParam(Cplex.Param.Preprocessing.Presolve, false); // build model INumVar[][] var = new INumVar[1][]; IRange[][] rng = new IRange[1][]; PopulateByRow (cplex, var, rng); // setup branch priorities INumVar[] ordvar = {var[0][1], var[0][3]}; int[] ordpri = {8, 7}; cplex.SetPriorities (ordvar, ordpri); // setup branch directions cplex.SetDirection(ordvar[0], Cplex.BranchDirection.Up); cplex.SetDirection(ordvar[1], Cplex.BranchDirection.Down); // write priority order to file cplex.WriteOrder("mipex3.ord"); // optimize and output solution information if ( cplex.Solve() ) { double[] x = cplex.GetValues(var[0]); double[] slack = cplex.GetSlacks(rng[0]); System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine("Solution value = " + cplex.ObjValue); for (int j = 0; j < x.Length; ++j) { System.Console.WriteLine("Variable " + j + ": Value = " + x[j]); } for (int i = 0; i < slack.Length; ++i) { System.Console.WriteLine("Constraint " + i + ": Slack = " + slack[i]); } } cplex.ExportModel("mipex3.lp"); cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception caught: " + e); } }
public static Cplex Build_CD3_Model(IALPFTMDP aff) { Cplex model = new Cplex(); IObjective cost = model.AddMaximize(); INumVar[][] var = new INumVar[aff.TimeHorizon][]; #region //////////////生成约束////////////// IRange[][] constraint1 = new IRange[aff.TimeHorizon][]; IRange[] constraint2 = new IRange[aff.TimeHorizon]; for (int i = 0; i < aff.TimeHorizon; i++) { var[i] = new INumVar[aff.DS.Count]; constraint1[i] = new IRange[aff.RS.Count]; foreach (IALPResource re in aff.RS) { constraint1[i][aff.RS.IndexOf(re)] = model.AddRange(double.MinValue, (aff.InitialState as IALPState)[re]); } constraint2[i] = model.AddRange(1, 1); } #endregion #region //////////////生成变量////////////// for (int t = 0; t < aff.TimeHorizon; t++) { foreach (IALPDecision a in aff.DS) { //目标函数 Column col = model.Column(cost, aff.Rt(t, a)); //第一类约束 foreach (IALPResource re in aff.RS) { for (int k = t + 1; k < aff.TimeHorizon; k++) { col = col.And(model.Column(constraint1[k][aff.RS.IndexOf(re)], aff.Qti(t, re, a))); } if (a.UseResource(re)) { col = col.And(model.Column(constraint1[t][aff.RS.IndexOf(re)], 1)); } } //第二类约束 col = col.And(model.Column(constraint2[t], 1)); var[t][aff.DS.IndexOf(a)] = model.NumVar(col, 0, double.MaxValue, NumVarType.Float); } } #endregion return(model); }
public static void Main(string[] args) { try { string filename = "../../../../examples/data/rates.dat"; if (args.Length > 0) { filename = args[0]; } ReadData(filename); Cplex cplex = new Cplex(); INumVar[] production = new INumVar[_generators]; for (int j = 0; j < _generators; ++j) { production[j] = cplex.SemiContVar(_minArray[j], _maxArray[j], NumVarType.Float); } cplex.AddMinimize(cplex.ScalProd(_cost, production)); cplex.AddGe(cplex.Sum(production), _demand); cplex.ExportModel("rates.lp"); if (cplex.Solve()) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); for (int j = 0; j < _generators; ++j) { System.Console.WriteLine(" generator " + j + ": " + cplex.GetValue(production[j])); } System.Console.WriteLine("Total cost = " + cplex.ObjValue); } else { System.Console.WriteLine("No solution"); } cplex.End(); } catch (ILOG.Concert.Exception exc) { System.Console.WriteLine("Concert exception '" + exc + "' caught"); } catch (System.IO.IOException exc) { System.Console.WriteLine("Error reading file " + args[0] + ": " + exc); } catch (InputDataReader.InputDataReaderException exc) { System.Console.WriteLine(exc); } }
static void DisplayResults(Cplex cplex, INumVar costVar, INumVar[] inside, INumVar[] outside) { System.Console.WriteLine("cost: " + cplex.GetValue(costVar)); for (int p = 0; p < _nbProds; p++) { System.Console.WriteLine("P" + p); System.Console.WriteLine("inside: " + cplex.GetValue(inside[p])); System.Console.WriteLine("outside: " + cplex.GetValue(outside[p])); } }
public static void Main(string[] args) { try { Cplex cplex = new Cplex(); INumVar[] inside = new INumVar[_nbProds]; INumVar[] outside = new INumVar[_nbProds]; IObjective obj = cplex.AddMinimize(); // Must meet demand for each product for (int p = 0; p < _nbProds; p++) { IRange demRange = cplex.AddRange(_demand[p], _demand[p]); inside[p] = cplex.NumVar(cplex.Column(obj, _insideCost[p]).And( cplex.Column(demRange, 1.0)), 0.0, System.Double.MaxValue); outside[p] = cplex.NumVar(cplex.Column(obj, _outsideCost[p]).And( cplex.Column(demRange, 1.0)), 0.0, System.Double.MaxValue); } // Must respect capacity constraint for each resource for (int r = 0; r < _nbResources; r++) { cplex.AddLe(cplex.ScalProd(_consumption[r], inside), _capacity[r]); } cplex.Solve(); if (!cplex.GetStatus().Equals(Cplex.Status.Optimal)) { System.Console.WriteLine("No optimal solution found"); return; } System.Console.WriteLine("Solution status = " + cplex.GetStatus()); DisplayResults(cplex, inside, outside); System.Console.WriteLine("----------------------------------------"); cplex.End(); } catch (ILOG.Concert.Exception exc) { System.Console.WriteLine("Concert exception '" + exc + "' caught"); } }
private void initializeImpliedOptions(Cplex cplex, INumVar currentOption, BinaryOption currentBinOpt) { List <List <ConfigurationOption> > impliedOptions = currentBinOpt.Implied_Options; foreach (List <ConfigurationOption> impliedGroup in impliedOptions) { INumVar[] implVars = populateArray(currentOption, impliedGroup); // For implication groups the sum of the options has to be the number of implied options // if the current options is selected cplex.Add(cplex.IfThen( cplex.Eq(one, currentOption), cplex.Eq(cplex.Sum(implVars), cplex.Constant(implVars.Count())) )); } }
public static void Main(string[] args) { try { // setup files to transfer model to server string mfile = "Model.dat"; string sfile = "Solution.dat"; // build model INumVar[][] var = new INumVar[1][]; IRange[][] rng = new IRange[1][]; CplexModeler model = new CplexModeler(); PopulateByRow(model, var, rng); FileStream mstream = new FileStream(mfile, FileMode.Create); BinaryFormatter formatter = new BinaryFormatter (); formatter.Serialize(mstream, new ModelData(model, var[0])); mstream.Close(); // start server Server server = new Server(mfile, sfile); SolutionData sol = null; FileStream sstream = new FileStream(sfile, FileMode.Open); sol = (SolutionData) formatter.Deserialize(sstream); sstream.Close(); System.Console.WriteLine("Solution status = " + sol.status); if ( sol.status.Equals(Cplex.CplexStatus.Optimal) ) { System.Console.WriteLine("Solution value = " + sol.obj); int ncols = var[0].Length; for (int j = 0; j < ncols; ++j) System.Console.WriteLine("Variable " + j + ": Value = " + sol.vals[j]); } } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception '" + e + "' caught"); } catch (System.Exception t) { System.Console.WriteLine("terminating due to exception " + t); } }
internal static void BuildModelByRow(IModeler model, Data data, INumVar[] Buy, NumVarType type) { int nFoods = data.nFoods; int nNutrs = data.nNutrs; for (int j = 0; j < nFoods; j++) { Buy[j] = model.NumVar(data.foodMin[j], data.foodMax[j], type); } model.AddMinimize(model.ScalProd(data.foodCost, Buy)); for (int i = 0; i < nNutrs; i++) { model.AddRange(data.nutrMin[i], model.ScalProd(data.nutrPerFood[i], Buy), data.nutrMax[i]); } }
internal static void PopulateByRow(IMPModeler model, INumVar[][] var, IRange[][] rng) { double[] lb = {0.0, 0.0, 0.0}; double[] ub = {40.0, System.Double.MaxValue, System.Double.MaxValue}; var[0] = model.NumVarArray(3, lb, ub); double[] objvals = {1.0, 2.0, 3.0}; model.AddMaximize(model.ScalProd(var[0], objvals)); rng[0] = new IRange[2]; rng[0][0] = model.AddLe(model.Sum(model.Prod(-1.0, var[0][0]), model.Prod( 1.0, var[0][1]), model.Prod( 1.0, var[0][2])), 20.0); rng[0][1] = model.AddLe(model.Sum(model.Prod( 1.0, var[0][0]), model.Prod(-3.0, var[0][1]), model.Prod( 1.0, var[0][2])), 30.0); }
public static void Main( string[] args ) { try { Cplex cplex = new Cplex(); INumVar[] inside = new INumVar[_nbProds]; INumVar[] outside = new INumVar[_nbProds]; IObjective obj = cplex.AddMinimize(); // Must meet demand for each product for(int p = 0; p < _nbProds; p++) { IRange demRange = cplex.AddRange(_demand[p], _demand[p]); inside[p] = cplex.NumVar(cplex.Column(obj, _insideCost[p]).And( cplex.Column(demRange, 1.0)), 0.0, System.Double.MaxValue); outside[p] = cplex.NumVar(cplex.Column(obj, _outsideCost[p]).And( cplex.Column(demRange, 1.0)), 0.0, System.Double.MaxValue); } // Must respect capacity constraint for each resource for(int r = 0; r < _nbResources; r++) cplex.AddLe(cplex.ScalProd(_consumption[r], inside), _capacity[r]); cplex.Solve(); if ( !cplex.GetStatus().Equals(Cplex.Status.Optimal) ) { System.Console.WriteLine("No optimal solution found"); return; } System.Console.WriteLine("Solution status = " + cplex.GetStatus()); DisplayResults(cplex, inside, outside); System.Console.WriteLine("----------------------------------------"); cplex.End(); } catch (ILOG.Concert.Exception exc) { System.Console.WriteLine("Concert exception '" + exc + "' caught"); } }
public static void Main( string[] args ) { try { string filename = "../../../../examples/data/rates.dat"; if (args.Length > 0) filename = args[0]; ReadData(filename); Cplex cplex = new Cplex(); INumVar[] production = new INumVar[_generators]; for (int j = 0; j < _generators; ++j) { production[j] = cplex.SemiContVar(_minArray[j], _maxArray[j], NumVarType.Float); } cplex.AddMinimize(cplex.ScalProd(_cost, production)); cplex.AddGe(cplex.Sum(production), _demand); cplex.ExportModel("rates.lp"); if ( cplex.Solve() ) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); for (int j = 0; j < _generators; ++j) { System.Console.WriteLine(" generator " + j + ": " + cplex.GetValue(production[j])); } System.Console.WriteLine("Total cost = " + cplex.ObjValue); } else System.Console.WriteLine("No solution"); cplex.End(); } catch (ILOG.Concert.Exception exc) { System.Console.WriteLine("Concert exception '" + exc + "' caught"); } catch (System.IO.IOException exc) { System.Console.WriteLine("Error reading file " + args[0] + ": " + exc); } catch (InputDataReader.InputDataReaderException exc) { System.Console.WriteLine(exc); } }
private bool AddCol(int t, IALPState s, IMDPDecision a)//Add a column into RMP model { Column col = RMPModel.Column(cost, Data.Rt(t, a)); foreach (IALPResource re in Data.RS) { col = col.And(RMPModel.Column(constraint1[t][Data.RS.IndexOf(re)], (s as IALPState)[re])); if (t < Data.TimeHorizon - 1) { col = col.And(RMPModel.Column(constraint1[t + 1][Data.RS.IndexOf(re)], (Data.Qti(t, re, a)) - (s as IALPState)[re])); } } col = col.And(RMPModel.Column(constraint2[t], 1)); INumVar var = RMPModel.NumVar(col, 0, double.MaxValue, NumVarType.Float); sas.Add(new StateActive() { S = s, D = a, Var = var }); return(true); }
internal static void PopulateByRow(IMPModeler model, INumVar[][] var, IRange[][] rng) { // Define the variables one-by-one INumVar[] x = new INumVar[4]; x[0] = model.NumVar(0.0, 40.0, "x0"); x[1] = model.IntVar(0, System.Int32.MaxValue, "x1"); x[2] = model.IntVar(0, System.Int32.MaxValue, "x2"); x[3] = model.IntVar(2, 3, "x3"); var[0] = x; // Objective Function model.AddMaximize(model.Sum(model.Prod(1.0, x[0]), model.Prod(2.0, x[1]), model.Prod(3.0, x[2]), model.Prod(1.0, x[3]))); // Define three constraints one-by-one rng[0] = new IRange[3]; rng[0][0] = model.AddLe(model.Sum(model.Prod(-1.0, x[0]), model.Prod(1.0, x[1]), model.Prod(1.0, x[2]), model.Prod(10.0, x[3])), 20.0, "rng0"); rng[0][1] = model.AddLe(model.Sum(model.Prod(1.0, x[0]), model.Prod(-3.0, x[1]), model.Prod(1.0, x[2])), 30.0, "rng1"); rng[0][2] = model.AddEq(model.Sum(model.Prod(1.0, x[1]), model.Prod(-3.5, x[3])), 0, "rng2"); // add special ordered set of type 1 INumVar[] sosvars = { x[2], x[3] }; double[] sosweights = { 25.0, 18.0 }; model.AddSOS1(sosvars, sosweights); }
internal static void PopulateByRow (IMPModeler model, INumVar[][] var, IRange[][] rng) { // Define the variables one-by-one INumVar[] x = new INumVar[4]; x[0] = model.NumVar(0.0, 40.0, "x0"); x[1] = model.IntVar(0, System.Int32.MaxValue, "x1"); x[2] = model.IntVar(0, System.Int32.MaxValue, "x2"); x[3] = model.IntVar(2, 3, "x3"); var[0] = x; // Objective Function model.AddMaximize(model.Sum(model.Prod( 1.0, x[0]), model.Prod( 2.0, x[1]), model.Prod( 3.0, x[2]), model.Prod( 1.0, x[3]))); // Define three constraints one-by-one rng[0] = new IRange[3]; rng[0][0] = model.AddLe(model.Sum(model.Prod(-1.0, x[0]), model.Prod( 1.0, x[1]), model.Prod( 1.0, x[2]), model.Prod(10.0, x[3])), 20.0, "rng0"); rng[0][1] = model.AddLe(model.Sum(model.Prod( 1.0, x[0]), model.Prod(-3.0, x[1]), model.Prod( 1.0, x[2])), 30.0, "rng1"); rng[0][2] = model.AddEq(model.Sum(model.Prod( 1.0, x[1]), model.Prod(-3.5, x[3])), 0, "rng2"); // add special ordered set of type 1 INumVar[] sosvars = {x[2], x[3]}; double[] sosweights = {25.0, 18.0}; model.AddSOS1(sosvars, sosweights); }
public static void Main(string[] args) { try { Cplex cplex = new Cplex(); INumVar[][] var = new INumVar[1][]; IRange[][] rng = new IRange[1][]; PopulateByRow(cplex, var, rng); if (cplex.Solve()) { double[] x = cplex.GetValues(var[0]); double[] slack = cplex.GetSlacks(rng[0]); System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine("Solution value = " + cplex.ObjValue); for (int j = 0; j < x.Length; ++j) { System.Console.WriteLine("Variable " + j + ": Value = " + x[j]); } for (int i = 0; i < slack.Length; ++i) { System.Console.WriteLine("Constraint " + i + ": Slack = " + slack[i]); } } cplex.ExportModel("mipex1.lp"); cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception caught '" + e + "' caught"); } }
// Print out the objective function. // Note that the quadratic expression in the objective // is normalized: i.E., for all i != j, terms // c(i,j)*x[i]*x[j] + c(j,i)*x[j]*x[i] is normalized as // (c(i,j) + c(j,i)) * x[i]*x[j], or // (c(i,j) + c(j,i)) * x[j]*x[i]. internal static void PrintObjective(IObjective obj) { System.Console.WriteLine("obj: " + obj); // Count the number of linear terms // in the objective function. int nlinterms = 0; ILinearNumExprEnumerator len = ((ILQNumExpr)obj.Expr).GetLinearEnumerator(); while (len.MoveNext()) { ++nlinterms; } // Count the number of quadratic terms // in the objective function. int nquadterms = 0; int nquaddiag = 0; IQuadNumExprEnumerator qen = ((ILQNumExpr)obj.Expr).GetQuadEnumerator(); while (qen.MoveNext()) { ++nquadterms; INumVar var1 = qen.GetNumVar1(); INumVar var2 = qen.GetNumVar2(); if (var1.Equals(var2)) { ++nquaddiag; } } System.Console.WriteLine("number of linear terms in the objective : " + nlinterms); System.Console.WriteLine("number of quadratic terms in the objective : " + nquadterms); System.Console.WriteLine("number of diagonal quadratic terms in the objective : " + nquaddiag); System.Console.WriteLine(); }
internal static void BuildModelByColumn(IMPModeler model, Data data, INumVar[] Buy, NumVarType type) { int nFoods = data.nFoods; int nNutrs = data.nNutrs; IObjective cost = model.AddMinimize(); IRange[] constraint = new IRange[nNutrs]; for (int i = 0; i < nNutrs; i++) { constraint[i] = model.AddRange(data.nutrMin[i], data.nutrMax[i]); } for (int j = 0; j < nFoods; j++) { Column col = model.Column(cost, data.foodCost[j]); for (int i = 0; i < nNutrs; i++) { col = col.And(model.Column(constraint[i], data.nutrPerFood[i][j])); } Buy[j] = model.NumVar(col, data.foodMin[j], data.foodMax[j], type); } }
internal Solve(INumVar[] vars, double[] x) { _vars = vars; _x = x; }
internal MyBranchGoal(INumVar[] vars) { _vars = vars; }
// The following method populates the problem with data for the // following linear program: // // Maximize // x1 + 2 x2 + 3 x3 // Subject To // - x1 + x2 + x3 <= 20 // x1 - 3 x2 + x3 <= 30 // Bounds // 0 <= x1 <= 40 // End // // using the IModeler API internal static void PopulateByRow(IModeler model, INumVar[][] var, IRange[][] rng) { double[] lb = {0.0, 0.0, 0.0}; double[] ub = {40.0, System.Double.MaxValue, System.Double.MaxValue}; string[] varname = {"x1", "x2", "x3"}; INumVar[] x = model.NumVarArray(3, lb, ub, varname); var[0] = x; double[] objvals = {1.0, 2.0, 3.0}; model.AddMaximize(model.ScalProd(x, objvals)); rng[0] = new IRange[2]; rng[0][0] = model.AddLe(model.Sum(model.Prod(-1.0, x[0]), model.Prod( 1.0, x[1]), model.Prod( 1.0, x[2])), 20.0, "c1"); rng[0][1] = model.AddLe(model.Sum(model.Prod( 1.0, x[0]), model.Prod(-3.0, x[1]), model.Prod( 1.0, x[2])), 30.0, "c2"); }
internal ModelData(IModel m, INumVar[] v) { model = m; vars = v; }
public INumExpr Prod(double coef, INumVar var) { INumExpr result = new INumExpr(); result.expr += coef * var.var; return result; }
internal static void PopulateByNonzero(IMPModeler model, INumVar[][] var, IRange[][] rng) { double[] lb = {0.0, 0.0, 0.0}; double[] ub = {40.0, System.Double.MaxValue, System.Double.MaxValue}; INumVar[] x = model.NumVarArray(3, lb, ub); var[0] = x; double[] objvals = {1.0, 2.0, 3.0}; model.Add(model.Maximize(model.ScalProd(x, objvals))); rng[0] = new IRange[2]; rng[0][0] = model.AddRange(-System.Double.MaxValue, 20.0); rng[0][1] = model.AddRange(-System.Double.MaxValue, 30.0); rng[0][0].Expr = model.Sum(model.Prod(-1.0, x[0]), model.Prod( 1.0, x[1]), model.Prod( 1.0, x[2])); rng[0][1].Expr = model.Sum(model.Prod( 1.0, x[0]), model.Prod(-3.0, x[1]), model.Prod( 1.0, x[2])); x[0].Name = "x1"; x[1].Name = "x2"; x[2].Name = "x3"; rng[0][0].Name = "c1"; rng[0][0].Name = "c2"; }
public static void Main(string[] args) { try { string filename = "../../../../examples/data/steel.dat"; if ( args.Length > 0 ) filename = args[0]; ReadData(filename); Cplex cplex = new Cplex(); // VARIABLES INumVar[][] Make = new INumVar[_nProd][]; for (int p = 0; p < _nProd; p++) { Make[p] = cplex.NumVarArray(_nTime, 0.0, System.Double.MaxValue); } INumVar[][] Inv = new INumVar[_nProd][]; for (int p = 0; p < _nProd; p++) { Inv[p] = cplex.NumVarArray(_nTime, 0.0, System.Double.MaxValue); } INumVar[][] Sell = new INumVar[_nProd][]; for (int p = 0; p < _nProd; p++) { Sell[p] = new INumVar[_nTime]; for (int t = 0; t < _nTime; t++) { Sell[p][t] = cplex.NumVar(0.0, _market[p][t]); } } // OBJECTIVE ILinearNumExpr TotalRevenue = cplex.LinearNumExpr(); ILinearNumExpr TotalProdCost = cplex.LinearNumExpr(); ILinearNumExpr TotalInvCost = cplex.LinearNumExpr(); for (int p = 0; p < _nProd; p++) { for (int t = 1; t < _nTime; t++) { TotalRevenue.AddTerm (_revenue[p][t], Sell[p][t]); TotalProdCost.AddTerm(_prodCost[p], Make[p][t]); TotalInvCost.AddTerm (_invCost[p], Inv[p][t]); } } cplex.AddMaximize(cplex.Diff(TotalRevenue, cplex.Sum(TotalProdCost, TotalInvCost))); // TIME AVAILABILITY CONSTRAINTS for (int t = 0; t < _nTime; t++) { ILinearNumExpr availExpr = cplex.LinearNumExpr(); for (int p = 0; p < _nProd; p++) { availExpr.AddTerm(1.0/_rate[p], Make[p][t]); } cplex.AddLe(availExpr, _avail[t]); } // MATERIAL BALANCE CONSTRAINTS for (int p = 0; p < _nProd; p++) { cplex.AddEq(cplex.Sum(Make[p][0], _inv0[p]), cplex.Sum(Sell[p][0], Inv[p][0])); for (int t = 1; t < _nTime; t++) { cplex.AddEq(cplex.Sum(Make[p][t], Inv[p][t-1]), cplex.Sum(Sell[p][t], Inv[p][t])); } } cplex.ExportModel("steel.lp"); if ( cplex.Solve() ) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine(); System.Console.WriteLine("Total Profit = " + cplex.ObjValue); System.Console.WriteLine(); System.Console.WriteLine("\tp\tt\tMake\tInv\tSell"); for (int p = 0; p < _nProd; p++) { for (int t = 0; t < _nTime; t++) { System.Console.WriteLine("\t" + p +"\t" + t +"\t" + cplex.GetValue(Make[p][t]) + "\t" + cplex.GetValue(Inv[p][t]) +"\t" + cplex.GetValue(Sell[p][t])); } } } cplex.End(); } catch (ILOG.Concert.Exception exc) { System.Console.WriteLine("Concert exception '" + exc + "' caught"); } catch (System.IO.IOException exc) { System.Console.WriteLine("Error reading file " + args[0] + ": " + exc); } catch (InputDataReader.InputDataReaderException exc) { System.Console.WriteLine(exc); } }
public INumExpr ScalProd(INumVar[] vars, double[] coefs) { return ScalProd(coefs, vars); }
internal LogCallback(INumVar[] var, int lastLog, double lastIncumbent) { _var = var; _lastLog = lastLog; _lastIncumbent = lastIncumbent; }
public INumExpr Prod(INumVar var, double coef) { return Prod(coef, var); }
public static void Main(string[] args) { try { string filename = "../../../../examples/data/diet.dat"; bool byColumn = false; NumVarType varType = NumVarType.Float; for (int i = 0; i < args.Length; i++) { if ( args[i].ToCharArray()[0] == '-') { switch (args[i].ToCharArray()[1]) { case 'c': byColumn = true; break; case 'i': varType = NumVarType.Int; break; default: Usage(); return; } } else { filename = args[i]; break; } } Data data = new Data(filename); int nFoods = data.nFoods; int nNutrs = data.nNutrs; // Build model Cplex cplex = new Cplex(); INumVar[] Buy = new INumVar[nFoods]; if ( byColumn ) BuildModelByColumn(cplex, data, Buy, varType); else BuildModelByRow (cplex, data, Buy, varType); // Solve model if ( cplex.Solve() ) { System.Console.WriteLine(); System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine(); System.Console.WriteLine(" cost = " + cplex.ObjValue); for (int i = 0; i < nFoods; i++) { System.Console.WriteLine(" Buy" + i + " = " + cplex.GetValue(Buy[i])); } System.Console.WriteLine(); } cplex.End(); } catch (ILOG.Concert.Exception ex) { System.Console.WriteLine("Concert Error: " + ex); } catch (InputDataReader.InputDataReaderException ex) { System.Console.WriteLine("Data Error: " + ex); } catch (System.IO.IOException ex) { System.Console.WriteLine("IO Error: " + ex); } }
public static void Main( string[] args ) { try { Cplex cplex = new Cplex(); INumVar[] m = cplex.NumVarArray(_nbElements, 0.0, System.Double.MaxValue); INumVar[] r = cplex.NumVarArray(_nbRaw, 0.0, System.Double.MaxValue); INumVar[] s = cplex.NumVarArray(_nbScrap, 0.0, System.Double.MaxValue); INumVar[] i = cplex.IntVarArray(_nbIngot, 0, System.Int32.MaxValue); INumVar[] e = new INumVar[_nbElements]; // Objective Function: Minimize Cost cplex.AddMinimize(cplex.Sum(cplex.ScalProd(_cm, m), cplex.ScalProd(_cr, r), cplex.ScalProd(_cs, s), cplex.ScalProd(_ci, i))); // Min and max quantity of each element in alloy for (int j = 0; j < _nbElements; j++) { e[j] = cplex.NumVar(_p[j] * _alloy, _P[j] * _alloy); } // Constraint: produce requested quantity of alloy cplex.AddEq(cplex.Sum(e), _alloy); // Constraints: Satisfy element quantity requirements for alloy for (int j = 0; j < _nbElements; j++) { cplex.AddEq(e[j], cplex.Sum(m[j], cplex.ScalProd(_PRaw[j], r), cplex.ScalProd(_PScrap[j], s), cplex.ScalProd(_PIngot[j], i))); } if ( cplex.Solve() ) { if ( cplex.GetStatus().Equals(Cplex.Status.Infeasible) ) { System.Console.WriteLine("No feasible solution found"); return; } double[] mVals = cplex.GetValues(m); double[] rVals = cplex.GetValues(r); double[] sVals = cplex.GetValues(s); double[] iVals = cplex.GetValues(i); double[] eVals = cplex.GetValues(e); // Print results System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine("Cost:" + cplex.ObjValue); System.Console.WriteLine("Pure metal:"); for(int j = 0; j < _nbElements; j++) System.Console.WriteLine("(" + j + ") " + mVals[j]); System.Console.WriteLine("Raw material:"); for(int j = 0; j < _nbRaw; j++) System.Console.WriteLine("(" + j + ") " + rVals[j]); System.Console.WriteLine("Scrap:"); for(int j = 0; j < _nbScrap; j++) System.Console.WriteLine("(" + j + ") " + sVals[j]); System.Console.WriteLine("Ingots : "); for(int j = 0; j < _nbIngot; j++) System.Console.WriteLine("(" + j + ") " + iVals[j]); System.Console.WriteLine("Elements:"); for(int j = 0; j < _nbElements; j++) System.Console.WriteLine("(" + j + ") " + eVals[j]); } cplex.End(); } catch (ILOG.Concert.Exception exc) { System.Console.WriteLine("Concert exception '" + exc + "' caught"); } }
// The constructor sets up the Cplex instance to solve the worker LP, // and creates the worker LP (i.e., the dual of flow constraints and // capacity constraints of the flow MILP) // // Modeling variables: // forall k in V0, i in V: // u(k,i) = dual variable associated with flow constraint (k,i) // // forall k in V0, forall (i,j) in A: // v(k,i,j) = dual variable associated with capacity constraint (k,i,j) // // Objective: // minimize sum(k in V0) sum((i,j) in A) x(i,j) * v(k,i,j) // - sum(k in V0) u(k,0) + sum(k in V0) u(k,k) // // Constraints: // forall k in V0, forall (i,j) in A: u(k,i) - u(k,j) <= v(k,i,j) // // Nonnegativity on variables v(k,i,j) // forall k in V0, forall (i,j) in A: v(k,i,j) >= 0 // internal WorkerLP(int numNodes) { this.numNodes = numNodes; int i, j, k; // Set up Cplex instance to solve the worker LP cplex = new Cplex(); cplex.SetOut(null); // Turn off the presolve reductions and set the CPLEX optimizer // to solve the worker LP with primal simplex method. cplex.SetParam(Cplex.Param.Preprocessing.Reduce, 0); cplex.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Primal); // Create variables v(k,i,j) forall k in V0, (i,j) in A // For simplicity, also dummy variables v(k,i,i) are created. // Those variables are fixed to 0 and do not partecipate to // the constraints. v = new INumVar[numNodes-1][][]; for (k = 1; k < numNodes; ++k) { v[k-1] = new INumVar[numNodes][]; for (i = 0; i < numNodes; ++i) { v[k-1][i] = new INumVar[numNodes]; for (j = 0; j < numNodes; ++j) { v[k-1][i][j] = cplex.NumVar(0.0, System.Double.MaxValue, "v." + k + "." + i + "." + j); cplex.Add(v[k-1][i][j]); } v[k-1][i][i].UB = 0.0; } } // Create variables u(k,i) forall k in V0, i in V u = new INumVar[numNodes-1][]; for (k = 1; k < numNodes; ++k) { u[k-1] = new INumVar[numNodes]; for (i = 0; i < numNodes; ++i) { u[k-1][i] = cplex.NumVar(-System.Double.MaxValue, System.Double.MaxValue, "u." + k + "." + i); cplex.Add(u[k-1][i]); } } // Initial objective function is empty cplex.AddMinimize(); // Add constraints: // forall k in V0, forall (i,j) in A: u(k,i) - u(k,j) <= v(k,i,j) for (k = 1; k < numNodes; ++k) { for (i = 0; i < numNodes; ++i) { for (j = 0; j < numNodes; ++j) { if ( i != j ) { ILinearNumExpr expr = cplex.LinearNumExpr(); expr.AddTerm(v[k-1][i][j], -1.0); expr.AddTerm(u[k-1][i], 1.0); expr.AddTerm(u[k-1][j], -1.0); cplex.AddLe(expr, 0.0); } } } } }
internal static IRange[] MakeCuts(IModeler m, ILPMatrix lp) { INumVar x11 = null, x12 = null, x13 = null, x14 = null, x15 = null; INumVar x21 = null, x22 = null, x23 = null, x24 = null, x25 = null; INumVar x31 = null, x32 = null, x33 = null, x34 = null, x35 = null; INumVar x41 = null, x42 = null, x43 = null, x44 = null, x45 = null; INumVar x51 = null, x52 = null, x53 = null, x54 = null, x55 = null; INumVar w11 = null, w12 = null, w13 = null, w14 = null, w15 = null; INumVar w21 = null, w22 = null, w23 = null, w24 = null, w25 = null; INumVar w31 = null, w32 = null, w33 = null, w34 = null, w35 = null; INumVar w41 = null, w42 = null, w43 = null, w44 = null, w45 = null; INumVar w51 = null, w52 = null, w53 = null, w54 = null, w55 = null; INumVar[] vars = lp.NumVars; int num = vars.Length; for (int i = 0; i < num; ++i) { if (vars[i].Name.Equals("X11")) { x11 = vars[i]; } else if (vars[i].Name.Equals("X12")) { x12 = vars[i]; } else if (vars[i].Name.Equals("X13")) { x13 = vars[i]; } else if (vars[i].Name.Equals("X14")) { x14 = vars[i]; } else if (vars[i].Name.Equals("X15")) { x15 = vars[i]; } else if (vars[i].Name.Equals("X21")) { x21 = vars[i]; } else if (vars[i].Name.Equals("X22")) { x22 = vars[i]; } else if (vars[i].Name.Equals("X23")) { x23 = vars[i]; } else if (vars[i].Name.Equals("X24")) { x24 = vars[i]; } else if (vars[i].Name.Equals("X25")) { x25 = vars[i]; } else if (vars[i].Name.Equals("X31")) { x31 = vars[i]; } else if (vars[i].Name.Equals("X32")) { x32 = vars[i]; } else if (vars[i].Name.Equals("X33")) { x33 = vars[i]; } else if (vars[i].Name.Equals("X34")) { x34 = vars[i]; } else if (vars[i].Name.Equals("X35")) { x35 = vars[i]; } else if (vars[i].Name.Equals("X41")) { x41 = vars[i]; } else if (vars[i].Name.Equals("X42")) { x42 = vars[i]; } else if (vars[i].Name.Equals("X43")) { x43 = vars[i]; } else if (vars[i].Name.Equals("X44")) { x44 = vars[i]; } else if (vars[i].Name.Equals("X45")) { x45 = vars[i]; } else if (vars[i].Name.Equals("X51")) { x51 = vars[i]; } else if (vars[i].Name.Equals("X52")) { x52 = vars[i]; } else if (vars[i].Name.Equals("X53")) { x53 = vars[i]; } else if (vars[i].Name.Equals("X54")) { x54 = vars[i]; } else if (vars[i].Name.Equals("X55")) { x55 = vars[i]; } else if (vars[i].Name.Equals("W11")) { w11 = vars[i]; } else if (vars[i].Name.Equals("W12")) { w12 = vars[i]; } else if (vars[i].Name.Equals("W13")) { w13 = vars[i]; } else if (vars[i].Name.Equals("W14")) { w14 = vars[i]; } else if (vars[i].Name.Equals("W15")) { w15 = vars[i]; } else if (vars[i].Name.Equals("W21")) { w21 = vars[i]; } else if (vars[i].Name.Equals("W22")) { w22 = vars[i]; } else if (vars[i].Name.Equals("W23")) { w23 = vars[i]; } else if (vars[i].Name.Equals("W24")) { w24 = vars[i]; } else if (vars[i].Name.Equals("W25")) { w25 = vars[i]; } else if (vars[i].Name.Equals("W31")) { w31 = vars[i]; } else if (vars[i].Name.Equals("W32")) { w32 = vars[i]; } else if (vars[i].Name.Equals("W33")) { w33 = vars[i]; } else if (vars[i].Name.Equals("W34")) { w34 = vars[i]; } else if (vars[i].Name.Equals("W35")) { w35 = vars[i]; } else if (vars[i].Name.Equals("W41")) { w41 = vars[i]; } else if (vars[i].Name.Equals("W42")) { w42 = vars[i]; } else if (vars[i].Name.Equals("W43")) { w43 = vars[i]; } else if (vars[i].Name.Equals("W44")) { w44 = vars[i]; } else if (vars[i].Name.Equals("W45")) { w45 = vars[i]; } else if (vars[i].Name.Equals("W51")) { w51 = vars[i]; } else if (vars[i].Name.Equals("W52")) { w52 = vars[i]; } else if (vars[i].Name.Equals("W53")) { w53 = vars[i]; } else if (vars[i].Name.Equals("W54")) { w54 = vars[i]; } else if (vars[i].Name.Equals("W55")) { w55 = vars[i]; } } IRange[] cut = new IRange[8]; cut[0] = m.Le(m.Diff(x21, x22), 0.0); cut[1] = m.Le(m.Diff(x22, x23), 0.0); cut[2] = m.Le(m.Diff(x23, x24), 0.0); cut[3] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x11), m.Prod(2.98, x21), m.Prod(3.47, x31), m.Prod(2.24, x41), m.Prod(2.08, x51)), m.Sum(m.Prod(0.25, w11), m.Prod(0.25, w21), m.Prod(0.25, w31), m.Prod(0.25, w41), m.Prod(0.25, w51))), 20.25); cut[4] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x12), m.Prod(2.98, x22), m.Prod(3.47, x32), m.Prod(2.24, x42), m.Prod(2.08, x52)), m.Sum(m.Prod(0.25, w12), m.Prod(0.25, w22), m.Prod(0.25, w32), m.Prod(0.25, w42), m.Prod(0.25, w52))), 20.25); cut[5] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x13), m.Prod(2.98, x23), m.Prod(3.47, x33), m.Prod(2.24, x43), m.Prod(2.08, x53)), m.Sum(m.Prod(0.25, w13), m.Prod(0.25, w23), m.Prod(0.25, w33), m.Prod(0.25, w43), m.Prod(0.25, w53))), 20.25); cut[6] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x14), m.Prod(2.98, x24), m.Prod(3.47, x34), m.Prod(2.24, x44), m.Prod(2.08, x54)), m.Sum(m.Prod(0.25, w14), m.Prod(0.25, w24), m.Prod(0.25, w34), m.Prod(0.25, w44), m.Prod(0.25, w54))), 20.25); cut[7] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x15), m.Prod(2.98, x25), m.Prod(3.47, x35), m.Prod(2.24, x45), m.Prod(2.08, x55)), m.Sum(m.Prod(0.25, w15), m.Prod(0.25, w25), m.Prod(0.25, w35), m.Prod(0.25, w45), m.Prod(0.25, w55))), 16.25); return(cut); }
internal static void PopulateByColumn(IMPModeler model, INumVar[][] var, IRange[][] rng) { IObjective obj = model.AddMaximize(); rng[0] = new IRange[2]; rng[0][0] = model.AddRange(-System.Double.MaxValue, 20.0, "c1"); rng[0][1] = model.AddRange(-System.Double.MaxValue, 30.0, "c2"); IRange r0 = rng[0][0]; IRange r1 = rng[0][1]; var[0] = new INumVar[3]; var[0][0] = model.NumVar(model.Column(obj, 1.0).And( model.Column(r0, -1.0).And( model.Column(r1, 1.0))), 0.0, 40.0, "x1"); var[0][1] = model.NumVar(model.Column(obj, 2.0).And( model.Column(r0, 1.0).And( model.Column(r1, -3.0))), 0.0, System.Double.MaxValue, "x2"); var[0][2] = model.NumVar(model.Column(obj, 3.0).And( model.Column(r0, 1.0).And( model.Column(r1, 1.0))), 0.0, System.Double.MaxValue, "x3"); }