public void AddMinVol_OrConstraint(int MinVol) { for (int i = 0; i < EmptyMoves.Length; i++) { theModel.Add(theModel.Or(theModel.Ge(EmptyMoves[i], MinVol), theModel.Ge(EmptyMoves[i], 0))); } for (int i = 0; i < LoadedMoves.Length; i++) { theModel.Add(theModel.Or(theModel.Ge(LoadedMoves[i], MinVol), theModel.Ge(LoadedMoves[i], 0))); } }
public static void Main(string[] args) { try { Cplex cplex = new Cplex(); cplex.ImportModel(args[0]); IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator(); matrixEnum.MoveNext(); ILPMatrix lp = (ILPMatrix)matrixEnum.Current; IConversion relax = cplex.Conversion(lp.NumVars, NumVarType.Float); cplex.Add(relax); cplex.Solve(); System.Console.WriteLine("Relaxed solution status = " + cplex.GetStatus()); System.Console.WriteLine("Relaxed solution value = " + cplex.ObjValue); double[] vals = cplex.GetValues(lp.NumVars); cplex.Use(new Solve(lp.NumVars, vals)); cplex.Delete(relax); cplex.SetParam(Cplex.Param.MIP.Strategy.Search, Cplex.MIPSearch.Traditional); if ( cplex.Solve() ) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine("Solution value = " + cplex.ObjValue); } cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception caught: " + e); } }
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)); } }
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); }
/// <summary> /// Adds the constraint to the model. /// </summary> /// <param name="expression">The constraint to add to the model.</param> /// <param name="name">A unique name of the constraint.</param> public void AddConstr(LinearExpression expression, string name) { switch (Type) { case SolverType.CPLEX: CplexModel.Add(expression.Expression); break; case SolverType.Gurobi: GurobiModel.AddConstr(expression.Expression, name); break; default: throw new ArgumentException("Unknown solver type: " + Type); } }
private void initializeExclusionConstraint(Cplex cplex, BinaryOption currentBinOpt, INumVar current, List <ConfigurationOption> notAllowed, INumExpr trigger) { INumVar[] excluded = populateArray(current, notAllowed); // If there is some kind of exclusiion then the sum of the group has to be one if the // trigger(either the parent for alternative groups or the current option for cross tree exclusions) // is selected cplex.Add(cplex.IfThen( cplex.Eq(one, trigger), cplex.Eq(one, cplex.Sum(excluded)) )); }
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) )); }
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())) )); } }
/// <summary>分支定价 /// 从指定的初始解作为上界开始 /// </summary> /// <param name="IS"></param> public void Branch_and_Price(InitialSolution IS) //initial solution初始解 { Stopwatch sw = new Stopwatch(); //stopwatch获取以每秒计时周期数表示的计时器频率,即计时 sw.Start(); //Build_RMP(IS); Build_RMP_YY(IS); //20191004 WriteModelToFIle(); root_node = new TreeNode(); CG(ref root_node); //ref-引用,修改参数变量的修改也将导致原来变量的值被修改 sw.Stop(); Console.WriteLine("根节点求解时间: " + sw.Elapsed.TotalSeconds); Console.WriteLine("根节点目标值: " + root_node.obj_value); best_feasible_solution = new List <int>(); //最优解 //RecordFeasibleSolution(root_node, ref best_feasible_solution); RecordFeasibleSolution(ref best_feasible_solution); double UB = IS.initial_ObjValue;//int.MaxValue; double LB = root_node.obj_value; sw.Restart(); //Branch_and_Bound(root_node , LB , UB); // 不分支定界了,转化为整数规划求解 IConversion mip = masterModel.Conversion(DvarSet.ToArray(), NumVarType.Int); masterModel.Add(mip); masterModel.Solve(); Console.WriteLine("RMP_BOJ:" + masterModel.GetObjValue()); RecordFeasibleSolution(ref best_feasible_solution); WriteOptScheduleToFile(); sw.Stop(); Console.WriteLine("分支定价共花费时间:" + sw.Elapsed.TotalSeconds); }
public static void Main(string[] args) { try { Cplex cplex = new Cplex(); cplex.ImportModel(args[0]); IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator(); matrixEnum.MoveNext(); ILPMatrix lp = (ILPMatrix)matrixEnum.Current; IConversion relax = cplex.Conversion(lp.NumVars, NumVarType.Float); cplex.Add(relax); cplex.Solve(); System.Console.WriteLine("Relaxed solution status = " + cplex.GetStatus()); System.Console.WriteLine("Relaxed solution value = " + cplex.ObjValue); double[] vals = cplex.GetValues(lp.NumVars); cplex.Use(new Solve(lp.NumVars, vals)); cplex.Delete(relax); cplex.SetParam(Cplex.Param.MIP.Strategy.Search, Cplex.MIPSearch.Traditional); if (cplex.Solve()) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine("Solution value = " + cplex.ObjValue); } cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception caught: " + e); } }
static void Main() { try { string resultFilename = "./ResultFiles/MTSP_MTZ.csv"; string filename = "./DataFiles/Data.dat"; Data data = new Data(filename); double timeFactor = 0; double distanceFactor = 1; double step = 0.1; int routeCounter = 0; File.WriteAllText(resultFilename, ""); do { using (Cplex cplex = new Cplex()) { #region [Decision Variables] IIntVar[][] x = new IIntVar[data.n][]; IIntVar Q = cplex.IntVar(1, 250, "Q"); for (int i = 0; i < data.n; i++) { x[i] = cplex.BoolVarArray(data.n); cplex.Add(x[i]); } #endregion #region [Objective Function] INumExpr obj = cplex.NumExpr(); for (int i = 0; i < data.n; i++) { for (int j = 0; j < data.n; j++) { if (i != j) { obj = cplex.Sum(obj, cplex.Prod( ( (timeFactor * data.timeNormalized[i][j]) + (distanceFactor * data.distanceNormalized[i][j]) ), x[i][j])); } } } cplex.AddMinimize(obj); #endregion #region [Restrictions] for (int j = 0; j < data.n; j++) { ILinearNumExpr sumj = cplex.LinearNumExpr(); for (int i = 0; i < data.n; i++) { if (i != j) { sumj.AddTerm(1, x[i][j]); } } cplex.AddEq(sumj, 1); } for (int i = 0; i < data.n; i++) { ILinearNumExpr sumi = cplex.LinearNumExpr(); for (int j = 0; j < data.n; j++) { if (i != j) { sumi.AddTerm(1, x[i][j]); } } cplex.AddEq(sumi, 1); } #endregion cplex.SetParam(Cplex.DoubleParam.WorkMem, 4000.0); cplex.SetParam(Cplex.Param.MIP.Strategy.File, 2); cplex.SetParam(Cplex.DoubleParam.EpGap, 0.1); cplex.SetParam(Cplex.BooleanParam.MemoryEmphasis, true); cplex.SetParam(Cplex.IntParam.VarSel, 4); SOLVE: Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); if (cplex.Solve()) { stopWatch.Stop(); double[][] sol_x = new double[data.n][]; for (int i = 0; i < data.n; i++) { sol_x[i] = cplex.GetValues(x[i]); } int[] tour = FindSubTour(sol_x); if (tour.Length < data.n) { ILinearNumExpr sumx = cplex.LinearNumExpr(); for (int i = 0; i < tour.Length; i++) { for (int j = 0; j < tour.Length; j++) { sumx.AddTerm(1, x[tour[i]][tour[j]]); } } cplex.AddLazyConstraint(cplex.AddLe(cplex.Diff(sumx, tour.Length), -1)); goto SOLVE; } double timeTotal = 0; double distanceTotal = 0; for (int i = 0; i < data.n; i++) { for (int j = 0; j < data.n; j++) { timeTotal += data.time[i][j] * sol_x[i][j]; distanceTotal += data.distance[i][j] * sol_x[i][j]; } } StreamWriter file = new StreamWriter(resultFilename, true); file.WriteLine($"{timeFactor},{distanceFactor},{stopWatch.Elapsed.TotalSeconds},{cplex.ObjValue},{timeTotal},{distanceTotal}"); file.Close(); StreamWriter fileRouteResult = new StreamWriter($"./ResultFiles/Route-{routeCounter}.txt"); for (int i = 0; i < data.n; i++) { for (int j = 0; j < data.n; j++) { if (sol_x[i][j] == 1) { fileRouteResult.WriteLine($"From city {i} to city {j}"); } } } fileRouteResult.Close(); } cplex.End(); } timeFactor += step; distanceFactor -= step; routeCounter++; } while (timeFactor <= 1); } catch (ILOG.Concert.Exception ex) { StreamWriter errorfile = new StreamWriter("./ErrorLog.txt"); errorfile.WriteLine("Exception Kind: ILOG.Concert.Exception (Concert Error)"); errorfile.WriteLine("Message: " + ex.Message); errorfile.WriteLine("StackTrace: " + ex.StackTrace); errorfile.Close(); } catch (InputDataReader.InputDataReaderException ex) { StreamWriter errorfile = new StreamWriter("./ErrorLog.txt"); errorfile.WriteLine("Exception Kind: InputDataReader.InputDataReaderException (Data Error)"); errorfile.WriteLine("Message: " + ex.Message); errorfile.WriteLine("StackTrace: " + ex.StackTrace); errorfile.Close(); } catch (System.IO.IOException ex) { StreamWriter errorfile = new StreamWriter("./ErrorLog.txt"); errorfile.WriteLine("Exception Kind: System.IO.IOException (IO Error)"); errorfile.WriteLine("Message: " + ex.Message); errorfile.WriteLine("StackTrace: " + ex.StackTrace); errorfile.Close(); } }
public static void Main(string[] args) { try { string datafile = "../../../../examples/data/cutstock.dat"; if (args.Length > 0) { datafile = args[0]; } ReadData(datafile); /// CUTTING-OPTIMIZATION PROBLEM /// Cplex cutSolver = new Cplex(); IObjective RollsUsed = cutSolver.AddMinimize(); IRange[] Fill = new IRange[_amount.Length]; for (int f = 0; f < _amount.Length; f++) { Fill[f] = cutSolver.AddRange(_amount[f], System.Double.MaxValue); } System.Collections.ArrayList Cut = new System.Collections.ArrayList(); int nWdth = _size.Length; for (int j = 0; j < nWdth; j++) { Cut.Add(cutSolver.NumVar(cutSolver.Column(RollsUsed, 1.0).And( cutSolver.Column(Fill[j], (int)(_rollWidth / _size[j]))), 0.0, System.Double.MaxValue)); } cutSolver.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Primal); /// PATTERN-GENERATION PROBLEM /// Cplex patSolver = new Cplex(); IObjective ReducedCost = patSolver.AddMinimize(); INumVar[] Use = patSolver.NumVarArray(nWdth, 0.0, System.Double.MaxValue, NumVarType.Int); patSolver.AddRange(-System.Double.MaxValue, patSolver.ScalProd(_size, Use), _rollWidth); /// COLUMN-GENERATION PROCEDURE /// double[] newPatt = new double[nWdth]; /// COLUMN-GENERATION PROCEDURE /// for (;;) { /// OPTIMIZE OVER CURRENT PATTERNS /// cutSolver.Solve(); Report1(cutSolver, Cut, Fill); /// FIND AND ADD A NEW PATTERN /// double[] price = cutSolver.GetDuals(Fill); ReducedCost.Expr = patSolver.Diff(1.0, patSolver.ScalProd(Use, price)); patSolver.Solve(); Report2(patSolver, Use); if (patSolver.ObjValue > -RC_EPS) { break; } newPatt = patSolver.GetValues(Use); Column column = cutSolver.Column(RollsUsed, 1.0); for (int p = 0; p < newPatt.Length; p++) { column = column.And(cutSolver.Column(Fill[p], newPatt[p])); } Cut.Add(cutSolver.NumVar(column, 0.0, System.Double.MaxValue)); } for (int i = 0; i < Cut.Count; i++) { cutSolver.Add(cutSolver.Conversion((INumVar)Cut[i], NumVarType.Int)); } cutSolver.Solve(); System.Console.WriteLine("Solution status = " + cutSolver.GetStatus()); Report3(cutSolver, Cut); cutSolver.End(); patSolver.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); } }
// 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); } } } } } // END WorkerLP
private void initializeBinaryVariables(Cplex cplex, VariabilityModel vm) { // Add the binary variables foreach (BinaryOption binOpt in vm.BinaryOptions) { // Limit mandatory options to the value of 1 // Any option that has excluded options is not mandatory even if optional // is set to false if (binOpt.Optional == false && binOpt.Excluded_Options.Count == 0) { binOptsToCplexVars[binOpt] = cplex.NumVar(1, 1, NumVarType.Bool); } else { binOptsToCplexVars[binOpt] = cplex.NumVar(0, 1, NumVarType.Bool); } } HashSet <ConfigurationOption> alreadyHandled = new HashSet <ConfigurationOption>(); foreach (BinaryOption binOpt in vm.BinaryOptions) { INumVar curr = binOptsToCplexVars[binOpt]; // Add parent implication if (binOpt.Parent != null) { INumVar parent = binOptsToCplexVars[(BinaryOption)binOpt.Parent]; cplex.Add(cplex.IfThen(cplex.Eq(1, curr), cplex.Eq(1, parent))); } // Add exclusions if (binOpt.Excluded_Options.Count > 0) { List <ConfigurationOption> alternatives = binOpt.collectAlternativeOptions(); if (alternatives.Count > 0 && !alreadyHandled.Contains(binOpt)) { alternatives.ForEach(x => alreadyHandled.Add(x)); alreadyHandled.Add(binOpt); // Initialize a constraint that states that exactly one of the group has to be // selected if (binOpt.Parent != null) { initializeExclusionConstraint(cplex, binOpt, curr, alternatives, binOptsToCplexVars[(BinaryOption)binOpt.Parent]); } else { initializeExclusionConstraint(cplex, binOpt, curr, alternatives, one); } } List <List <ConfigurationOption> > nonAlternativeExclusives = binOpt.getNonAlternativeExlcudedOptions(); foreach (List <ConfigurationOption> nonAlternativeExclusiveGroup in nonAlternativeExclusives) { // Initialize constraint that states that if curr is selected all nonAlternative exclusives // have to be deselected initializeExclusionConstraint(cplex, binOpt, curr, nonAlternativeExclusiveGroup, curr); } } // Add implications initializeImpliedOptions(cplex, curr, binOpt); } initializeArbitraryBooleanConstraints(cplex, vm, binOptsToCplexVars); }
public static void Main( string[] args ) { try { string datafile = "../../../../examples/data/cutstock.dat"; if (args.Length > 0) datafile = args[0]; ReadData(datafile); /// CUTTING-OPTIMIZATION PROBLEM /// Cplex cutSolver = new Cplex(); IObjective RollsUsed = cutSolver.AddMinimize(); IRange[] Fill = new IRange[_amount.Length]; for (int f = 0; f < _amount.Length; f++ ) { Fill[f] = cutSolver.AddRange(_amount[f], System.Double.MaxValue); } System.Collections.ArrayList Cut = new System.Collections.ArrayList(); int nWdth = _size.Length; for (int j = 0; j < nWdth; j++) Cut.Add(cutSolver.NumVar(cutSolver.Column(RollsUsed, 1.0).And( cutSolver.Column(Fill[j], (int)(_rollWidth/_size[j]))), 0.0, System.Double.MaxValue)); cutSolver.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Primal); /// PATTERN-GENERATION PROBLEM /// Cplex patSolver = new Cplex(); IObjective ReducedCost = patSolver.AddMinimize(); INumVar[] Use = patSolver.NumVarArray(nWdth, 0.0, System.Double.MaxValue, NumVarType.Int); patSolver.AddRange(-System.Double.MaxValue, patSolver.ScalProd(_size, Use), _rollWidth); /// COLUMN-GENERATION PROCEDURE /// double[] newPatt = new double[nWdth]; /// COLUMN-GENERATION PROCEDURE /// for (;;) { /// OPTIMIZE OVER CURRENT PATTERNS /// cutSolver.Solve(); Report1(cutSolver, Cut, Fill); /// FIND AND ADD A NEW PATTERN /// double[] price = cutSolver.GetDuals(Fill); ReducedCost.Expr = patSolver.Diff(1.0, patSolver.ScalProd(Use, price)); patSolver.Solve(); Report2 (patSolver, Use); if ( patSolver.ObjValue > -RC_EPS ) break; newPatt = patSolver.GetValues(Use); Column column = cutSolver.Column(RollsUsed, 1.0); for ( int p = 0; p < newPatt.Length; p++ ) column = column.And(cutSolver.Column(Fill[p], newPatt[p])); Cut.Add( cutSolver.NumVar(column, 0.0, System.Double.MaxValue) ); } for ( int i = 0; i < Cut.Count; i++ ) { cutSolver.Add(cutSolver.Conversion((INumVar)Cut[i], NumVarType.Int)); } cutSolver.Solve(); System.Console.WriteLine("Solution status = " + cutSolver.GetStatus()); Report3 (cutSolver, Cut); cutSolver.End(); patSolver.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 Main(string[] args) { int nSamples = 0; // Number of samples int nMutGenes = 0; // Number of mutation genes int nExpGenes = 0; // Number of expression genes int nVar = 0; // Number of variables in MILP int nPathways = 5; // Number of pathways int nConstraints = 0; // Number of constraints in MILP Data data = new Data(); // Loads input data. data.ReadData("../../inputFile.txt"); nSamples = data.mutMatrix.Length; nMutGenes = data.mutMatrix[0].Length; nExpGenes = data.connectMat.Length; // Total number of decision variables: // pM --> nMutGenes * nPathways // pE --> nExpGenes * nPathways // aM --> nSamples * nPathways // fM --> nSamples * nPathways nVar = (nMutGenes * nPathways) + (nExpGenes * nPathways) + 2 * (nSamples * nPathways); // Instance of cplex model. Cplex cplex = new Cplex(); /* We were having issues with "Out of Memory" errors as we increased the number of samples and number of genes * To address this, we set parameter NodeFileInd = 3 --> this indicates that node info from MIP optimizer will be compressed * and written to files instead of accessing the computer memory during the simulation run * * */ cplex.SetParam(Cplex.IntParam.NodeFileInd, 3); // Sets names of decision variables. string[] name = new string[nVar]; for (int i = 1; i <= nVar; i++) { name[i - 1] = "x" + i.ToString(); } // Sets type, lower and upper bound of decision variables. NumVarType[] varType = new NumVarType[nVar]; double[] lb = new double[nVar]; double[] ub = new double[nVar]; for (int i = 0; i < nMutGenes * nPathways; i++) { // Variable pM is binary. varType[i] = NumVarType.Bool; lb[i] = 0; ub[i] = 1; } for (int i = nMutGenes * nPathways; i < (nMutGenes * nPathways) + (nExpGenes * nPathways); i++) { // Variable pE is real number. varType[i] = NumVarType.Float; lb[i] = 0; ub[i] = System.Double.MaxValue; } for (int i = (nMutGenes * nPathways) + (nExpGenes * nPathways); i < nVar; i++) { // Variables aM and fM are binary. varType[i] = NumVarType.Bool; lb[i] = 0; ub[i] = 1; } // Decision Variables. INumVar[] x = cplex.NumVarArray(nVar, lb, ub, varType, name); // Coeficients of objective function. double[] objvals = new double[nVar]; int contobjvals = 0; int idMap = 0; // Mapping index. // Variable pM. int[][] pM = new int[nMutGenes][]; // Mapping matrix pM. for (int i = 0; i < nMutGenes; i++) { pM[i] = new int[nPathways]; for (int j = 0; j < nPathways; j++) { // Mapping.... pM[i][j] = idMap; idMap++; objvals[contobjvals] = 0; for (int k = 0; k < nSamples; k++) { // Weight associated with first component of objective function = 0.1. objvals[contobjvals] += 0.1 * data.mutMatrix[k][i]; } contobjvals++; } } // Variable pE. int[][] pE = new int[nExpGenes][]; for (int i = 0; i < nExpGenes; i++) { pE[i] = new int[nPathways]; for (int j = 0; j < nPathways; j++) { // Mapping.... pE[i][j] = idMap; idMap++; // Weight associated with second component of objective function = 0.9. objvals[contobjvals] = -0.9; contobjvals++; } } // Variable aM. int[][] aM = new int[nSamples][]; for (int i = 0; i < nSamples; i++) { aM[i] = new int[nPathways]; for (int j = 0; j < nPathways; j++) { // Mapping.... aM[i][j] = idMap; idMap++; // Weight associated with first component of objective function = 0.1. objvals[contobjvals] = -0.1; contobjvals++; } } // Variable fM. int[][] fM = new int[nSamples][]; for (int i = 0; i < nSamples; i++) { fM[i] = new int[nPathways]; for (int j = 0; j < nPathways; j++) { // Mapping.... fM[i][j] = idMap; idMap++; // Weight associated with first component of objective function = 0.1. objvals[contobjvals] = 0.1; contobjvals++; } } // Defines the cost function as a minimization of decision variables with corresponding cost coefficients. cplex.Add(cplex.Minimize(cplex.ScalProd(x, objvals))); nConstraints = nMutGenes + nExpGenes + 2 * nPathways + nSamples * (nPathways - 1) + (nSamples * nPathways) + (nPathways * nExpGenes); // Total number of constraints. IRange[] constraint = new IRange[nConstraints]; int contconstraints = 0; INumExpr[] Expr = null; // Constraints C1. Expr = new INumExpr[nPathways]; for (int i = 0; i < nMutGenes; i++) { for (int j = 0; j < nPathways; j++) { Expr[j] = x[pM[i][j]]; } // Constraints of the form sum(pM) = 1. constraint[contconstraints] = cplex.AddRange(1, 1); // Defines right hand side (= 1). constraint[contconstraints].Expr = cplex.Sum(Expr); // Defines left hand side (sum(pM)). contconstraints++; } // Constraints C2. Expr = new INumExpr[nPathways]; for (int i = 0; i < nExpGenes; i++) { for (int j = 0; j < nPathways; j++) { Expr[j] = x[pE[i][j]]; } // Constraints of the form sum(pE) > 0. constraint[contconstraints] = cplex.AddRange(0.000001, System.Double.MaxValue); // Defines right hand side (> 0). constraint[contconstraints].Expr = cplex.Sum(Expr); // Defines left hand side (sum(pE)). contconstraints++; } // Constraints C3. Expr = new INumExpr[nMutGenes]; for (int i = 0; i < nPathways; i++) { for (int j = 0; j < nMutGenes; j++) { Expr[j] = x[pM[j][i]]; } // Constraints of the form sum(pM) >= 1. constraint[contconstraints] = cplex.AddRange(1, System.Double.MaxValue); // Defines right hand side (>= 1). constraint[contconstraints].Expr = cplex.Sum(Expr); // Defines left hand side (sum(pM)). contconstraints++; } // Constraints C4. int id = nMutGenes * nPathways; Expr = new INumExpr[nExpGenes]; for (int i = 0; i < nPathways; i++) { for (int j = 0; j < nExpGenes; j++) { Expr[j] = x[pE[j][i]]; } // Constraints of the form sum(pE) > 0. constraint[contconstraints] = cplex.AddRange(0.000001, System.Double.MaxValue); // Defines right hand side (> 0). constraint[contconstraints].Expr = cplex.Sum(Expr); // Defines left hand side (sum(pE)). contconstraints++; } // Constraints C5. id = nMutGenes * nPathways + nExpGenes * nPathways; for (int i = 0; i < nSamples; i++) { // Constraints of the form aM - aM >= 0. for (int j = 0; j < (nPathways - 1); j++) { constraint[contconstraints] = cplex.AddRange(0, System.Double.MaxValue); // Defines right hand side (>= 0). constraint[contconstraints].Expr = cplex.Sum(cplex.Prod(1.0, x[aM[i][j]]), cplex.Prod(-1.0, x[aM[i][j + 1]])); // Defines left hand side (aM - aM). contconstraints++; } } // Constraints C6. Expr = new INumExpr[nMutGenes + 2]; for (int i = 0; i < nSamples; i++) // Goes along lines of mutation matrix. { for (int k = 0; k < nPathways; k++) { for (int j = 0; j < nMutGenes; j++) // Goes along columns of mutation matrix. { Expr[j] = cplex.Prod(data.mutMatrix[i][j], x[pM[j][k]]); } Expr[nMutGenes] = cplex.Prod(1.0, x[fM[i][k]]); Expr[nMutGenes + 1] = cplex.Prod(-1.0, x[aM[i][k]]); // Constraints of the form sum(mutMat*pM) + fM - aM >= 0. constraint[contconstraints] = cplex.AddRange(0, System.Double.MaxValue); // Defines right hand side (>= 0). constraint[contconstraints].Expr = cplex.Sum(Expr); // Defines left hand side (sum(mutMat*pM) + fM - aM). contconstraints++; } } // Constraints C7. Expr = new INumExpr[nMutGenes + 1]; for (int i = 0; i < nPathways; i++) { for (int j = 0; j < nExpGenes; j++) { for (int k = 0; k < nMutGenes; k++) { Expr[k] = cplex.Prod(-data.connectMat[j][k], x[pM[k][i]]); } Expr[nMutGenes] = cplex.Prod(1.0, x[pE[j][i]]); // Constraints of the form pE - sum(connectMat*pM) = 0. constraint[contconstraints] = cplex.AddRange(0, 0); // Defines right hand side (= 0). constraint[contconstraints].Expr = cplex.Sum(Expr); // Defines left hand side (pE - sum(connectMat*pM)). contconstraints++; } } // Writes file with MILP model formulation. cplex.ExportModel("MILP.lp"); try { if (cplex.Solve()) { // Retrieves optimal values of decision variables. double[] xx = cplex.GetValues(x); // Displays solution info on command window. cplex.Output().WriteLine("Solution status=" + cplex.GetStatus()); cplex.Output().WriteLine("Solution value = " + cplex.ObjValue); // Writes output to txt file. StreamWriter objWriter = new StreamWriter("Result.txt"); int cont = 0; string sLine = ""; int nvars = xx.Length; objWriter.WriteLine("Total cost"); objWriter.WriteLine(cplex.ObjValue.ToString()); objWriter.WriteLine(""); objWriter.WriteLine("Matrix pM"); objWriter.WriteLine(""); for (int i = 0; i < nMutGenes; i++) { sLine = ""; for (int j = 0; j < nPathways; j++) { sLine += xx[cont].ToString() + "\t"; cont++; } objWriter.WriteLine(sLine); } // Value of second term of objective function (sum of pE's). double sumPE = 0.0; objWriter.WriteLine(""); objWriter.WriteLine("Matrix pE"); objWriter.WriteLine(""); for (int i = 0; i < nExpGenes; i++) { sLine = ""; for (int j = 0; j < nPathways; j++) { sLine += xx[cont].ToString() + "\t"; cont++; // Computes running sum of pE's. sumPE = sumPE + xx[cont]; } objWriter.WriteLine(sLine); } objWriter.WriteLine(""); objWriter.WriteLine("Sum pE"); objWriter.WriteLine(sumPE.ToString()); objWriter.WriteLine(""); objWriter.WriteLine(""); objWriter.WriteLine("Matrix aM"); objWriter.WriteLine(""); for (int i = 0; i < nSamples; i++) { sLine = ""; for (int j = 0; j < nPathways; j++) { sLine += xx[cont].ToString() + "\t"; cont++; } objWriter.WriteLine(sLine); } objWriter.WriteLine(""); objWriter.WriteLine("Matrix fM"); objWriter.WriteLine(""); for (int i = 0; i < nSamples; i++) { sLine = ""; for (int j = 0; j < nPathways; j++) { sLine += xx[cont].ToString() + "\t"; cont++; } objWriter.WriteLine(sLine); } objWriter.Close(); // Writes optimal solution info to file. cplex.WriteSolution("solution"); } else { cplex.GetCplexStatus(); } cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception '" + e + "' caught"); } }
static void Main(string[] args) { double BinCap = 0; var dict = InputReader.ReadDataFile(ref BinCap); Cplex cplex = new Cplex(); Dictionary <string, INumVar> dictvariables = new Dictionary <string, INumVar>(); Dictionary <string, IRange> dictconstraints = new Dictionary <string, IRange>(); IObjective objective = cplex.AddMinimize(); foreach (var vari in dict.Keys) { var cname = "C" + vari; dictconstraints.Add(cname, cplex.AddRange(1, Int32.MaxValue, cname)); } Dictionary <int, Set> InitialSets = new Dictionary <int, Set>();; InitialSets.Add(1, new Set(new List <int> { 1, 5 })); InitialSets.Add(2, new Set(new List <int> { 2, 5 })); InitialSets.Add(3, new Set(new List <int> { 3, 5 })); InitialSets.Add(4, new Set(new List <int> { 4, 5 })); //Add intial sets to the model foreach (var vari in InitialSets) { var setID = vari.Key.ToString(); Column VarSet = cplex.Column(objective, 1); foreach (var members in vari.Value.member) { var cname = "C" + members; VarSet = VarSet.And(cplex.Column(dictconstraints[cname], 1)); } dictvariables.Add(setID, cplex.NumVar(VarSet, 0, 1, NumVarType.Float)); } cplex.Solve(); var duals = getDuals(cplex, dictconstraints); var solution = getSolution(cplex, dictvariables); Console.WriteLine("The objective value is {0}", cplex.GetObjValue()); int piter = 0; int fixediter = 0; Dictionary <string, INumVar> Fixedvar = new Dictionary <string, INumVar>(); while (true) { //Formulate Pricing Problem Cplex pcplex = new Cplex(); IObjective pobjective = pcplex.AddMaximize(); piter++; //Add Bin Capacity Constraint IRange Knapsack = pcplex.AddRange(0, BinCap, "Bin"); Dictionary <string, INumVar> pdictvar = new Dictionary <string, INumVar>(); foreach (var vari in dict.Keys) { var varname = vari.ToString(); var objcoeff = duals["C" + varname]; Column item = pcplex.Column(pobjective, objcoeff); item = item.And(pcplex.Column(Knapsack, dict[vari])); pdictvar.Add(varname, pcplex.NumVar(item, 0, 1, NumVarType.Int)); } pcplex.Solve(); if (pcplex.GetObjValue() > 1) { Console.WriteLine("Pricing Iteration: {0} and obj value is {1} ", piter, pcplex.GetObjValue()); var psolution = getSolution(pcplex, pdictvar); List <int> sol = new List <int>(); foreach (var vari in psolution.Keys) { sol.Add(Convert.ToInt32(vari)); } InitialSets.Add(InitialSets.Count + 1, new Set(sol)); var setID = (InitialSets.Count).ToString(); Column VarSet1 = cplex.Column(objective, 1); foreach (var members in sol) { var cname = "C" + members; VarSet1 = VarSet1.And(cplex.Column(dictconstraints[cname], 1)); } dictvariables.Add(setID, cplex.NumVar(VarSet1, 0, 1, NumVarType.Float)); cplex.Solve(); Console.WriteLine("The objective value of cplex after adding column is {0}", cplex.GetObjValue()); duals = getDuals(cplex, dictconstraints); solution = getSolution(cplex, dictvariables); } else { fixediter++; bool fixedsomething = false; //fix variables above 0.5 foreach (var val in solution) { if (val.Value > 0.5 && !Fixedvar.ContainsKey(val.Key)) { Fixedvar.Add(val.Key, dictvariables[val.Key]); dictvariables[val.Key].LB = 1; fixedsomething = true; } } if (!fixedsomething) { break; } cplex.Solve(); Console.WriteLine("The Fixing iterations is {0}", cplex.GetObjValue()); duals = getDuals(cplex, dictconstraints); } } foreach (var vari in Fixedvar.Values) { vari.LB = 0; } IConversion IP = cplex.Conversion(dictvariables.Values.ToArray(), NumVarType.Int); cplex.Add(IP); cplex.SetParam(Cplex.DoubleParam.TiLim, 600); cplex.Solve(); solution = getSolution(cplex, dictvariables); Console.WriteLine("The objective value is {0}", cplex.GetObjValue()); }
static void Main(string[] args) { string data_path = "Server = PC-201606172102\\SQLExpress;DataBase = 乘务计划;Integrated Security = true"; /*--LOAD DATA FROM SQL--*/ NetWork Network = new NetWork(); Network.CreateNetwork(data_path); Network.IsAllTripsCovered(); //建网,一天的没问题,但未删除出入度为0的点与弧 //出度为0,说明到达站不在乘务基地,说明其到达时间太晚,无法接续 其他到站为乘务基地的车次 //入度为0,说明出发站不在乘务基地,说明其出发时间太早,发站为乘务基地的车次 无法接续 到它 //两天的网,再说 System.Diagnostics.Stopwatch Net_start = new System.Diagnostics.Stopwatch(); Net_start.Start(); InitialSolution IS = new InitialSolution(Network); //京津,200车次,初始解耗时:107s;建网仅0.6s IS.GetFeasibleSolutionByPenalty(); //Add 2-21-2019 Net_start.Stop(); TimeSpan initiail_solution = Net_start.Elapsed; Console.WriteLine("time for get inition solution : " + initiail_solution.TotalSeconds); //test path content of initial feasible solution List <Pairing> initial_Paths = new List <Pairing>(); initial_Paths = IS.PathSet; Node trip = new Node(); int count = 0; int i; foreach (Pairing path in initial_Paths) { Console.WriteLine("route " + count); for (i = 0; i < path.Arcs.Count; i++) { trip = path.Arcs[i].D_Point; Console.Write(trip.ID + " -> "); } count++; } /*--BRANCH AND PRICE--*/ CSP Csp = new CSP(Network); //Csp.Build_RMP(IS); Csp.Build_RMP(IS); Csp.LinearRelaxation(); string LP_result_schedule = "C:\\Users\\Administrator\\Desktop\\LP_CYY2.txt"; //Csp.WriteCrewPaths(LP_result_schedule); Cplex masterModel = Csp.masterModel; List <INumVar> vars = Csp.DvarSet; //masterModel.WriteSolutions("D:\\Crew_Solution.txt"); masterModel.ExportModel("D:\\MP2.lp"); int j; count = 0; for (i = 0; i < vars.Count; i++) { if (masterModel.GetValue((INumVar)(vars[i])) >= 0.5) { for (j = 0; j < Csp.PathSet[i].Arcs.Count; j++) { Console.Write(Csp.PathSet[i].Arcs[j].D_Point.ID + " -> "); } //Console.WriteLine(); Console.WriteLine("route " + count++); } } for (int t = 0; t < vars.Count; t++) { masterModel.Add(masterModel.Conversion((INumVar)vars[t], NumVarType.Int)); } //masterModel.SetParam(Cplex.IntParam.VarSel, 3);//强分支 //masterModel.SetParam(Cplex.DoubleParam.EpGap, 0.05);//相对GAP masterModel.SetParam(Cplex.DoubleParam.TiLim, 1800);//求解时间1200s masterModel.Solve(); masterModel.WriteSolutions("D:\\IP_Solutions"); string IP_result_schedule = "C:\\Users\\Administrator\\Desktop\\IP_Crew_Schedule2.txt"; //Csp.WriteCrewPaths(IP_result_schedule); count = 0; for (i = 0; i < vars.Count; i++) { if (masterModel.GetValue((INumVar)(vars[i])) >= 0.5) { for (j = 0; j < Csp.PathSet[i].Arcs.Count; j++) { Console.Write(Csp.PathSet[i].Arcs[j].D_Point.ID + " -> "); } //Console.WriteLine(); Console.WriteLine("route " + count++); } } int all_covered_num = 0; count = 0; int[] trip_coverd = new int[151]; for (i = 0; i < 151; i++) { trip_coverd[i] = 0; } for (i = 0; i < vars.Count; i++) { if (masterModel.GetValue((INumVar)(vars[i])) >= 0.5) { Console.Write("route " + (++count) + ","); Console.Write(Csp.PathSet[i].Arcs.Count - 1 + "\t"); all_covered_num = all_covered_num + Csp.PathSet[i].Arcs.Count - 1; Node trip2 = new Node(); for (j = 0; j < Csp.PathSet[i].Arcs.Count; j++) { if (Csp.PathSet[i].Arcs[j].O_Point.LineID != 0) { for (int k = 0; k < 151; k++) { if (Csp.PathSet[i].Arcs[j].O_Point.LineID == (k + 1)) { trip_coverd[k]++; break; } } } } } } Console.WriteLine("all covered node num:" + all_covered_num); for (int t = 0; t < trip_coverd.Length; t++) { if (trip_coverd[t] < 1) { Console.Write("<< trip" + (t + 1) + " coverd " + trip_coverd[t] + " times " + " >> "); } } }
public static void Main (string[] args) { int nMonths = cost.Length; int nProducts = cost[0].Length; try { Cplex cplex = new Cplex(); INumVar[] produce = cplex.NumVarArray(nMonths, 0, System.Double.MaxValue); INumVar[][] use = new INumVar[nMonths][]; INumVar[][] buy = new INumVar[nMonths][]; INumVar[][] store = new INumVar[nMonths][]; for (int i = 0; i < nMonths; i++) { use[i] = cplex.NumVarArray(nProducts, 0.0, System.Double.MaxValue); buy[i] = cplex.NumVarArray(nProducts, 0.0, System.Double.MaxValue); store[i] = cplex.NumVarArray(nProducts, 0.0, 1000.0); } for (int p = 0; p < nProducts; p++) { store[nMonths-1][p].LB = 500.0; store[nMonths-1][p].UB = 500.0; } INumExpr profit = cplex.NumExpr(); for (int i = 0; i < nMonths; i++) { // Not more than 200 tons of vegetable oil can be refined cplex.AddLe(cplex.Sum(use[i][v1], use[i][v2]), 200.0); // Not more than 250 tons of non-vegetable oil can be refined cplex.AddLe(cplex.Sum(use[i][o1], use[i][o2], use[i][o3]), 250.0); // Constraints on food composition cplex.AddLe(cplex.Prod(3.0,produce[i]), cplex.Sum(cplex.Prod(8.8, use[i][v1]), cplex.Prod(6.1, use[i][v2]), cplex.Prod(2.0, use[i][o1]), cplex.Prod(4.2, use[i][o2]), cplex.Prod(5.0, use[i][o3]))); cplex.AddGe(cplex.Prod(6.0, produce[i]), cplex.Sum(cplex.Prod(8.8, use[i][v1]), cplex.Prod(6.1, use[i][v2]), cplex.Prod(2.0, use[i][o1]), cplex.Prod(4.2, use[i][o2]), cplex.Prod(5.0, use[i][o3]))); cplex.AddEq(produce[i], cplex.Sum(use[i])); // Raw oil can be stored for later use if (i == 0) { for (int p = 0; p < nProducts; p++) cplex.AddEq(cplex.Sum(500.0, buy[i][p]), cplex.Sum(use[i][p], store[i][p])); } else { for (int p = 0; p < nProducts; p++) cplex.AddEq(cplex.Sum(store[i-1][p], buy[i][p]), cplex.Sum(use[i][p], store[i][p])); } // Logical constraints: // The food cannot use more than 3 oils // (or at least two oils must not be used) cplex.AddGe(cplex.Sum(cplex.Eq(use[i][v1], 0), cplex.Eq(use[i][v2], 0), cplex.Eq(use[i][o1], 0), cplex.Eq(use[i][o2], 0), cplex.Eq(use[i][o3], 0)), 2); // When an oil is used, the quantity must be at least 20 tons for (int p = 0; p < nProducts; p++) cplex.Add(cplex.Or(cplex.Eq(use[i][p], 0), cplex.Ge(use[i][p], 20))); // If products v1 or v2 are used, then product o3 is also used cplex.Add(cplex.IfThen(cplex.Or(cplex.Ge(use[i][v1], 20), cplex.Ge(use[i][v2], 20)), cplex.Ge(use[i][o3], 20))); // Objective function profit = cplex.Sum (profit, cplex.Prod(150, produce[i])); profit = cplex.Diff(profit, cplex.ScalProd(cost[i], buy[i])); profit = cplex.Diff(profit, cplex.Prod(5, cplex.Sum(store[i]))); } cplex.AddMaximize(profit); if ( cplex.Solve() ) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine(" Maximum profit = " + cplex.ObjValue); for (int i = 0; i < nMonths; i++) { System.Console.WriteLine(" Month {0}", i); System.Console.Write(" . buy "); for (int p = 0; p < nProducts; p++) System.Console.Write("{0,8:F2} ", cplex.GetValue(buy[i][p])); System.Console.WriteLine(); System.Console.Write(" . use "); for (int p = 0; p < nProducts; p++) System.Console.Write("{0,8:F2} ", cplex.GetValue(use[i][p])); System.Console.WriteLine(); System.Console.Write(" . store "); for (int p = 0; p < nProducts; p++) System.Console.Write("{0,8:F2} ", cplex.GetValue(store[i][p])); System.Console.WriteLine(); } } cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception caught: " + e); } }
public static void Main(string[] args) { int nMonths = cost.Length; int nProducts = cost[0].Length; try { Cplex cplex = new Cplex(); INumVar[] produce = cplex.NumVarArray(nMonths, 0, System.Double.MaxValue); INumVar[][] use = new INumVar[nMonths][]; INumVar[][] buy = new INumVar[nMonths][]; INumVar[][] store = new INumVar[nMonths][]; for (int i = 0; i < nMonths; i++) { use[i] = cplex.NumVarArray(nProducts, 0.0, System.Double.MaxValue); buy[i] = cplex.NumVarArray(nProducts, 0.0, System.Double.MaxValue); store[i] = cplex.NumVarArray(nProducts, 0.0, 1000.0); } for (int p = 0; p < nProducts; p++) { store[nMonths - 1][p].LB = 500.0; store[nMonths - 1][p].UB = 500.0; } INumExpr profit = cplex.NumExpr(); for (int i = 0; i < nMonths; i++) { // Not more than 200 tons of vegetable oil can be refined cplex.AddLe(cplex.Sum(use[i][v1], use[i][v2]), 200.0); // Not more than 250 tons of non-vegetable oil can be refined cplex.AddLe(cplex.Sum(use[i][o1], use[i][o2], use[i][o3]), 250.0); // Constraints on food composition cplex.AddLe(cplex.Prod(3.0, produce[i]), cplex.Sum(cplex.Prod(8.8, use[i][v1]), cplex.Prod(6.1, use[i][v2]), cplex.Prod(2.0, use[i][o1]), cplex.Prod(4.2, use[i][o2]), cplex.Prod(5.0, use[i][o3]))); cplex.AddGe(cplex.Prod(6.0, produce[i]), cplex.Sum(cplex.Prod(8.8, use[i][v1]), cplex.Prod(6.1, use[i][v2]), cplex.Prod(2.0, use[i][o1]), cplex.Prod(4.2, use[i][o2]), cplex.Prod(5.0, use[i][o3]))); cplex.AddEq(produce[i], cplex.Sum(use[i])); // Raw oil can be stored for later use if (i == 0) { for (int p = 0; p < nProducts; p++) { cplex.AddEq(cplex.Sum(500.0, buy[i][p]), cplex.Sum(use[i][p], store[i][p])); } } else { for (int p = 0; p < nProducts; p++) { cplex.AddEq(cplex.Sum(store[i - 1][p], buy[i][p]), cplex.Sum(use[i][p], store[i][p])); } } // Logical constraints: // The food cannot use more than 3 oils // (or at least two oils must not be used) cplex.AddGe(cplex.Sum(cplex.Eq(use[i][v1], 0), cplex.Eq(use[i][v2], 0), cplex.Eq(use[i][o1], 0), cplex.Eq(use[i][o2], 0), cplex.Eq(use[i][o3], 0)), 2); // When an oil is used, the quantity must be at least 20 tons for (int p = 0; p < nProducts; p++) { cplex.Add(cplex.Or(cplex.Eq(use[i][p], 0), cplex.Ge(use[i][p], 20))); } // If products v1 or v2 are used, then product o3 is also used cplex.Add(cplex.IfThen(cplex.Or(cplex.Ge(use[i][v1], 20), cplex.Ge(use[i][v2], 20)), cplex.Ge(use[i][o3], 20))); // Objective function profit = cplex.Sum(profit, cplex.Prod(150, produce[i])); profit = cplex.Diff(profit, cplex.ScalProd(cost[i], buy[i])); profit = cplex.Diff(profit, cplex.Prod(5, cplex.Sum(store[i]))); } cplex.AddMaximize(profit); if (cplex.Solve()) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine(" Maximum profit = " + cplex.ObjValue); for (int i = 0; i < nMonths; i++) { System.Console.WriteLine(" Month {0}", i); System.Console.Write(" . buy "); for (int p = 0; p < nProducts; p++) { System.Console.Write("{0,8:F2} ", cplex.GetValue(buy[i][p])); } System.Console.WriteLine(); System.Console.Write(" . use "); for (int p = 0; p < nProducts; p++) { System.Console.Write("{0,8:F2} ", cplex.GetValue(use[i][p])); } System.Console.WriteLine(); System.Console.Write(" . store "); for (int p = 0; p < nProducts; p++) { System.Console.Write("{0,8:F2} ", cplex.GetValue(store[i][p])); } System.Console.WriteLine(); } } cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception caught: " + e); } }
// 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); } } } } }
static int Main(string[] args) { int status = 127; try { OplFactory.DebugMode = true; OplFactory oplF = new OplFactory(); OplErrorHandler errHandler = oplF.CreateOplErrorHandler(); OplSettings settings = oplF.CreateOplSettings(errHandler); Cplex masterCplex = oplF.CreateCplex(); masterCplex.SetOut(null); OplErrorHandler errorHandler = oplF.CreateOplErrorHandler(); OplRunConfiguration masterRC = oplF.CreateOplRunConfiguration(DATADIR + "/cutstock_change.mod", DATADIR + "/cutstock_change.dat"); masterRC.ErrorHandler = errorHandler; masterRC.Cplex = masterCplex; OplModel masterOpl = masterRC.OplModel; masterOpl.Generate(); OplDataElements masterDataElements = masterOpl.MakeDataElements(); OplModelSource subSource = oplF.CreateOplModelSource(DATADIR + "/cutstock-sub.mod"); OplModelDefinition subDef = oplF.CreateOplModelDefinition(subSource, settings); Cplex subCplex = oplF.CreateCplex(); subCplex.SetOut(null); int nWdth = masterDataElements.GetElement("Amount").AsIntMap().Size; ArrayList masterVars = new ArrayList(); INumVarMap cuts = masterOpl.GetElement("Cut").AsNumVarMap(); for (int i = 1; i <= nWdth; i++) { masterVars.Add(cuts.Get(i)); } double best; double curr = double.MaxValue; do { best = curr; // Make master model Console.Out.WriteLine("Solve master."); if (masterCplex.Solve()) { curr = masterCplex.ObjValue; Console.Out.WriteLine("OBJECTIVE: " + curr); status = 0; } else { Console.Out.WriteLine("No solution!"); status = 1; } // set sub model data OplDataElements subDataElements = oplF.CreateOplDataElements(); subDataElements.AddElement(masterDataElements.GetElement("RollWidth")); subDataElements.AddElement(masterDataElements.GetElement("Size")); subDataElements.AddElement(masterDataElements.GetElement("Duals")); // get reduced costs and set them in sub problem INumMap duals = subDataElements.GetElement("Duals").AsNumMap(); for (int i = 1; i <= nWdth; i++) { IForAllRange forAll = (IForAllRange)masterOpl.GetElement("ctFill").AsConstraintMap().Get(i); duals.Set(i, masterCplex.GetDual(forAll)); } // make sub model OplModel subOpl = oplF.CreateOplModel(subDef, subCplex); subOpl.AddDataSource(subDataElements); subOpl.Generate(); Console.Out.WriteLine("Solve sub."); if (subCplex.Solve()) { Console.Out.WriteLine("OBJECTIVE: " + subCplex.ObjValue); status = 0; } else { Console.Out.WriteLine("No solution!"); status = 1; } if (subCplex.ObjValue > -RC_EPS) { break; } ; // Add variable in master model INumVar newVar = masterCplex.NumVar(0, double.MaxValue); IObjective masterObj = masterOpl.Objective; masterCplex.SetLinearCoef(masterObj, newVar, 1); for (int i = 1; i <= nWdth; i++) { double coef = subCplex.GetValue(subOpl.GetElement("Use").AsIntVarMap().Get(i)); IForAllRange forAll = (IForAllRange)masterOpl.GetElement("ctFill").AsConstraintMap().Get(i); masterCplex.SetLinearCoef(forAll, newVar, coef); } masterVars.Add(newVar); subOpl.End(); } while (best != curr && status == 0); INumVar[] masterVarsA = (INumVar[])masterVars.ToArray(typeof(INumVar)); masterCplex.Add(masterCplex.Conversion(masterVarsA, NumVarType.Int)); if (masterCplex.Solve()) { Console.Out.WriteLine("OBJECTIVE: " + masterCplex.ObjValue); } oplF.End(); } catch (ILOG.OPL.OplException ex) { Console.WriteLine(ex.Message); status = 2; } catch (ILOG.Concert.Exception ex) { Console.WriteLine(ex.Message); status = 3; } catch (System.Exception ex) { Console.WriteLine(ex.Message); status = 4; } Console.WriteLine("--Press <Enter> to exit--"); Console.ReadLine(); return(status); }
static void Main(string[] args) { try { string filename = "../../../../examples/data/etsp.dat"; if ( args.Length > 0) filename = args[0]; Data data = new Data(filename); Cplex cplex = new Cplex(); // Create start variables INumVar[][] s = new INumVar[data.nJobs][]; for (int j = 0; j < data.nJobs; j++) s[j] = cplex.NumVarArray(data.nResources, 0.0, Horizon); // State precedence constraints for (int j = 0; j < data.nJobs; j++) { for (int i = 1; i < data.nResources; i++) cplex.AddGe(s[j][i], cplex.Sum(s[j][i-1], data.duration[j][i-1])); } // State disjunctive constraints for each resource for (int i = 0; i < data.nResources; i++) { int end = data.nJobs - 1; for (int j = 0; j < end; j++) { int a = data.activityOnResource[i][j]; for (int k = j + 1; k < data.nJobs; k++) { int b = data.activityOnResource[i][k]; cplex.Add(cplex.Or( cplex.Ge(s[j][a], cplex.Sum(s[k][b], data.duration[k][b])), cplex.Ge(s[k][b], cplex.Sum(s[j][a], data.duration[j][a])) )); } } } // The cost is the sum of earliness or tardiness costs of each job int last = data.nResources - 1; INumExpr costSum = cplex.NumExpr(); for (int j = 0; j < data.nJobs; j++) { double[] points = { data.dueDate[j] }; double[] slopes = { -data.earlinessCost[j], data.tardinessCost[j] }; costSum = cplex.Sum(costSum, cplex.PiecewiseLinear( cplex.Sum(s[j][last], data.duration[j][last]), points, slopes, data.dueDate[j], 0) ); } cplex.AddMinimize(costSum); cplex.SetParam(Cplex.Param.Emphasis.MIP, 4); if ( cplex.Solve() ) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine(" Optimal Value = " + cplex.ObjValue); } cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception caught: " + e); } catch (InputDataReader.InputDataReaderException ex) { System.Console.WriteLine("Data Error: " + ex); } catch (System.IO.IOException ex) { System.Console.WriteLine("IO Error: " + ex); } }
static void Main(string[] args) { try { string filename = "../../../../examples/data/etsp.dat"; if (args.Length > 0) { filename = args[0]; } Data data = new Data(filename); Cplex cplex = new Cplex(); // Create start variables INumVar[][] s = new INumVar[data.nJobs][]; for (int j = 0; j < data.nJobs; j++) { s[j] = cplex.NumVarArray(data.nResources, 0.0, Horizon); } // State precedence constraints for (int j = 0; j < data.nJobs; j++) { for (int i = 1; i < data.nResources; i++) { cplex.AddGe(s[j][i], cplex.Sum(s[j][i - 1], data.duration[j][i - 1])); } } // State disjunctive constraints for each resource for (int i = 0; i < data.nResources; i++) { int end = data.nJobs - 1; for (int j = 0; j < end; j++) { int a = data.activityOnResource[i][j]; for (int k = j + 1; k < data.nJobs; k++) { int b = data.activityOnResource[i][k]; cplex.Add(cplex.Or( cplex.Ge(s[j][a], cplex.Sum(s[k][b], data.duration[k][b])), cplex.Ge(s[k][b], cplex.Sum(s[j][a], data.duration[j][a])) )); } } } // The cost is the sum of earliness or tardiness costs of each job int last = data.nResources - 1; INumExpr costSum = cplex.NumExpr(); for (int j = 0; j < data.nJobs; j++) { double[] points = { data.dueDate[j] }; double[] slopes = { -data.earlinessCost[j], data.tardinessCost[j] }; costSum = cplex.Sum(costSum, cplex.PiecewiseLinear( cplex.Sum(s[j][last], data.duration[j][last]), points, slopes, data.dueDate[j], 0) ); } cplex.AddMinimize(costSum); cplex.SetParam(Cplex.Param.Emphasis.MIP, 4); if (cplex.Solve()) { System.Console.WriteLine("Solution status = " + cplex.GetStatus()); System.Console.WriteLine(" Optimal Value = " + cplex.ObjValue); } cplex.End(); } catch (ILOG.Concert.Exception e) { System.Console.WriteLine("Concert exception caught: " + e); } catch (InputDataReader.InputDataReaderException ex) { System.Console.WriteLine("Data Error: " + ex); } catch (System.IO.IOException ex) { System.Console.WriteLine("IO Error: " + ex); } }
/// <summary> /// return a list of words that can be played, left over letters are the last word /// </summary> /// <param name="chips">All of the chips to conisder, first ones are on the board</param> /// <param name="numberOnBoard">The number of leading chips are on the board already</param> /// <returns></returns> public static List <Chip[]> Solve(List <Chip> chips, int numberOnBoard, bool suppress = true) { if (chips == null || chips.Count == 0) { Utility.Warning("Chips is null or empty!"); return(null); } int chip_count = chips.Count; int word_count = chip_count / 3 + 1; Cplex model = new Cplex(); IIntVar[] X = model.BoolVarArray(chip_count); // should we place the ith chip IIntVar[][] Y = new IIntVar[chip_count][]; // which word do we place the ith chip on IIntVar[] WO = model.BoolVarArray(word_count); // flag for if the jth word is an order word or not IIntVar[] WC = model.BoolVarArray(word_count); // flag for if the jth word is a color word or not IIntVar[] WN = model.BoolVarArray(word_count); // flag for if the jth word is not used or is used IIntVar[][] UO = new IIntVar[word_count][]; // what is the number associated with this word (used only if a color word) IIntVar[][] UC = new IIntVar[word_count][]; // what is the color associated with this word (used only if a order word) IIntVar[][] PC = new IIntVar[word_count][]; // if i maps to word j and j is a color word, this will be 1 at [j][i] IIntVar[][] PO = new IIntVar[word_count][]; // if i maps to word j and j is a order word, this will be 1 at [j][i] (if and only if) // Initialize for (int i = 0; i < chip_count; i++) { Y[i] = model.BoolVarArray(word_count); } for (int i = 0; i < word_count; i++) { UC[i] = model.BoolVarArray(Chip.COLORCOUNT); } for (int i = 0; i < word_count; i++) { UO[i] = model.BoolVarArray(Chip.NUMBERCOUNT); } for (int i = 0; i < word_count; i++) { PC[i] = model.BoolVarArray(chip_count); } for (int i = 0; i < word_count; i++) { PO[i] = model.BoolVarArray(chip_count); } // for each word which chips map to it IIntVar[][] Yt = new IIntVar[word_count][]; for (int i = 0; i < word_count; i++) { Yt[i] = new IIntVar[chip_count]; for (int j = 0; j < chip_count; j++) { Yt[i][j] = Y[j][i]; } } // maximize the number of placed chips model.AddMaximize(model.Sum(X)); // if we place i, we need to map it to some word for (int i = 0; i < chip_count; i++) { model.AddLe(X[i], model.Sum(Y[i])); } // we can map to at most 1 value for (int i = 0; i < chip_count; i++) { model.AddLe(model.Sum(Y[i]), 1); } // if any chip maps to word j, turn the not used flag off for (int j = 0; j < word_count; j++) { for (int i = 0; i < chip_count; i++) { model.AddLe(Y[i][j], model.Diff(1, WN[j])); } } // if a word is used, make sure it has at least 3 chips for (int j = 0; j < word_count; j++) { model.AddLe(model.Prod(3, model.Diff(1, WN[j])), model.Sum(Yt[j])); } // first 'numberOnBoard' chips are on the board and thus must be placed for (int i = 0; i < numberOnBoard; i++) { model.AddEq(X[i], 1); } // each word is either an order word or a color word for (int i = 0; i < word_count; i++) { model.AddEq(model.Sum(WO[i], WC[i], WN[i]), 1); } // if i maps to word j and j is a color word make sure PC[j][i] is 1 for (int j = 0; j < word_count; j++) { for (int i = 0; i < chip_count; i++) { model.AddGe(model.Sum(1, PC[j][i]), model.Sum(WC[j], Y[i][j])); } } // if i maps to word j and j is a order word, PO will be 1 at [j][i] (if and only if) for (int j = 0; j < word_count; j++) { for (int i = 0; i < chip_count; i++) { model.AddGe(model.Sum(1, PO[j][i]), model.Sum(WO[j], Y[i][j])); model.AddLe(PO[j][i], WO[j]); model.AddLe(PO[j][i], Y[i][j]); } } // ************************************************ // ************ TYPE CONSTRAINTS ****************** // ************************************************ for (int i = 0; i < chip_count; i++) { for (int j = 0; j < word_count; j++) { // if this is a color word and a chip maps to it then the numbers of each chip on this word must match for (int k = 0; k < Chip.NUMBERCOUNT; k++) { var bnd = model.Sum(WO[j], model.Diff(1, Y[i][j])); model.AddLe(model.Diff(UO[j][k], chips[i].number[k] ? 1 : 0), bnd); model.AddLe(model.Diff(chips[i].number[k] ? 1 : 0, UO[j][k]), bnd); } // if this is a order word and a chip maps to it then the colors of each chip on this word must match for (int k = 0; k < Chip.COLORCOUNT; k++) { var bnd = model.Sum(WC[j], model.Diff(1, Y[i][j])); model.AddLe(model.Diff(UC[j][k], chips[i].color[k] ? 1 : 0), bnd); model.AddLe(model.Diff(chips[i].color[k] ? 1 : 0, UC[j][k]), bnd); } } } // if this is a color word, ensure that at most one of each color is allowed for (int j = 0; j < word_count; j++) { for (int k = 0; k < Chip.COLORCOUNT; k++) { int[] colstack = new int[chip_count]; for (int i = 0; i < chip_count; i++) { colstack[i] = chips[i].color[k] ? 1 : 0; } model.Add(model.IfThen(model.Eq(WC[j], 1), model.Le(model.ScalProd(colstack, PC[j]), 1))); } } // ensure that the numbers in an order word are sequential for (int j = 0; j < word_count; j++) { IIntVar[] V = model.BoolVarArray(Chip.NUMBERCOUNT); for (int k = 0; k < Chip.NUMBERCOUNT; k++) { int[] numstack = new int[chip_count]; for (int i = 0; i < chip_count; i++) { numstack[i] = chips[i].number[k] ? 1 : 0; } // if this is an order word put the binary numbers into a vector of flags for those numbers model.Add(model.IfThen(model.Eq(WO[j], 1), model.Eq(model.ScalProd(numstack, PO[j]), V[k]))); } // for each number either the next flag is strictly larger, meaning the start of the sequence // or every flag after a decrease is 0, the end of a sequence for (int i = 0; i < Chip.NUMBERCOUNT - 1; i++) { IIntVar Z = model.BoolVar(); model.AddLe(model.Diff(V[i], V[i + 1]), Z); for (int k = i + 1; k < Chip.NUMBERCOUNT; k++) { model.AddLe(V[k], model.Diff(1, Z)); } } } List <Chip[]> words = new List <Chip[]>(); if (suppress) { model.SetOut(null); } Utility.Log("Thinking..."); if (model.Solve()) { for (int j = 0; j < word_count; j++) { if (model.GetValue(WN[j]) > 0.5) { continue; } List <Chip> word = new List <Chip>(); double[] flags = model.GetValues(Yt[j]); for (int i = 0; i < chip_count; i++) { if (flags[i] > 0.5) { word.Add(chips[i]); } } // if this is a color word else it is an order word if (model.GetValue(WC[j]) > 0.5) { words.Add(word.OrderBy(p => Array.IndexOf(p.color, true)).ToArray()); } else { words.Add(word.OrderBy(p => Array.IndexOf(p.number, true)).ToArray()); } } } else { Utility.Warning("No possible moves found!"); } model.Dispose(); Chip[] notplayed = chips.Where(p => !words.Any(q => q.Contains(p))).ToArray(); words.Add(notplayed); return(words); }
static void LocalBranching(Cplex cplex, Instance instance, Process process, Random rnd, Stopwatch clock) { //Define the possible value that the radius can be assume int[] possibleRadius = { 3, 5, 7, 10 }; //We start whit a radius of 3 int currentRange = 0; //Don't want print every candidate incumbent solution inside the lazy constraint callback bool BlockPrint = false; //Define the vector where is coded the incumbent solution double[] incumbentSol = new double[(instance.NNodes - 1) * instance.NNodes / 2]; //Variable where is store the cost of the incumbent solution double incumbentCost = double.MaxValue; //Create the vector conten that it will contain the last best solution find befor time limit or when it can't be improved instance.BestSol = new double[(instance.NNodes - 1) * instance.NNodes / 2]; //Build the model INumVar[] x = Utility.BuildModel(cplex, instance, -1); //List use in NearestNeightbor method List <int>[] listArray = Utility.BuildSLComplete(instance); //Create a heuristic solution PathStandard heuristicSol = Utility.NearestNeightbor(instance, rnd, listArray); //Apply 2-opt algotithm in order to improve the cost to the heuristicSol TwoOpt(instance, heuristicSol); //The heuristic solution is the incumbent, translate the encode in the format used by Cplex for (int i = 0; i < instance.NNodes; i++) { int position = Utility.xPos(i, heuristicSol.path[i], instance.NNodes); //Set to one only the edge that belong to euristic solution incumbentSol[position] = 1; } //Installation of the Lazy Constraint Callback cplex.Use(new TSPLazyConsCallback(cplex, x, instance, process, BlockPrint)); //Set the number of thread equal to the number of logical core present in the processor cplex.SetParam(Cplex.Param.Threads, cplex.GetNumCores()); //Provide to Cplex a warm start cplex.AddMIPStart(x, incumbentSol); //Create a empty expression ILinearNumExpr expr = cplex.LinearNumExpr(); //Create the firts member of the local branch constraint for (int i = 0; i < instance.NNodes; i++) { expr.AddTerm(x[Utility.xPos(i, heuristicSol.path[i], instance.NNodes)], 1); } //Create a new local branch constraint IAddable localBranchConstraint = cplex.Ge(expr, instance.NNodes - possibleRadius[currentRange]); //Add the constraint cplex.Add(localBranchConstraint); do { //Solve the model cplex.Solve(); if (incumbentCost > cplex.GetObjValue()) { incumbentCost = cplex.ObjValue; incumbentSol = cplex.GetValues(x); //Eliminate the previous local branch constraint cplex.Remove(localBranchConstraint); //Create an empty expression expr = cplex.LinearNumExpr(); StreamWriter file = new StreamWriter(instance.InputFile + ".dat", false); //Print the new incombent solution for (int i = 0; i < instance.NNodes; i++) { for (int j = i + 1; j < instance.NNodes; j++) { int position = Utility.xPos(i, j, instance.NNodes); if (incumbentSol[position] >= 0.5) { file.WriteLine(instance.Coord[i].X + " " + instance.Coord[i].Y + " " + (i + 1)); file.WriteLine(instance.Coord[j].X + " " + instance.Coord[j].Y + " " + (j + 1) + "\n"); //Create the firts member of the local branch constraint expr.AddTerm(x[position], 1); } } } Utility.PrintGNUPlot(process, instance.InputFile, 1, incumbentCost, -1); file.Close(); //Create a local branch constraint localBranchConstraint = cplex.Ge(expr, instance.NNodes - possibleRadius[currentRange]); //Add the local branch constraint cplex.Add(localBranchConstraint); } else { if (possibleRadius[currentRange] != 10) { //Increase the radius currentRange++; //Remove the previous local branch constraint cplex.Remove(localBranchConstraint); //Create the new local branch constraint localBranchConstraint = cplex.Ge(expr, instance.NNodes - possibleRadius[currentRange]); //Add the local branch constraint to the model cplex.Add(localBranchConstraint); } else { break; } } } while (clock.ElapsedMilliseconds / 1000.0 < instance.TimeLimit); //Store in the appropriate fields inside instance the last incumbent solution find and the relative cost instance.BestSol = incumbentSol; instance.BestLb = incumbentCost; }
public void LR_and_CG(ref CreateNetWork net, int lr_iter_num) { //1.initial solution LR.GenerateLRSoln(ref net, lr_iter_num); double lr_lb = LR.BestLB; double ub = 0; //2.RMP //BuildRMP(LR.SortedPathSet); //AddColumnsToRMP(LR.LB_PathSet); BuildRMP(LR.g_LB_PathSet); //double real_LB = 0; //double real_UB = 0; #region //CG progress changed 20191026 //for (; ; ) //{ // try // { // RMP.Solve(); // //Console.WriteLine(GetRMPObjValue(LR.SortedPathSet)); // RMPObjValue = RMP.GetObjValue(); // Console.WriteLine("RMPOBJ:" + RMPObjValue); // //3.get dual:v // GetDuals(); // } // catch (ILOG.Concert.Exception iloex) // { // Console.WriteLine(iloex.Message); // } // //4.renew LR multipliers u //2 way:1) u = a*v + u_best of last LR solve process // double weight = 0.05;// 0.05; // List<Line> lineList = net.LineList; // List<T_S_S_Arc> taskArcSet = LR.type_arcPair[1]; // RenewLRMultipliers(ref lineList, ref taskArcSet, weight); // real_LB = LR.BestLB; // real_UB = LR.BestUB; // foreach (var path in LR.LB_PathSet) // { // if (path.Route.Count <= 2) // { // real_LB -= path.Price; // } // } // foreach (var path in LR.SortedPathSet) // { // if (path.Route.Count <= 2) // { // real_UB -= path.Price; // } // } // Console.WriteLine("real_LB: {0} \t real_UB: {1}\n", real_LB, real_UB); // //5.gap // if (CheckTwoGAP(real_LB, real_UB, RMPObjValue) || num_iter >= 100) // { // //got best solution // break; // } // //6.LR loop,either for some short path,not all Np numbers, or all Np short path // //7.found no path with negetive reduced cost,then // //renew LR multipliers by renew weight // num_iter += 20; // LR.GenerateLRSoln(ref net, num_iter); // while (LR.SortedPathSet[0].Price >= 0 && weight < 1) // { // Console.WriteLine("!!!!"); // weight += 0.1; // RenewLRMultipliers(ref lineList, ref taskArcSet, weight); // num_iter += 20; // LR.GenerateLRSoln(ref net, num_iter); // } // if (weight >= 1) // { // //got best solution // break; // } // //8.if found path with negetive reduced cost,then // //add to RMP // AddColumnsToRMP(LR.SortedPathSet); // AddColumnsToRMP(LR.LB_PathSet); //} #endregion //求整数解 IConversion mip = RMP.Conversion(DvarSet.ToArray(), NumVarType.Int); RMP.Add(mip); RMP.Solve(); Console.WriteLine("MIP_OBJ:" + RMP.GetObjValue()); int real_crew_num = 0; //ub = calLRUB_with_and_without_penalry(net.virtualRoutingCost, ref real_crew_num); Console.WriteLine("ub:" + ub); Console.WriteLine("real crew num:" + real_crew_num); //******stop when met stop-condition LR.BestUB = ub; setOptSoln(net.LineList); sortOptSolnByASC(); getOptSolnContent(net); }