Exemple #1
0
   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");
      }
   }
Exemple #2
0
      // Branch on var with largest objective coefficient
      // among those with largest infeasibility
      public override  Cplex.Goal Execute(Cplex cplex) {
         double[] x   = GetValues  (_vars);
         double[] obj = GetObjCoefs(_vars);
         Cplex.IntegerFeasibilityStatus[] feas = GetFeasibilities(_vars);

         double maxinf = 0.0;
         double maxobj = 0.0;
         int    bestj  = -1;
         int    cols   = _vars.Length;
         for (int j = 0; j < cols; ++j) {
            if ( feas[j].Equals(Cplex.IntegerFeasibilityStatus.Infeasible) ) {
               double xj_inf = x[j] - System.Math.Floor(x[j]);
               if ( xj_inf > 0.5 )
                  xj_inf = 1.0 - xj_inf;
               if ( xj_inf >= maxinf                               &&
                    (xj_inf > maxinf || System.Math.Abs(obj[j]) >= maxobj)  ) {
                  bestj  = j;
                  maxinf = xj_inf;
                  maxobj = System.Math.Abs(obj[j]);
               }
            }
         }

         if ( bestj >= 0 ) {
            return cplex.And(
                     cplex.Or(cplex.GeGoal(_vars[bestj], System.Math.Floor(x[bestj])+1),
                              cplex.LeGoal(_vars[bestj], System.Math.Floor(x[bestj]))),
                     this);
         }
         else
            return null;
      }
Exemple #3
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);
      }
   }
Exemple #4
0
    public static void Main(string[] args)
    {
        try {
         Cplex   cplex = new Cplex();
         IRange[]  row = new IRange[3];
         INumVar[] var = populateByRow(cplex, row);

         if ( cplex.Solve() ) {
            double[] x     = cplex.GetValues(var);
            double[] slack = cplex.GetSlacks(row);

            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);

            int ncols = x.Length;
            for (int j = 0; j < ncols; ++j)
               System.Console.WriteLine("Variable   " + j +
                                        ": Value = " + x[j]);

            int nrows = slack.Length;
            for (int i = 0; i < nrows; ++i)
               System.Console.WriteLine("Constraint " + i +
                                        ": Slack = " + slack[i]);

            cplex.ExportModel("qcpex1.lp");
         }
         cplex.End();
          }
          catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception '" + e + "' caught");
          }
    }
Exemple #5
0
   public static void Main(string[] args) {
      try {
         Cplex cplex = new Cplex();
         ILPMatrix lp = PopulateByRow(cplex);

         cplex.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Dual);


         if ( cplex.Solve() ) {
            double[] x     = cplex.GetValues(lp);
            double[] slack = cplex.GetSlacks(lp);

            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);

            int nvars = x.Length;
            for (int j = 0; j < nvars; ++j) {
               System.Console.WriteLine("Variable   " + j +
                                        ": Value = " + x[j]);
            }

            int ncons = slack.Length;
            for (int i = 0; i < ncons; ++i) {
               System.Console.WriteLine("Constraint " + i +
                                        ": Slack = " + slack[i]);
            }

            cplex.ExportModel("miqpex1.lp");
         }
         cplex.End();
      }
      catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception '" + e + "' caught");
      }
   }
Exemple #6
0
    public static void Main(string[] args)
    {
        try {
         Cplex cplex = new Cplex();

         string filename = "../../../../examples/data/noswot.mps";
         if ( args.Length > 0 ) {
            filename = args[0];
            if ( filename.IndexOf("noswot") < 0 ) {
               System.Console.WriteLine("Error: noswot model is required.");
               return;
            }
         }
         cplex.ImportModel(filename);

         IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator();
         matrixEnum.MoveNext();

         ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

         cplex.Use(new Callback(MakeCuts(cplex, lp)));

         cplex.SetParam(Cplex.Param.MIP.Interval, 1000);
         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);
          }
    }
Exemple #7
0
   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");
      }
   }
Exemple #8
0
 static void Main(string[] args)
 {
     Cplex m = new Cplex();
     INumVar x1 = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "food.1");
     INumVar x2 = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "food.2");
     INumVar x3 = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "food.3");
     INumVar x4 = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "food.4");
     INumVar x5 = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "food.5");
     IObjective obj = m.AddMinimize(m.Sum(
         m.Prod(x1, 20), m.Prod(x2, 10), m.Prod(x3, 31), m.Prod(x4, 11), m.Prod(x5, 12)));
     INumExpr ironLHS = m.Sum(m.Prod(x1, 2), m.Prod(x3, 3), m.Prod(x4, 1), m.Prod(x5, 2));
     IRange con1 = m.AddGe(ironLHS, 21, "nutrient.iron");
     INumExpr calciumLHS = m.Sum(m.Prod(x2, 1), m.Prod(x3, 2), m.Prod(x4, 2), m.Prod(x5, 1));
     IRange con2 = m.AddGe(calciumLHS, 12, "nutrient.calcium");
     Console.WriteLine("**** Solver Output:\n");
     m.Solve();
     m.ExportModel("diet.lp");
     Console.WriteLine("\n**** Diet Program Output:\n");
     Console.WriteLine("Objective Value = {0}", m.GetObjValue());
     Console.WriteLine("{0} = {1}, reduced cost = {2}", x1.Name, m.GetValue(x1), m.GetReducedCost(x1));
     Console.WriteLine("{0} = {1}, reduced cost = {2}", x2.Name, m.GetValue(x2), m.GetReducedCost(x2));
     Console.WriteLine("{0} = {1}, reduced cost = {2}", x3.Name, m.GetValue(x3), m.GetReducedCost(x3));
     Console.WriteLine("{0} = {1}, reduced cost = {2}", x4.Name, m.GetValue(x4), m.GetReducedCost(x4));
     Console.WriteLine("{0} = {1}, reduced cost = {2}", x5.Name, m.GetValue(x5), m.GetReducedCost(x5));
     Console.WriteLine("{0}, slack = {1}, pi = {2}", con1.Name, m.GetSlack(con1), m.GetDual(con1));
     Console.WriteLine("{0}, slack = {1}, pi = {2}", con2.Name, m.GetSlack(con2), m.GetDual(con2));
     m.End();
 }
Exemple #9
0
    public static void Main(string[] args)
    {
        if ( args.Length != 1 ) {
         System.Console.WriteLine("Usage: Goalex1 filename");
         System.Console.WriteLine("   where filename is a file with extension ");
         System.Console.WriteLine("      MPS, SAV, or LP (lower case is allowed)");
         System.Console.WriteLine(" Exiting...");
         return;
          }

          try {
         Cplex cplex = new Cplex();

         cplex.ImportModel(args[0]);

         IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator();
         matrixEnum.MoveNext();

         ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

         cplex.SetParam(Cplex.Param.MIP.Strategy.Search, Cplex.MIPSearch.Traditional);
         if ( cplex.Solve(new MyBranchGoal(lp.NumVars)) ) {
            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);
          }
    }
Exemple #10
0
    public static void Main(string[] args)
    {
        try {
         Cplex cplex = new Cplex();
         ILPMatrix lp = PopulateByRow(cplex);

         int[]    ind = {0};
         double[] val = {1.0};

         // When a non-convex objective function is present, CPLEX
         // will raise an exception unless the parameter
         // Cplex.Param.OptimalityTarget is set to accept
         // first-order optimal solutions
         cplex.SetParam(Cplex.Param.OptimalityTarget, 2);

         // CPLEX may converge to either local optimum
         SolveAndDisplay(cplex, lp);

         // Add a constraint that cuts off the solution at (-1, 1)
         lp.AddRow(0.0, System.Double.MaxValue, ind, val);
         SolveAndDisplay(cplex, lp);

         // Remove the newly added constraint and add a new constraint
         // with the opposite sense to cut off the solution at (1, 1)
         lp.RemoveRow(lp.Nrows - 1);
         lp.AddRow(-System.Double.MaxValue, 0.0, ind, val);
         SolveAndDisplay(cplex, lp);

         cplex.ExportModel("indefqpex1.lp");
         cplex.End();
          }
          catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception '" + e + "' caught");
          }
    }
Exemple #11
0
 internal TimeLimitCallback(Cplex cplex, bool aborted, double timeStart,
                            double timeLimit, double acceptableGap) {
    _cplex         = cplex;
    _aborted       = aborted;
    _timeStart     = timeStart;
    _timeLimit     = timeLimit;
    _acceptableGap = acceptableGap;
 }
Exemple #12
0
    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);
          }
    }
Exemple #13
0
 internal static void Report3(Cplex cutSolver, 
                              System.Collections.ArrayList Cut) {
    System.Console.WriteLine();
    System.Console.WriteLine("Best integer solution uses " + 
                       cutSolver.ObjValue + " rolls");
    System.Console.WriteLine();
    for (int j = 0; j < Cut.Count; j++) 
       System.Console.WriteLine("  Cut" + j + " = " + 
                                cutSolver.GetValue((INumVar)Cut[j]));
 }
Exemple #14
0
    public static void Main(string[] args)
    {
        // Check length of command line
          if ( args.Length != 2 ) {
         Usage();
         System.Environment.Exit(-1);
          }

          // Pick up VMC from command line.
          string vmconfig = args[0];

          // Solve the model.
          Cplex cplex = null;
          try {
         // Create CPLEX solver and load model.
         cplex = new Cplex();
         cplex.ImportModel(args[1]);

         // Load the virtual machine configuration.
         // This will force Solve() to use distributed parallel MIP.
         cplex.ReadVMConfig(vmconfig);

         // Install logging info callback.
         IEnumerator e = cplex.GetLPMatrixEnumerator();
         e.MoveNext();
         ILPMatrix lp = (ILPMatrix)e.Current;
         IObjective obj = cplex.GetObjective();
         double lastObjVal =
             (obj.Sense == ObjectiveSense.Minimize ) ?
             System.Double.MaxValue : -System.Double.MaxValue;
         cplex.Use(new LogCallback(lp.NumVars, -100000, lastObjVal,
                                   cplex.GetCplexTime(), cplex.GetDetTime()));

         // Turn off CPLEX logging
         cplex.SetParam(Cplex.Param.MIP.Display, 0);

         // Solve the model and print some solution information.
         if ( cplex.Solve() )
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);
         else
            System.Console.WriteLine("No solution available");
         System.Console.WriteLine("Solution status = " + cplex.GetStatus());
          }
          catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception caught '" + e + "' caught");
         if ( cplex != null )
            cplex.End();
         System.Environment.Exit(-1);
          }
          finally {
         if ( cplex != null )
            cplex.End();
          }
    }
Exemple #15
0
    public static void Main(string[] args)
    {
        if ( args.Length != 2 ) {
         Usage();
         return;
          }
          try {
         Cplex cplex = new Cplex();

         // Evaluate command line option and set optimization method accordingly.
         switch ( args[1].ToCharArray()[0] ) {
         case 'o': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                  Cplex.Algorithm.Auto);
                   break;
         case 'p': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                  Cplex.Algorithm.Primal);
                   break;
         case 'd': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                  Cplex.Algorithm.Dual);
                   break;
         case 'b': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                  Cplex.Algorithm.Barrier);
                   cplex.SetParam(Cplex.Param.Barrier.Crossover,
                                  Cplex.Algorithm.None);
                   break;
         case 'n': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                  Cplex.Algorithm.Network);
                   break;
         default:  Usage();
                   return;
         }

         cplex.ImportModel(args[0]);

         if ( cplex.Solve() ) {
            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);

            IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator();
            matrixEnum.MoveNext();

            ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

            double[] x = cplex.GetValues(lp);
            for (int j = 0; j < x.Length; ++j) {
               System.Console.WriteLine("Variable " + j + ": Value = " + x[j]);
            }
         }
         cplex.End();
          }
          catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception caught: " + e);
          }
    }
Exemple #16
0
 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]));
    }
 }
Exemple #17
0
 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();
    }
 }
Exemple #18
0
    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");
          }
    }
Exemple #19
0
    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");
          }
    }
Exemple #20
0
    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);
          }
    }
Exemple #21
0
    public static void Main(string[] args)
    {
        try {
         Cplex    cplex = new Cplex();
         ILPMatrix lp   = PopulateByRow(cplex);

         // turn off presolve to prevent it from completely solving the model
         // before entering the actual LP optimizer
         cplex.SetParam(Cplex.Param.Preprocessing.Presolve, false);

         // turn off logging
         cplex.SetOut(null);

         // create and instruct cplex to use callback
         cplex.Use(new MyCallback());

         if ( cplex.Solve() ) {
            double[] x     = cplex.GetValues(lp);
            double[] dj    = cplex.GetReducedCosts(lp);
            double[] pi    = cplex.GetDuals(lp);
            double[] slack = cplex.GetSlacks(lp);

            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Iterations      = " + cplex.Niterations);
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);

            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 e) {
         System.Console.WriteLine("Concert exception '" + e + "' caught");
          }
    }
Exemple #22
0
 internal static void Report1(Cplex cutSolver,
                              System.Collections.ArrayList Cut,
                              IRange[] Fill) {
    System.Console.WriteLine();
    System.Console.WriteLine("Using " + cutSolver.ObjValue + " rolls");
  
    System.Console.WriteLine();
    for (int j = 0; j < Cut.Count; j++) {
       System.Console.WriteLine("  Cut" + j + " = " +
                                cutSolver.GetValue((INumVar)Cut[j]));
    }
    System.Console.WriteLine();
    
    for (int i = 0; i < Fill.Length; i++) 
       System.Console.WriteLine("  Fill" + i + " = " + 
                                cutSolver.GetDual(Fill[i]));
    System.Console.WriteLine();
 }
Exemple #23
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");
          }
    }
Exemple #24
0
    public static void Main(string[] args)
    {
        if ( args.Length != 1 ) {
         System.Console.WriteLine("Usage: AdMIPex1 filename");
         System.Console.WriteLine("   where filename is a file with extension ");
         System.Console.WriteLine("      MPS, SAV, or LP (lower case is allowed)");
         System.Console.WriteLine(" Exiting...");
         System.Environment.Exit(-1);
          }

          try {
         Cplex cplex = new Cplex();

         cplex.ImportModel(args[0]);

         if ( cplex.NSOS1 > 0 ) {
            ISOS1[] sos1 = new ISOS1[cplex.NSOS1];
            int i = 0;
            for (IEnumerator sosenum = cplex.GetSOS1Enumerator();
                 sosenum.MoveNext(); ++i) {
               sos1[i] = (ISOS1)sosenum.Current;
            }
            cplex.Use(new SOSbranch(sos1));
            System.Console.WriteLine("using SOS branch callback for " +
                                     sos1.Length + " SOS1s");
         }

         cplex.SetParam(Cplex.Param.MIP.Strategy.Search, Cplex.MIPSearch.Traditional);
         if (cplex.Solve()) {
            IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator();
            matrixEnum.MoveNext();

            ILPMatrix matrix = (ILPMatrix)matrixEnum.Current;
            double[] vals = cplex.GetValues(matrix);

            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);
         }
         cplex.End();
          }
          catch (ILOG.Concert.Exception exc) {
         System.Console.WriteLine("Concert exception caught: " + exc);
          }
    }
Exemple #25
0
    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);
          }
    }
Exemple #26
0
    public static void Main( string[] args )
    {
        try {
         Cplex cplex = new Cplex();

         INumVar[] fused = cplex.BoolVarArray(_nbMachines);
         INumVar[] x     = cplex.NumVarArray(_nbMachines, 0.0, System.Double.MaxValue);

         // Objective: minimize the sum of fixed and variable costs
         cplex.AddMinimize(cplex.Sum(cplex.ScalProd(_cost, x),
                                     cplex.ScalProd(fused, _fixedCost)));

         for (int i =  0; i < _nbMachines; i++) {
            // Constraint: respect capacity constraint on machine 'i'
            cplex.AddLe(x[i], _capacity[i]);

            // Constraint: only produce product on machine 'i' if it is 'used'
            //             (to capture fixed cost of using machine 'i')
            cplex.AddLe(x[i], cplex.Prod(10000, fused[i]));
         }

         // Constraint: meet demand
         cplex.AddEq(cplex.Sum(x), _demand);

         if ( cplex.Solve() ) {
            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Obj " + cplex.ObjValue);
            double eps = cplex.GetParam(Cplex.Param.MIP.Tolerances.Integrality);
            for(int i = 0; i < _nbMachines; i++)
               if (cplex.GetValue(fused[i]) > eps)
                  System.Console.WriteLine("E" + i + " is used for " +
                                     cplex.GetValue(x[i]));

            System.Console.WriteLine();
            System.Console.WriteLine("----------------------------------------");
         }
         cplex.End();
          }
          catch (ILOG.Concert.Exception exc) {
         System.Console.WriteLine("Concert exception '" + exc + "' caught");
          }
    }
Exemple #27
0
   public static void Main(string[] args) {
      if ( args.Length != 1 ) {
         System.Console.WriteLine("Usage: AdMIPex2 filename");
         System.Console.WriteLine("   where filename is a file with extension ");
         System.Console.WriteLine("      MPS, SAV, or LP (lower case is allowed)");
         System.Console.WriteLine(" Exiting...");
         System.Environment.Exit(-1);
      }
    
      try {
         Cplex cplex = new Cplex();
       
         cplex.ImportModel(args[0]);

         // Check model is all binary except for objective constant variable
         if ( cplex.NbinVars < cplex.Ncols - 1 ) {
            System.Console.WriteLine (
               "Problem contains non-binary variables, exiting.");
            System.Environment.Exit(-1);
         }


         IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator();
         matrixEnum.MoveNext();

         ILPMatrix lp = (ILPMatrix)matrixEnum.Current;
       
         cplex.Use(new RoundDown(lp.NumVars));
       
	 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);
      }
   }
Exemple #28
0
      public override  Cplex.Goal Execute(Cplex cplex) {
         if ( IsIntegerFeasible() )
            return null;
       
         int num = cut.Length;
         Cplex.Goal goal = this;
         for (int i = 0; i < num; ++i) {
	    IRange thecut = cut[i];
            if ( thecut != null ) {
               double val = GetValue(thecut.Expr);
               if ( thecut.LB > val+eps || val-eps > thecut.UB ) {
                  goal = cplex.And(cplex.GlobalCutGoal(thecut), goal);
                  cut[i] = null;
               }
            }
         }

         if ( goal == this )
            goal = cplex.And(cplex.BranchAsCplex(), goal);

         return goal;
      }
Exemple #29
0
    public static void Main(string[] args)
    {
        try {
         Cplex cplex = new Cplex();

         string filename = "../../../../examples/data/noswot.mps";
         if ( args.Length > 0 ) {
            filename = args[0];
            if ( filename.IndexOf("noswot") < 0 ) {
               System.Console.WriteLine("Error: noswot model is required.");
               return;
            }
         }
         cplex.ImportModel(filename);

         IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator();
         matrixEnum.MoveNext();

         ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

         // Use AddUserCuts when the added constraints strengthen the
         // formulation.  Use AddLazyConstraints when the added constraints
         // remove part of the feasible region.  Use AddCuts when you are
         // not certain.

         cplex.AddUserCuts(MakeCuts(cplex, lp));

         cplex.SetParam(Cplex.Param.MIP.Interval, 1000);
         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);
          }
    }
Exemple #30
0
    public static void Main(string[] args)
    {
        // Check length of command line
          if ( args.Length != 2 ) {
         Usage();
         System.Environment.Exit(-1);
          }

          // Pick up VMC from command line.
          string vmconfig = args[0];

          // Solve the model.
          Cplex cplex = null;
          try {
         // Create CPLEX solver and load model.
         cplex = new Cplex();
         cplex.ImportModel(args[1]);

         // Load the virtual machine configuration.
         // This will force Solve() to use distributed parallel MIP.
         cplex.ReadVMConfig(vmconfig);

         // Solve the model and print some solution information.
         if ( cplex.Solve() )
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);
         else
            System.Console.WriteLine("No solution available");
         System.Console.WriteLine("Solution status = " + cplex.GetStatus());
          }
          catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception caught '" + e + "' caught");
          }
          finally {
         if ( cplex != null )
            cplex.End();
          }
    }
Exemple #31
0
    public static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Usage();
            return;
        }
        try {
            Cplex cplex = new Cplex();

            string fixedfile   = null;
            string tunedfile   = null;
            int    tunemeasure = 0;
            bool   mset        = false;
            System.Collections.ArrayList tmpfilenames = new System.Collections.ArrayList();
            for (int i = 0; i < args.Length; ++i)
            {
                if (args[i][0] != '-')
                {
                    tmpfilenames.Add(args[i]);
                }
                switch (args[i][1])
                {
                case 'a':
                    tunemeasure = 1;
                    mset        = true;
                    break;

                case 'm':
                    tunemeasure = 2;
                    mset        = true;
                    break;

                case 'f':
                    fixedfile = args[++i];
                    break;

                case 'o':
                    tunedfile = args[++i];
                    break;
                }
            }

            string[] filenames = new string[tmpfilenames.Count];
            System.Console.WriteLine("Problem set:");
            for (int i = 0; i < filenames.Length; ++i)
            {
                filenames[i] = (string)tmpfilenames[i];
                System.Console.WriteLine("  " + filenames[i]);
            }

            if (mset)
            {
                cplex.SetParam(Cplex.Param.Tune.Measure, tunemeasure);
            }

            Cplex.ParameterSet paramset = null;

            if (fixedfile != null)
            {
                cplex.ReadParam(fixedfile);
                paramset = cplex.GetParameterSet();
                cplex.SetDefaults();
            }

            int tunestat = cplex.TuneParam(filenames, paramset);

            if (tunestat == Cplex.TuningStatus.Complete)
            {
                System.Console.WriteLine("Tuning complete.");
            }
            else if (tunestat == Cplex.TuningStatus.Abort)
            {
                System.Console.WriteLine("Tuning abort.");
            }
            else if (tunestat == Cplex.TuningStatus.TimeLim)
            {
                System.Console.WriteLine("Tuning time limit.");
            }
            else
            {
                System.Console.WriteLine("Tuning status unknown.");
            }

            if (tunedfile != null)
            {
                cplex.WriteParam(tunedfile);
                System.Console.WriteLine("Tuned parameters written to file '" +
                                         tunedfile + "'");
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
Exemple #32
0
        static void Main(string[] args)
        {
            // Portfolio asset daily price data:
            var assets = new[] { "A", "B", "C" };
            var prices = new double[][] {
                new double[] { .02, .03, .02, .05 },
                new double[] { .01, .01, .05, .01 },
                new double[] { .1, .05, .04, .02 },
            };
            // Pre-process data
            var covmat = CovarianceMatrix(prices);

            DisplayCovariance(covmat);
            var expReturns = AssetReturns(prices);

            DisplayReturns(assets, expReturns);
            var rho = 0.05;

            // Create LP model

            try
            {
                Cplex cplex = new Cplex();

                // Weights bounded 0 <= weight <= 1.0
                var weights = cplex.NumVarArray(assets.Length, 0, 1.0);

                // x = weights.
                // Expected (mean) return of portfolio: ∑ᵢ x[i]*assetReturn[i]
                var expRet = cplex.ScalProd(expReturns, weights);

                // Portfolio variance : xᵀ∑x (matrix form of bi-linear: ∑ᵢ∑ⱼ x[i]*x[j]*cov(i,j)
                // where ∑ is the covariance matrix m*m of m assets.
                var pvar = cplex.QuadNumExpr();
                for (int i = 0; i < assets.Length; ++i)
                {
                    for (int j = 0; j < assets.Length; ++j)
                    {
                        pvar.AddTerm(covmat[i][j], weights[i], weights[j]);
                    }
                }

                // Objective (maximize): portfolio return  - (Rho/2) * portfolio variance.
                // Where 0 <= Rho <= 1 is the desired risk tolerance.
                var obj = cplex.Diff(expRet, cplex.Prod(rho / 2, pvar));

                cplex.AddMaximize(obj);

                // Subject to:
                // Sum of weights <= 1.0
                cplex.AddEq(cplex.Sum(weights), 1.0);

                // Exports model definition to readable LP format
                cplex.ExportModel(@"c:\users\mike\cplexfin.lp");

                // Solve and print results
                if (cplex.Solve())
                {
                    var w = new double[weights.Length];
                    Console.WriteLine("\nResulting Weights:");
                    for (int i = 0; i < weights.Length; i++)
                    {
                        Console.WriteLine($"{i + 1} : {cplex.GetValue(weights[i]) * 100:0.0}%");
                        w[i] = cplex.GetValue(weights[i]);
                    }
                    var totReturn   = WeightedReturn(w, expReturns);
                    var totVariance = PortfolioVariance(w, covmat);
                    Console.WriteLine($"Total Return: {totReturn:0.00}, Total Variance: {totVariance:0.0000}");
                }

                cplex.End();
            }
            catch (ILOG.Concert.Exception e)
            {
                System.Console.WriteLine("Concert exception caught: " + e);
            }

            Console.WriteLine("Press any key to quit.");
            Console.ReadKey();
        }
Exemple #33
0
    public static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            Usage();
            return;
        }
        try {
            // Create the modeler/solver object
            Cplex cplex = new Cplex();

            // Evaluate command line option and set optimization method accordingly.
            switch (args[1].ToCharArray()[0])
            {
            case 'o': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Auto);
                break;

            case 'p': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Primal);
                break;

            case 'd': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Dual);
                break;

            case 'h': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Barrier);
                break;

            case 'b': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Barrier);
                cplex.SetParam(Cplex.Param.Barrier.Crossover,
                               Cplex.Algorithm.None);
                break;

            case 'n': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Network);
                break;

            case 's': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Sifting);
                break;

            case 'c': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Concurrent);
                break;

            default:  Usage();
                return;
            }

            // Read model from file with name args[0] into cplex optimizer object
            cplex.ImportModel(args[0]);


            // Solve the model and display the solution if one was found
            if (cplex.Solve())
            {
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine("Solution value  = " + cplex.ObjValue);

                // Access the ILPMatrix object that has been read from a file in
                // order to access variables which are the columns of the LP.  The
                // method importModel() guarantees that exactly one ILPMatrix
                // object will exist, which is why no tests or enumerators are
                // needed in the following line of code.

                IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator();
                matrixEnum.MoveNext();

                ILPMatrix lp   = (ILPMatrix)matrixEnum.Current;
                INumVar[] vars = lp.NumVars;
                double[]  vals = cplex.GetValues(vars);

                // Basis information is not available for barrier without crossover.
                // Thus we include the query in a try statement and print the solution
                // without barrier information in case we get an exception.
                try {
                    Cplex.BasisStatus[] bStat = cplex.GetBasisStatuses(vars);
                    for (int i = 0; i < vals.Length; i++)
                    {
                        System.Console.WriteLine("Variable " + vars[i].Name +
                                                 " has vals " + vals[i] +
                                                 " and status " + bStat[i]);
                    }
                }
                catch (ILOG.Concert.Exception) {
                    for (int i = 0; i < vals.Length; i++)
                    {
                        System.Console.WriteLine("Variable " + vars[i].Name +
                                                 " has vals " + vals[i]);
                    }
                }
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception exc) {
            System.Console.WriteLine("Concert exception '" + exc + "' caught");
        }
    }
Exemple #34
0
        //A quadratic interger program for graph matching,
        //When tuned with the right similarity function it can represent the GED problem.
        // See Pattern Reocgnition Paper paper On the unification of graph matching and graph edit distance paper.
        public override void QAPGMGED()
        {
            //some important variables
            int nbNode1       = graph1.ListNodes.Count;
            int nbNode2       = graph2.ListNodes.Count;
            int nbvar         = nbNode1 * nbNode2; // number of variables
            int nbcontraintes = nbNode1 + nbNode2; // number of constraints

            Graphs.Label nodeepslabel;

            //Adjacency matrices
            MatrixLibrary.Matrix adj1 = graph1.calculateAdjacencyMatrix();
            MatrixLibrary.Matrix adj2 = graph2.calculateAdjacencyMatrix();
            //Similarity matrix
            Double[,] S = new Double[nbvar, nbvar];

            //Creation of the Similarity matrix
            //4 for loops integrated
            int countrow = -1;

            for (int i = 0; i < nbNode1; i++)
            {
                Node nodei = graph1.ListNodes[i];
                for (int k = 0; k < nbNode2; k++)
                {
                    Node nodek = graph2.ListNodes[k];
                    countrow = countrow + 1;
                    int countcol = -1;
                    for (int j = 0; j < nbNode1; j++)
                    {
                        Node nodej = graph1.ListNodes[j];
                        for (int l = 0; l < nbNode2; l++)
                        {
                            Node nodel = graph2.ListNodes[l];
                            countcol = countcol + 1;
                            if (i == j && k == l) // Similarity between nodes
                            {
                                Type   typeLabel = nodei.Label.GetType();
                                object obj       = Activator.CreateInstance(typeLabel);
                                nodeepslabel    = (Graphs.Label)obj;
                                nodeepslabel.Id = ConstantsAC.EPS_ID;

                                double costsub = nodei.Label.dissimilarity(nodek.Label);
                                double costdel = nodei.Label.dissimilarity(nodeepslabel);
                                double costins = nodeepslabel.dissimilarity(nodek.Label);
                                double cost    = costsub - costdel - costins;
                                cost *= -1;

                                S[countrow, countcol] = cost;
                            }
                            else // Similarity between edges
                            {
                                int connect1 = (int)adj1[i, j];
                                int connect2 = (int)adj2[k, l];
                                if (connect1 == 1 && connect2 == 1) // Two edges are connected
                                {
                                    Edge ij = findedge(nodei, nodej);
                                    Edge kl = findedge(nodek, nodel);


                                    Type   typeLabel = ij.Label.GetType();
                                    object obj       = Activator.CreateInstance(typeLabel);
                                    nodeepslabel    = (Graphs.Label)obj;
                                    nodeepslabel.Id = ConstantsAC.EPS_ID;

                                    double costsub = ij.Label.dissimilarity(kl.Label);
                                    double costdel = ij.Label.dissimilarity(nodeepslabel);
                                    double costins = nodeepslabel.dissimilarity(kl.Label);
                                    double cost    = costsub - costdel - costins;
                                    cost *= -1;
                                    cost *= 0.5;
                                    S[countrow, countcol] = cost;
                                }
                            }
                        }
                    }
                }
            }


            //We compute the constant that represents the
            //deletion and insertion of the nodes and edges

            //deletions of the nodes of g1
            double constante = 0;

            for (int i = 1; i <= nbNode1; i++)
            {
                Type   typeLabel = graph1.ListNodes[i - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;
                constante      += (graph1.ListNodes[i - 1].Label).dissimilarity(nodeepslabel);
            }

            //deletions of the edges of g1
            for (int ij = 1; ij <= nbEdge1; ij++)
            {
                Type   typeLabel = graph1.ListEdges[ij - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;
                double costEdge = (graph1.ListEdges[ij - 1].Label).dissimilarity(nodeepslabel);
                constante += costEdge;
            }

            //insertions of the nodes of g2
            for (int k = 1; k <= nbNode2; k++)
            {
                Type   typeLabel = graph2.ListNodes[k - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;
                constante      += (graph2.ListNodes[k - 1].Label).dissimilarity(nodeepslabel);
            }

            //insertions of the edges of g2
            for (int kl = 1; kl <= nbEdge2; kl++)
            {
                Type   typeLabel = graph2.ListEdges[kl - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;
                double costEdge = (graph2.ListEdges[kl - 1].Label).dissimilarity(nodeepslabel);
                constante += costEdge;
            }

            // the number of variables is the number of columns
            int nbCols = nbvar;
            // the number of constraints is the number of rows
            int           nbRows      = nbcontraintes;
            List <string> colNameList = new List <string>();


            //We create the name of the vrariables for all couples of nodes in g1 and g2
            for (int i = 0; i < nbNode1; i++)
            {
                for (int k = 0; k < nbNode2; k++)
                {
                    colNameList.Add("x_" + graph1.ListNodes[i].Id + "," + graph2.ListNodes[k].Id + "");
                }
            }
            try
            {
                cplex = new Cplex();                                         // creation du modèle CPLEX

                this.ilpMatrix = cplex.AddLPMatrix();                        // matrice du pb (initialisée à 0 colonnes et 0 lignes)

                ColumnArray colonnes = cplex.ColumnArray(ilpMatrix, nbCols); // définition des variables-colonnes du pb

                // ajout des variables-colonnes dans la matrice du pb
                // y is a vector
                INumVar[] y = cplex.NumVarArray(colonnes, 0, 1, NumVarType.Bool, colNameList.ToArray());


                #region création fonction objectif

                // CALCUL DES COEFFICIENTS
                // We create the ojective function
                INumExpr[] coeffs_expr = new INumExpr[nbvar * nbvar]; // vecteur des coeffs des coûts des arrêtes

                int count = 0;
                for (int ik = 0; ik < nbvar; ik++)
                {
                    for (int jl = 0; jl < nbvar; jl++)
                    {
                        coeffs_expr[count] = cplex.Prod(y[ik], y[jl]);
                        coeffs_expr[count] = cplex.Prod(S[ik, jl], coeffs_expr[count]);
                        count = count + 1;
                    }
                }
                INumExpr ff = cplex.Sum(coeffs_expr);
                INumExpr gg = cplex.Sum(ff, cplex.Constant(-constante));
                cplex.AddMaximize(gg);
                #endregion


                #region définition des contraintes du pb

                // We create the constraints

                // The sum of x variables by rows

                for (int i = 0; i < nbNode1; i++)
                {
                    INumVar[] sommeLignes = new INumVar[nbNode2];
                    for (int k = 0; k < nbNode2; k++)
                    {
                        string nameVarik = "x_" + i + "," + k;
                        int    indexik   = SolverCPLEX.GetIndexByName(y, nameVarik);
                        sommeLignes[k] = y[indexik];
                    }
                    cplex.AddLe(cplex.Sum(sommeLignes), 1);
                }

                // The sum of x variables by columns
                for (int k = 0; k < nbNode2; k++)
                {
                    INumVar[] sommeLignes = new INumVar[nbNode1];
                    for (int i = 0; i < nbNode1; i++)
                    {
                        string nameVarik = "x_" + i + "," + k;
                        int    indexik   = SolverCPLEX.GetIndexByName(y, nameVarik);
                        sommeLignes[i] = y[indexik];
                    }
                    cplex.AddLe(cplex.Sum(sommeLignes), 1);
                }



                #endregion
            }
            catch (ILOG.Concert.Exception e)
            {
                System.Console.WriteLine("Concert exception `" + e + "` caught");
            }
        }
Exemple #35
0
    /* ***************************************************************** *
    *                                                                   *
    *    C A L C U L A T E   D U A L S   F O R   Q U A D S              *
    *                                                                   *
    *   CPLEX does not give us the dual multipliers for quadratic       *
    *   constraints directly. This is because they may not be properly  *
    *   defined at the cone top and deciding whether we are at the cone *
    *   top or not involves (problem specific) tolerance issues. CPLEX  *
    *   instead gives us all the values we need in order to compute the *
    *   dual multipliers if we are not at the cone top.                 *
    *                                                                   *
    * ***************************************************************** */
    /// <summary>
    /// Calculate dual multipliers for quadratic constraints from dual
    /// slack vectors and optimal solutions.
    /// The dual multiplier is essentially the dual slack divided
    /// by the derivative evaluated at the optimal solution. If the optimal
    /// solution is 0 then the derivative at this point is not defined (we are
    /// at the cone top) and we cannot compute a dual multiplier.
    /// </summary>
    /// <remarks>
    ///   <c>cplex</c> is the Cplex instance that holds the optimal
    ///                solution.
    ///   <c>xval</c>  is the optimal solution vector.
    ///   <c>tol</c>   is the tolerance used to decide whether we are at
    ///                the cone
    ///   <c>x</c>     is the array of variables in the model.
    ///   <c>qs</c>    is the array of quadratic constraints for which duals
    ///                shall be calculated.
    /// </remarks>
    private static double[] getqconstrmultipliers(Cplex cplex, double[] xval, double tol, INumVar[] x, IRange[] qs)
    {
        double[] qpi = new double[qs.Length];
        // Store solution in map so that we can look up by variable.
        IDictionary <INumVar, System.Double> sol = new Dictionary <INumVar, System.Double>();

        for (int j = 0; j < x.Length; ++j)
        {
            sol.Add(x[j], xval[j]);
        }

        for (int i = 0; i < qs.Length; ++i)
        {
            IDictionary <INumVar, System.Double> dslack = new Dictionary <INumVar, System.Double>();
            for (ILinearNumExprEnumerator it = cplex.GetQCDSlack(qs[i]).GetLinearEnumerator(); it.MoveNext(); /* nothing */)
            {
                dslack[it.NumVar] = it.Value;
            }

            IDictionary <INumVar, System.Double> grad = new Dictionary <INumVar, System.Double>();
            bool conetop = true;
            for (IQuadNumExprEnumerator it = ((ILQNumExpr)qs[i].Expr).GetQuadEnumerator();
                 it.MoveNext(); /* nothing */)
            {
                INumVar x1 = it.NumVar1;
                INumVar x2 = it.NumVar2;
                if (sol[x1] > tol || sol[x2] > tol)
                {
                    conetop = false;
                }
                System.Double old;
                if (!grad.TryGetValue(x1, out old))
                {
                    old = 0.0;
                }
                grad[x1] = old + sol[x2] * it.Value;
                if (!grad.TryGetValue(x2, out old))
                {
                    old = 0.0;
                }
                grad[x2] = old + sol[x1] * it.Value;
            }
            if (conetop)
            {
                throw new System.SystemException("Cannot compute dual multiplier at cone top!");
            }

            // Compute qpi[i] as slack/gradient.
            // We may have several indices to choose from and use the one
            // with largest absolute value in the denominator.
            bool   ok     = false;
            double maxabs = -1.0;
            foreach (INumVar v in x)
            {
                System.Double g;
                if (grad.TryGetValue(v, out g))
                {
                    if (System.Math.Abs(g) > tol)
                    {
                        if (System.Math.Abs(g) > maxabs)
                        {
                            System.Double d;
                            qpi[i] = (dslack.TryGetValue(v, out d) ? d : 0.0) / g;
                            maxabs = System.Math.Abs(g);
                        }
                        ok = true;
                    }
                }
            }
            if (!ok)
            {
                // Dual slack is all 0. qpi[i] can be anything, just set to 0.
                qpi[i] = 0;
            }
        }
        return(qpi);
    }
Exemple #36
0
        //F2 version with constant and slack variables
        ////Formlation F2 for the GED problem. Very efficient.
        // https://hal.archives-ouvertes.fr/hal-01619313

        public override void IsoGraphInexactF2b()
        {
            int mincst = Math.Min((nbNode2 * nbEdge1), (nbNode1 * nbEdge2));

            this.nbRows = nbNode1 + nbNode2 + 1 * mincst;        //ns +ms+ng+mg+4ngms +4nsmg /contrainte
            this.nbCols = nbNode1 * nbNode2 + nbEdge1 * nbEdge2; //nsng+msmg+ns+ms+ng+mg //variable

            Graphs.Label nodeepslabel;

            #region objectFunction
            List <double> objList     = new List <double>();
            List <string> colNameList = new List <string>();
            List <char>   typeList    = new List <char>();
            List <Double> ubList      = new List <Double>();
            //the objetive funcion

            //variable x
            for (int i = 1; i <= nbNode1; i++)
            {
                for (int k = 1; k <= nbNode2; k++)
                {
                    Type   typeLabel = graph1.ListNodes[i - 1].Label.GetType();
                    object obj       = Activator.CreateInstance(typeLabel);
                    nodeepslabel    = (Graphs.Label)obj;
                    nodeepslabel.Id = ConstantsAC.EPS_ID;

                    double costsub = graph1.ListNodes[i - 1].Label.dissimilarity(graph2.ListNodes[k - 1].Label);
                    double costdel = graph1.ListNodes[i - 1].Label.dissimilarity(nodeepslabel);
                    double costins = nodeepslabel.dissimilarity(graph2.ListNodes[k - 1].Label);
                    double cost    = costsub - costdel - costins;
                    objList.Add(cost);
                    colNameList.Add("x_" + graph1.ListNodes[i - 1].Id + "," + graph2.ListNodes[k - 1].Id);
                }
            }

            //variable y
            for (int ij = 1; ij <= nbEdge1; ij++)
            {
                for (int kl = 1; kl <= nbEdge2; kl++)
                {
                    Type   typeLabel = graph1.ListEdges[ij - 1].Label.GetType();
                    object obj       = Activator.CreateInstance(typeLabel);
                    nodeepslabel    = (Graphs.Label)obj;
                    nodeepslabel.Id = ConstantsAC.EPS_ID;

                    double costsub = graph1.ListEdges[ij - 1].Label.dissimilarity(graph2.ListEdges[kl - 1].Label);
                    double costdel = graph1.ListEdges[ij - 1].Label.dissimilarity(nodeepslabel);
                    double costins = nodeepslabel.dissimilarity(graph2.ListEdges[kl - 1].Label);
                    double cost    = costsub - costdel - costins;
                    objList.Add(cost);

                    colNameList.Add("y_" + graph1.ListEdges[ij - 1].Id + "," + graph2.ListEdges[kl - 1].Id);
                }
            }
            double constante = 0;
            for (int i = 1; i <= nbNode1; i++)
            {
                Type   typeLabel = graph1.ListNodes[i - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;
                constante      += (graph1.ListNodes[i - 1].Label).dissimilarity(nodeepslabel);
            }

            for (int ij = 1; ij <= nbEdge1; ij++)
            {
                Type   typeLabel = graph1.ListEdges[ij - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;
                double costEdge = (graph1.ListEdges[ij - 1].Label).dissimilarity(nodeepslabel);
                constante += costEdge;
            }

            for (int k = 1; k <= nbNode2; k++)
            {
                Type   typeLabel = graph2.ListNodes[k - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;
                constante      += (graph2.ListNodes[k - 1].Label).dissimilarity(nodeepslabel);
                // colNameList.Add("v_Del_" + graph2.ListNodes[k - 1].Id + "," + graph2.ListNodes[k - 1].Id);
            }

            for (int kl = 1; kl <= nbEdge2; kl++)
            {
                Type   typeLabel = graph2.ListEdges[kl - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;
                double costEdge = (graph2.ListEdges[kl - 1].Label).dissimilarity(nodeepslabel);
                constante += costEdge;

                //colNameList.Add("f_Del_" + graph2.ListEdges[kl - 1].Id + "," + graph2.ListEdges[kl - 1].Id);
            }
            #endregion

            try
            {
                cplex     = new Cplex();
                ilpMatrix = cplex.AddLPMatrix();

                // add empty corresponding to new variables columns to ilpMatrix
                INumVar[] x = cplex.NumVarArray(cplex.ColumnArray(ilpMatrix, nbCols), 0, 1, NumVarType.Bool, colNameList.ToArray());

                List <Double> lbMatrixList = new List <Double>();
                List <Double> ubMatrixList = new List <Double>();
                Int32[][]     indiceH      = new Int32[nbRows][];
                Double[][]    valeurH      = new Double[nbRows][];
                List <Int32>  jaList; //les indice des valeurs
                List <Double> arList; //les valeurs non zeros dans la ligne

                int rownum = 0;
                #region construire constraintes
                //18.B
                for (int i = 0; i < nbNode1; i++)
                {
                    jaList = new List <int>();
                    arList = new List <Double>();
                    lbMatrixList.Add(0.0);
                    ubMatrixList.Add(1.0);

                    for (int k = 0; k < nbNode2; k++)
                    {
                        jaList.Add(i * nbNode2 + k);
                        arList.Add(1);
                    }
                    indiceH[rownum] = jaList.ToArray();
                    valeurH[rownum] = arList.ToArray();
                    rownum++;
                }


                // contraint: equation [Fb.1]-4
                //18.c
                for (int k = 0; k < nbNode2; k++)
                {
                    jaList = new List <int>();
                    arList = new List <Double>();
                    lbMatrixList.Add(0.0);
                    ubMatrixList.Add(1.0);
                    for (int i = 0; i < nbNode1; i++)
                    {
                        jaList.Add(i * nbNode2 + k);
                        arList.Add(1);
                    }

                    indiceH[rownum] = jaList.ToArray();
                    valeurH[rownum] = arList.ToArray();
                    rownum++;
                }



                if (nbNode2 * nbEdge1 < nbNode1 * nbEdge2)
                {
                    //6 If two vertices are matched together,
                    //an edge originating one of these two vertices must be matched with an edge originating the other vertex)
                    //18.F
                    for (int k = 0; k < nbNode2; k++)
                    {
                        for (int ij = 0; ij < nbEdge1; ij++)
                        {
                            jaList = new List <int>();    //les indice des valeurs
                            arList = new List <Double>(); //les valeurs non zeros dans la ligne
                            lbMatrixList.Add(0.0);
                            ubMatrixList.Add(1.0);


                            string sourcei   = graph1.ListEdges[ij].NodeSource.Id;
                            string nameVarik = "x_" + sourcei + "," + graph2.ListNodes[k].Id;
                            int    colIndxik = SolverCPLEX.GetIndexByName(x, nameVarik);
                            if (colIndxik == -1)
                            {
                                throw new InvalidProgramException();
                            }

                            jaList.Add(colIndxik);
                            arList.Add(1);

                            string sourcej    = graph1.ListEdges[ij].NodeTarget.Id;
                            string nameVarxjk = "x_" + sourcej + "," + graph2.ListNodes[k].Id;
                            int    colIndxjk  = SolverCPLEX.GetIndexByName(x, nameVarxjk);
                            if (colIndxjk == -1)
                            {
                                throw new InvalidProgramException();
                            }

                            jaList.Add(colIndxjk);
                            arList.Add(1);

                            string name1 = graph1.ListEdges[ij].Id;
                            foreach (Edge e in graph2.ListNodes[k].ListEdgesOut)
                            {
                                string name2   = e.Id;
                                string nameVar = "y_" + name1 + "," + name2;
                                int    colInd  = SolverCPLEX.GetIndexByName(x, nameVar);
                                if (colInd == -1)
                                {
                                    throw new InvalidProgramException();
                                }
                                jaList.Add(colInd);
                                arList.Add(-1);
                            }



                            indiceH[rownum] = jaList.ToArray();
                            valeurH[rownum] = arList.ToArray();
                            rownum++;
                        }
                    }
                }
                else
                {
                    //Todo
                    for (int i = 0; i < nbNode1; i++)
                    {
                        for (int kl = 0; kl < nbEdge2; kl++)
                        {
                            jaList = new List <int>();    //les indice des valeurs
                            arList = new List <Double>(); //les valeurs non zeros dans la ligne
                            lbMatrixList.Add(0.0);
                            ubMatrixList.Add(1.0);


                            string sourcei   = graph2.ListEdges[kl].NodeSource.Id;
                            string nameVarik = "x_" + graph1.ListNodes[i].Id + "," + sourcei;
                            int    colIndxik = SolverCPLEX.GetIndexByName(x, nameVarik);
                            if (colIndxik == -1)
                            {
                                throw new InvalidProgramException();
                            }

                            jaList.Add(colIndxik);
                            arList.Add(1);

                            string sourcej    = graph2.ListEdges[kl].NodeTarget.Id;
                            string nameVarxjk = "x_" + graph1.ListNodes[i].Id + "," + sourcej;
                            int    colIndxjk  = SolverCPLEX.GetIndexByName(x, nameVarxjk);
                            if (colIndxjk == -1)
                            {
                                throw new InvalidProgramException();
                            }

                            jaList.Add(colIndxjk);
                            arList.Add(1);

                            string name1 = graph2.ListEdges[kl].Id;
                            foreach (Edge e in graph1.ListNodes[i].ListEdgesOut)
                            {
                                string name2   = e.Id;
                                string nameVar = "y_" + name2 + "," + name1;
                                int    colInd  = SolverCPLEX.GetIndexByName(x, nameVar);
                                if (colInd == -1)
                                {
                                    throw new InvalidProgramException();
                                }
                                jaList.Add(colInd);
                                arList.Add(-1);
                            }

                            indiceH[rownum] = jaList.ToArray();
                            valeurH[rownum] = arList.ToArray();
                            rownum++;
                        }
                    }
                }

                #endregion
                Int32 res = ilpMatrix.AddRows(lbMatrixList.ToArray(), ubMatrixList.ToArray(), indiceH, valeurH);

                // add the objective function
                objCoef = objList.ToArray();
                cplex.AddMinimize(cplex.Sum(cplex.Constant(constante), cplex.ScalProd(x, objCoef)));
            }
            catch (ILOG.Concert.Exception e)
            {
                System.Console.WriteLine("Concert exception '" + e + "' caught");
            }
        }
Exemple #37
0
        public override void Work()
        {
            //获取求解设置
            decimal terminalFactor = _ctx.GetParameter("TerminalFactor", 0.001m);
            int     iteration      = _ctx.GetParameter("Iteration", 10);
            int     resolution     = _ctx.GetParameter("Resolution", 60);
            decimal initMultipler  = _ctx.GetParameter("InitMultiper", 0.1m);

            string objectiveType = _ctx.GetParameter("ObjectiveType", "");

            // 相对-绝对时间转化器
            DiscreteTimeAdapter adapter
                = new DiscreteTimeAdapter(_ctx.StartTime, _ctx.EndTime, resolution);

            // 路径集
            Dictionary <CustomerArrival, List <TravelPath> > pathDict
                = new Dictionary <CustomerArrival, List <TravelPath> >();

            #region 建立初始网络,搜索可行路径
            //目标函数网络
            var objgraph = ObjectNetworkFactory.Create(objectiveType, _ctx, adapter); //new ObjectTravelHyperNetwork(_ctx, adapter);
            objgraph.Build();

            //基础网络
            var basicGraph = new BasicTravelHyperNetwork(_ctx, adapter);
            basicGraph.Build();

            SubTasks.Clear();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                Task ta = factory.StartNew(() =>
                {
                    var ori   = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                    var des   = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).DesSta;
                    var paths = DepthFirstSearcher.FindAllPaths(basicGraph,
                                                                new TravelHyperNode()
                    {
                        Time = adapter.ConvertToDiscreteTime(customer.ArriveTime), Station = ori, Price = 0
                    },
                                                                new TravelHyperNode()
                    {
                        Time = adapter.Horizon + 1440, Station = des, Price = 0
                    });
                    pathDict.Add(customer, new List <TravelPath>());
                    foreach (var path in paths)
                    {
                        pathDict[customer].Add(new TravelPath(basicGraph, path));
                    }
                });
                SubTasks.Add(ta);
            }
            Task.WaitAll(SubTasks.ToArray());
            #endregion

            #region 构建对偶问题 with CPLEX
            Cplex model = new Cplex();
            model.SetOut(null);
            INumVar theta = model.NumVar(double.MinValue, double.MaxValue); //θ

            model.AddMaximize(theta);

            Dictionary <IServiceSegment, INumVar> dual_rho = _ctx.Wor.RailwayTimeTable.Trains
                                                             .SelectMany(i => i.ServiceSegments).ToDictionary(i => i, i =>
                                                                                                              model.NumVar(0, double.MaxValue));

            Dictionary <CustomerArrival, Dictionary <TravelPath, INumVar> > dual_mu =
                new Dictionary <CustomerArrival, Dictionary <TravelPath, INumVar> >();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                dual_mu.Add(customer, new Dictionary <TravelPath, INumVar>());
                foreach (var path in pathDict[customer])
                {
                    dual_mu[customer].Add(path, model.NumVar(0, double.MaxValue));
                }
            }

            Dictionary <IEdge <TravelHyperNode>, INumVar> dual_lambda =
                new Dictionary <IEdge <TravelHyperNode>, INumVar>();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                foreach (var path in pathDict[customer])
                {
                    if (!dual_lambda.ContainsKey(path.ReservationArc))
                    {
                        dual_lambda.Add(path.ReservationArc, model.NumVar(0, double.MaxValue));
                    }
                }
            }
            #endregion

            #region 变量与乘子
            //决策变量 x
            Dictionary <CustomerArrival, TravelPath> x
                = new Dictionary <CustomerArrival, TravelPath>();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                x.Add(customer, new TravelPath());
            }

            //决策变量 w
            Dictionary <ITrainTrip, Dictionary <IRailwayStation, PricePath> > w
                = new Dictionary <ITrainTrip, Dictionary <IRailwayStation, PricePath> >();
            foreach (var train in _ctx.Wor.RailwayTimeTable.Trains)
            {
                w.Add(train, new Dictionary <IRailwayStation, PricePath>());
                foreach (var sta in _ctx.Wor.Net.StationCollection)
                {
                    w[train].Add(sta, null);
                }
            }

            //辅助变量 y
            //记录每条弧在当前w的取值下是否可行(available),值为true = 可行;false = 不可行
            //超出了y记录的reservation arc 不会有人走
            Dictionary <IEdge <TravelHyperNode>, bool> y
                = new Dictionary <IEdge <TravelHyperNode>, bool>();
            foreach (var p in pathDict.Values.SelectMany(i => i))
            {
                if (p.ReservationArc != null && !y.ContainsKey(p.ReservationArc))
                {
                    y.Add(p.ReservationArc, false);
                }
            }

            //拉格朗日乘子 rho
            Dictionary <IServiceSegment, decimal> LM_rho = _ctx.Wor.RailwayTimeTable.Trains
                                                           .SelectMany(i => i.ServiceSegments).ToDictionary(i => i, i => initMultipler);

            //拉格朗日乘子 rho 迭代方向
            Dictionary <IServiceSegment, decimal> Grad_rho = _ctx.Wor.RailwayTimeTable.Trains
                                                             .SelectMany(i => i.ServiceSegments).ToDictionary(i => i, i => initMultipler);


            //拉格朗日乘子 mu
            Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> > LM_mu
                = new Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> >();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                LM_mu.Add(customer, new Dictionary <TravelPath, decimal>());
                foreach (var path in pathDict[customer])
                {
                    LM_mu[customer].Add(path, initMultipler);
                }
            }
            //拉格朗日乘子 mu 迭代方向
            Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> > Grad_mu
                = new Dictionary <CustomerArrival, Dictionary <TravelPath, decimal> >();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                Grad_mu.Add(customer, new Dictionary <TravelPath, decimal>());
                foreach (var path in pathDict[customer])
                {
                    Grad_mu[customer].Add(path, initMultipler);
                }
            }

            //拉格朗日乘子 lambda
            Dictionary <IEdge <TravelHyperNode>, decimal> LM_lambda = new Dictionary <IEdge <TravelHyperNode>, decimal>();
            //WARNING: 这里缺少了没有旅客选择的reservation arc
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                foreach (var path in pathDict[customer])
                {
                    if (!LM_lambda.ContainsKey(path.ReservationArc))
                    {
                        LM_lambda.Add(path.ReservationArc, initMultipler);
                    }
                }
            }

            //拉格朗日乘子 lambda 迭代方向
            Dictionary <IEdge <TravelHyperNode>, decimal> Grad_lambda = new Dictionary <IEdge <TravelHyperNode>, decimal>();
            foreach (CustomerArrival customer in _ctx.Pal)
            {
                foreach (var path in pathDict[customer])
                {
                    if (!Grad_lambda.ContainsKey(path.ReservationArc))
                    {
                        Grad_lambda.Add(path.ReservationArc, initMultipler);
                    }
                }
            }

            #endregion

            decimal bigM1       = pathDict.Max(i => i.Value.Max(j => basicGraph.GetPathCost(j)));
            decimal bigM2       = _ctx.Pal.Count();
            decimal bigM        = Math.Max(bigM1, bigM2);
            decimal lowerBound  = decimal.MinValue;
            decimal upperBound  = decimal.MaxValue;
            decimal trustRegion = 1m;
            decimal LagErrBound = 0.01m;

            bool    flag           = false;//对偶问题有解
            decimal lastlowerBound = 0;

            PrintIterationInfo($"Iteration Number, Lower Bound, Upper Bound, Best Lower Bound, Best Upper Bound, Total Gap(%) ");

            for (int iter = 0; iter < iteration; iter++)
            {
                Log($"--------------第{iter}轮求解开始--------------");

                bool hasFeasibleSolution = true;

                #region 求解LR问题
                SubTasks.Clear();
                foreach (CustomerArrival customer in _ctx.Pal)// 求解x
                {
                    Task ta = factory.StartNew(() =>
                    {
                        var graph = new LRxTravelHyperNetwork(_ctx, adapter, objgraph, customer, pathDict, LM_rho, LM_mu, LM_lambda);
                        graph.Build();
                        var ori = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                        var des = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).DesSta;
                        DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode> dijkstra
                            = new DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode>(graph, new TravelHyperNode()
                        {
                            Time    = adapter.ConvertToDiscreteTime(customer.ArriveTime),
                            Station = ori,
                            Price   = 0
                        });    //考虑该旅客到达时间
                        x[customer] = new TravelPath(graph, dijkstra.ShortestPathTo(
                                                         new TravelHyperNode()
                        {
                            Time    = adapter.Horizon + 1440,
                            Station = des,
                            Price   = 0
                        }));
                    });
                    SubTasks.Add(ta);
                }
                foreach (var train in _ctx.Wor.RailwayTimeTable.Trains)
                {
                    foreach (IRailwayStation station in _ctx.Wor.Net.StationCollection)// 求解w
                    {
                        Task ta = factory.StartNew(() =>
                        {
                            var graph = DpnAlgorithm.BuildLRwGraph(_ctx, adapter, train, station, pathDict, basicGraph.LinkTrainDict, LM_mu, LM_lambda);
                            DijkstraShortestPaths <DirectedWeightedSparseGraph <string>, string> dijkstra
                                         = new DijkstraShortestPaths <DirectedWeightedSparseGraph <string>, string>(graph, "Start");//考虑该旅客到达时间
                            var nodepath = dijkstra.ShortestPathTo("End");
                            if (nodepath == null)
                            {
                                throw new System.Exception("No path found");
                            }
                            else
                            {
                                w[train][station] = new PricePath(graph, nodepath);
                            }
                        });
                        SubTasks.Add(ta);
                    }
                }
                Task.WaitAll(SubTasks.ToArray());

                foreach (var edge in y.Keys.ToArray())//更新y
                {
                    var sta   = edge.Source.Station;
                    var train = basicGraph.GetTrainByReservationLink(edge);
                    y[edge] = w[train][sta].GetWrapPoints(edge.Destination.Price, edge.Source.Time).Any();
                }
                #endregion

                #region 计算拉格朗日函数值作为下界

                decimal templowerBound       = 0m;
                decimal templowerBound_part1 = 0m;
                decimal templowerBound_part2 = 0m;
                decimal templowerBound_part3 = 0m;
                decimal templowerBound_part4 = 0m;
                Dictionary <CustomerArrival, decimal> lbValueDic
                    = new Dictionary <CustomerArrival, decimal>();
                //1 计算在基础网络中的路径cost
                foreach (CustomerArrival customer in _ctx.Pal)
                {
                    lbValueDic.Add(customer, objgraph.GetPathCost(x[customer]));
                    templowerBound_part1 += lbValueDic[customer];
                }

                //2计算BRUE项
                templowerBound_part2 += _ctx.Pal.Sum(c => pathDict[c].Sum(p =>
                {
                    decimal secondItem = 0m;
                    secondItem        += basicGraph.GetPathCost(x[c]) - basicGraph.GetPathCost(p) - _ctx.SitaDic[c.Customer.MarSegID];
                    secondItem        -= (p.ReservationArc != null && y[p.ReservationArc]) ? 0 : bigM;
                    return(secondItem * LM_mu[c][p]);
                }));

                //3计算In-train Capacity项
                Dictionary <IServiceSegment, int> ServiceDic = _ctx.Wor.RailwayTimeTable
                                                               .Trains.SelectMany(i => i.ServiceSegments)
                                                               .ToDictionary(i => i, i => 0);//当前service segment使用情况

                foreach (var p in x.Values)
                {
                    foreach (IServiceSegment seg in p.GetSegments(basicGraph))
                    {
                        ServiceDic[seg] += 1;
                    }
                }
                foreach (var train in _ctx.Wor.RailwayTimeTable.Trains)
                {
                    foreach (var seg in train.ServiceSegments)
                    {
                        templowerBound_part3 += LM_rho[seg] * (ServiceDic[seg] - train.Carriage.Chairs.Count());
                    }
                }

                //4 计算reservation constraint 项
                Dictionary <IEdge <TravelHyperNode>, int> reservationDic
                    = new Dictionary <IEdge <TravelHyperNode>, int>();
                foreach (var p in x.Values)
                {
                    if (reservationDic.ContainsKey(p.ReservationArc))
                    {
                        reservationDic[p.ReservationArc] += 1;
                    }
                    else
                    {
                        reservationDic.Add(p.ReservationArc, 1);
                    }
                }
                foreach (var pair in y.Keys)
                {
                    //y是所有的reservation 的集合 reservationDic 是已经使用的reservation 集合
                    var res = reservationDic.Keys.FirstOrDefault(i => i.Source == pair.Source && i.Destination == pair.Destination);
                    templowerBound_part4 += LM_lambda[pair] * ((res != null ? reservationDic[res] : 0) - (y[pair] ? bigM : 0));
                }

                templowerBound = templowerBound_part1 + templowerBound_part2 + templowerBound_part3 + templowerBound_part4;

                //Log($"Lower Bound = { Math.Round(templowerBound, 2)}," +
                //   $"({ Math.Round(templowerBound_part1, 2) }" +
                //   $"+{ Math.Round(templowerBound_part2, 2)}" +
                //   $"+{ Math.Round(templowerBound_part3, 2)}" +
                //   $"+{ Math.Round(templowerBound_part4, 2)})");

                PrintLBSolution(DpnAlgorithm.GetTravelPathString(_ctx, adapter, objgraph, x, lbValueDic));
                #endregion

                #region 乘子更新
                if (flag)
                {
                    decimal LagLowerBound = Convert.ToDecimal(model.GetValue(theta));
                    lowerBound = Math.Max(lowerBound, templowerBound);
                    decimal lagGap = LagLowerBound - templowerBound;

                    Log($"Lower Bound = { templowerBound }");
                    Log($"Lag Lower Bound = { LagLowerBound }");
                    if (lagGap <= LagErrBound)//判断拉格朗日对偶问题是否达到最优
                    {
                        Log($"求解终止:对偶函数已最优。");
                        break;
                    }
                    else
                    {
                        decimal ratio = (templowerBound - lastlowerBound) / lagGap;
                        if (ratio >= 1m)
                        {
                            trustRegion = trustRegion * 2m;
                        }
                        else if (ratio < 0)
                        {
                            trustRegion = trustRegion / 3m;
                        }
                        if (ratio >= 0m)
                        {
                            /* 更新乘子值 */
                            foreach (var pair in dual_rho)
                            {
                                LM_rho[pair.Key] = Convert.ToDecimal(model.GetValue(pair.Value));
                            }
                            foreach (var pair in dual_lambda)
                            {
                                LM_lambda[pair.Key] = Convert.ToDecimal(model.GetValue(pair.Value));
                            }
                            foreach (CustomerArrival customer in _ctx.Pal)
                            {
                                foreach (var path in pathDict[customer])
                                {
                                    LM_mu[customer][path] = Convert.ToDecimal(model.GetValue(dual_mu[customer][path]));
                                }
                            }
                        }
                        Log($"ratio = { ratio }, Trust-Region = { trustRegion }");
                    }
                }
                else /* 如果对偶问题无可行解,不迭代 */
                {
                    //decimal step = 1.618m / (iter + 1);
                    //foreach (CustomerArrival c in _ctx.Pal)//更新mu
                    //{
                    //    foreach (TravelPath p in pathDict[c])
                    //    {
                    //        Grad_mu[c][p] = basicGraph.GetPathCost(x[c]) - basicGraph.GetPathCost(p) - _ctx.SitaDic[c.Customer.MarSegID]
                    //            - ((p.ReservationArc != null && y[p.ReservationArc]) ? 0 : bigM);
                    //        LM_mu[c][p] = Math.Max(0, LM_mu[c][p] + step * Grad_mu[c][p]);
                    //    }
                    //}
                    //foreach (var pair in y.Keys) //更新lambda
                    //{
                    //    var res = reservationDic.Keys.FirstOrDefault(i => i.Source == pair.Source && i.Destination == pair.Destination);
                    //    Grad_lambda[pair] = ((res != null ? reservationDic[res] : 0) - (y[pair] ? bigM : 0));
                    //    LM_lambda[pair] = Math.Max(0, LM_lambda[pair] + step * Grad_lambda[pair]);
                    //}
                    //foreach (var train in _ctx.Wor.RailwayTimeTable.Trains)//更新rho
                    //{
                    //    foreach (var seg in train.ServiceSegments)
                    //    {
                    //        Grad_rho[seg] = ServiceDic[seg] - train.Carriage.Chairs.Count();
                    //        LM_rho[seg] = Math.Max(0, LM_rho[seg] + step * Grad_rho[seg]);
                    //    }
                    //}
                }

                lastlowerBound = templowerBound;

                #endregion

                #region 求解拉格朗日对偶问题

                /* 求解 几何乘子 */
                // 增加 一个约束
                INumExpr exp = model.NumExpr();

                //2 计算BRUE项
                foreach (var c in _ctx.Pal)
                {
                    foreach (var p in pathDict[c])
                    {
                        decimal secondItem = 0m;
                        secondItem += basicGraph.GetPathCost(x[c]) - basicGraph.GetPathCost(p) - _ctx.SitaDic[c.Customer.MarSegID];
                        secondItem -= (p.ReservationArc != null && y[p.ReservationArc]) ? 0 : bigM;
                        exp         = model.Sum(exp, model.Prod(Convert.ToDouble(secondItem), dual_mu[c][p]));
                    }
                }

                //3计算In-train Capacity项 (这里直接用了计算下界时候的 Service_dic
                foreach (var train in _ctx.Wor.RailwayTimeTable.Trains)
                {
                    foreach (var seg in train.ServiceSegments)
                    {
                        exp = model.Sum(exp, model.Prod(Convert.ToDouble(ServiceDic[seg]
                                                                         - train.Carriage.Chairs.Count()), dual_rho[seg]));
                    }
                }

                //4 计算reservation constraint 项 (这里直接用了计算下界时候的 reservationDic
                foreach (var pair in y.Keys)
                {
                    var res = reservationDic.Keys.FirstOrDefault(i => i.Source == pair.Source &&
                                                                 i.Destination == pair.Destination);
                    exp = model.Sum(exp, model.Prod(Convert.ToDouble(((res != null ? reservationDic[res] : 0)
                                                                      - (y[pair] ? bigM : 0))), dual_lambda[pair]));
                }

                model.AddGe(model.Sum(Convert.ToDouble(templowerBound_part1), exp), theta);

                /* Trust-Region */

                foreach (var c in _ctx.Pal)
                {
                    foreach (var p in pathDict[c])
                    {
                        dual_mu[c][p].LB = Math.Max(0, Convert.ToDouble(LM_mu[c][p] - trustRegion));
                        dual_mu[c][p].UB = Convert.ToDouble(LM_mu[c][p] + trustRegion);
                    }
                }

                foreach (var train in _ctx.Wor.RailwayTimeTable.Trains)
                {
                    foreach (var seg in train.ServiceSegments)
                    {
                        dual_rho[seg].LB = Math.Max(0, Convert.ToDouble(LM_rho[seg] - trustRegion));
                        dual_rho[seg].UB = Convert.ToDouble(LM_rho[seg] + trustRegion);
                    }
                }

                foreach (var pair in y.Keys)
                {
                    dual_lambda[pair].LB = Math.Max(0, Convert.ToDouble(LM_lambda[pair] - trustRegion));
                    dual_lambda[pair].UB = Convert.ToDouble(LM_lambda[pair] + trustRegion);
                }

                flag = model.Solve();
                Log($"Is Dual Problem Feasible: { flag }");

                #endregion

                #region 通过一个启发式规则计算上界(按照w模拟到达)

                var pathcost     = lbValueDic.ToDictionary(i => i.Key, i => i.Value);
                var x_least      = x.ToDictionary(i => i.Key, i => i.Value);//当前w下每个旅客的最短路径
                var x_upperbound = x.ToDictionary(i => i.Key, i => i.Value);
                var x_controlled = x.ToDictionary(i => i.Key, i => i.Value);

                #region 1-构建当前y下的最优x值
                SubTasks.Clear();
                foreach (CustomerArrival customer in _ctx.Pal)// 求解x
                {
                    Task ta = factory.StartNew(() =>
                    {
                        var controlledLRxgraph = new ControlledLRxTravelHyperNetwork(
                            _ctx, adapter, objgraph, customer, pathDict, LM_rho, LM_mu, LM_lambda, y);
                        controlledLRxgraph.Build();
                        var ori = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                        var des = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).DesSta;

                        TravelHyperNode startNode = new TravelHyperNode()
                        {
                            Time    = adapter.ConvertToDiscreteTime(customer.ArriveTime),
                            Station = ori,
                            Price   = 0
                        };
                        TravelHyperNode endNode = new TravelHyperNode()
                        {
                            Time    = adapter.Horizon + 1440,
                            Station = des,
                            Price   = 0
                        };

                        DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode> dijkstra
                            = new DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode>
                                  (controlledLRxgraph, startNode);//考虑该旅客到达时间

                        if (!dijkstra.HasPathTo(endNode))
                        {
                            throw new System.Exception("没有路径!");
                        }
                        else
                        {
                            x_controlled[customer] = new TravelPath(controlledLRxgraph, dijkstra.ShortestPathTo(endNode));
                        }
                    });
                    SubTasks.Add(ta);
                }
                Task.WaitAll(SubTasks.ToArray());
                #endregion

                # region 2-构建当前y下的出行最小值
                var solutiongraph = new ControlledTravelHyperNetwork(_ctx, adapter, y);
                solutiongraph.Build();
                Parallel.ForEach(_ctx.Pal, customer =>                //foreach (var customer in _ctx.Pal)//求此网络下每个旅客的最短路径
                {
                    var ori = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                    var des = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).DesSta;

                    TravelHyperNode startNode = new TravelHyperNode()
                    {
                        Time    = adapter.ConvertToDiscreteTime(customer.ArriveTime),
                        Station = ori,
                        Price   = 0
                    };

                    TravelHyperNode endNode = new TravelHyperNode()
                    {
                        Time    = adapter.Horizon + 1440,
                        Station = des,
                        Price   = 0
                    };

                    DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode> dijkstra
                        = new DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode>
                              (solutiongraph, startNode);

                    if (!dijkstra.HasPathTo(endNode))
                    {
                        throw new System.Exception("没有路径!");
                    }
                    else
                    {
                        x_least[customer] = new TravelPath(solutiongraph, dijkstra.ShortestPathTo(endNode));
                    }
                });
                #endregion

                #region 3-修复可行解
                var solutiongraphTemp = new SimNetwork(_ctx, adapter, y);//建立仿真网络
                solutiongraphTemp.Build();
                foreach (var customer in _ctx.Pal)
                {
                    x_upperbound[customer] = x_controlled[customer];
                    TravelPath path = x_controlled[customer];

                    if (!solutiongraphTemp.IsPathFeasible(path) ||
                        solutiongraphTemp.GetPathCost(path) > solutiongraph.GetPathCost(x_least[customer]) + _ctx.SitaDic[customer.Customer.MarSegID])//如果违反了容量约束或者BRUE约束
                    {
                        var ori = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).OriSta;
                        var des = (_ctx.Wor.Mar[customer.Customer.MarSegID] as IRailwayMarketSegment).DesSta;
                        DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode> dijkstra
                            = new DijkstraShortestPaths <DirectedWeightedSparseGraph <TravelHyperNode>, TravelHyperNode>(solutiongraphTemp, new TravelHyperNode()
                        {
                            Time    = adapter.ConvertToDiscreteTime(customer.ArriveTime),
                            Station = ori,
                            Price   = 0
                        });

                        //重新查找路径,如果存在路径
                        if (dijkstra.HasPathTo(new TravelHyperNode()
                        {
                            Time = adapter.Horizon + 1440,
                            Station = des,
                            Price = 0
                        }))
                        {
                            x_upperbound[customer] = new TravelPath(solutiongraphTemp, dijkstra.ShortestPathTo(new TravelHyperNode()
                            {
                                Time    = adapter.Horizon + 1440,
                                Station = des,
                                Price   = 0
                            }));
                            if (solutiongraphTemp.GetPathCost(x_upperbound[customer]) <= //满足BRUE约束
                                solutiongraph.GetPathCost(x_least[customer]) + _ctx.SitaDic[customer.Customer.MarSegID])
                            {
                                path = x_upperbound[customer];
                            }
                            else
                            {
                                hasFeasibleSolution = false;
                                break;
                            }
                        }
                        else
                        {
                            hasFeasibleSolution = false;
                            break;
                        }
                    }

                    pathcost[customer] = objgraph.GetPathCost(path);

                    //加载路径
                    foreach (var seg in path.GetSegments(basicGraph))
                    {
                        solutiongraphTemp.AddUsage(seg, 1);
                    }
                }
                var tempUpperbound = _ctx.Pal.Sum(c => objgraph.GetPathCost(x_upperbound[c]));
                #endregion

                //如果有最优解再更新上界
                bool hasBetterUpperbound = tempUpperbound < upperBound;
                if (hasFeasibleSolution)
                {
                    upperBound = Math.Min(upperBound, tempUpperbound);
                }
                Log($"Upper Bound = {  Math.Round(tempUpperbound, 2) },找到可行解 : { hasFeasibleSolution.ToString()}");
                #endregion

                #region  Gap 信息

                decimal absoluteGap = 0;
                string  gapStr      = "";
                //如果上限是无穷,那么此时gap也是无穷
                if (upperBound == decimal.MaxValue || lowerBound == decimal.MinValue)
                {
                    absoluteGap = decimal.MaxValue;
                    gapStr      = $"+∞";
                }
                else
                {
                    absoluteGap = upperBound - lowerBound;
                    gapStr      = $"{ Math.Round(absoluteGap, 2)}";
                }


                if (absoluteGap < terminalFactor && absoluteGap > 0)
                {
                    Log($"求解终止:Gap以满足终止条件,Gap={ absoluteGap }");
                    break;
                }

                Log($"Total Gap = { gapStr }");
                #endregion

                #region 输出信息

                //SendMessage($"#Iteration Number, Lower Bound, Upper Bound, Best Lower Bound, Best Upper Bound, Total Gap(%) ");
                PrintIterationInfo($"#{iter},{ Math.Round(templowerBound) },{ Math.Round(tempUpperbound) },{ Math.Round(lowerBound)}" +
                                   $",{ Math.Round(upperBound) },{ gapStr }");

                string ss = "###,";
                foreach (var s in LM_rho)
                {
                    ss += ($"{s.Key.ToString()}:{ s.Value.ToString() },");
                }
                PrintIterationInfo(ss);

                PrintIterationInfo($"#{iter},{ Math.Round(templowerBound) },{ Math.Round(tempUpperbound) },{ Math.Round(lowerBound)}" +
                                   $",{ Math.Round(upperBound) },{ gapStr }");

                if (hasFeasibleSolution && hasBetterUpperbound)
                {
                    ObjValue = pathcost.Sum(i => i.Value);
                    PrintSolution(
                        DpnAlgorithm.GetTravelPathString(_ctx, adapter, solutiongraph, x_upperbound, pathcost),
                        DpnAlgorithm.GetPricingPathString(_ctx, adapter, w));
                }

                #endregion

                Log($"--------------第{iter}轮求解结束--------------");
            }
Exemple #38
0
        // GED formulation from the paper
        // https://ieeexplore.ieee.org/document/1642656
        public override void BLPjusticehero()
        {
            int nbNode1 = graph1.ListNodes.Count;
            int nbNode2 = graph2.ListNodes.Count;
            int N       = nbNode1 + nbNode2; // nombre de noeuds du graphe d'édition
            // #region
            //création matrices de placement standard A0 et A1
            Graph  gridg1        = new Graph();
            Graph  gridg2        = new Graph();
            Type   typeNodeLabel = graph1.ListNodes[0].Label.GetType();
            object objNode       = Activator.CreateInstance(typeNodeLabel);

            Graphs.Label nodeepslabel = (Graphs.Label)objNode;
            nodeepslabel.Id = ConstantsAC.EPS_ID;

            Type   typeEdgeLabel = null;
            object objEdge       = null;

            Graphs.Label edgeepslabel = null;
            if (graph1.ListEdges.Count > 0)
            {
                typeEdgeLabel   = graph1.ListEdges[0].Label.GetType();
                objEdge         = Activator.CreateInstance(typeEdgeLabel);
                edgeepslabel    = (Graphs.Label)objEdge;
                edgeepslabel.Id = ConstantsAC.EPS_ID;
            }

            if (graph2.ListEdges.Count > 0)
            {
                typeEdgeLabel   = graph2.ListEdges[0].Label.GetType();
                objEdge         = Activator.CreateInstance(typeEdgeLabel);
                edgeepslabel    = (Graphs.Label)objEdge;
                edgeepslabel.Id = ConstantsAC.EPS_ID;
            }

            if (graph1.ListEdges.Count == 0 && graph2.ListEdges.Count == 0)
            {
                Console.Out.WriteLine("error no edges random edge label alkane");
                edgeepslabel    = (Graphs.Label) new LabelEdgeAlkane();
                edgeepslabel.Id = ConstantsAC.EPS_ID;
            }

            //else
            //{

            //edgeepslabel = (Graphs.Label)new LabelEdgeAlkane();
            //edgeepslabel.Id = ConstantsAC.EPS_ID;
            //}

            for (int i = 0; i < nbNode1; i++)
            {
                gridg1.addNode(graph1.ListNodes[i]);
            }

            for (int i = 0; i < graph1.ListEdges.Count; i++)
            {
                gridg1.addEdge(graph1.ListEdges[i]);
            }

            // ajout des noeuds "virtuels" au graphe g1, pour que g1 corresponde au placement standard dans le graphe d'édition (A0)
            for (int i = nbNode1; i < N; i++)
            {
                Node n = new Node((i + 2).ToString());
                gridg1.addNode(n);
                n.Label    = nodeepslabel;
                n.Label.Id = ConstantsAC.EPS_ID;

                // LabelEdgeLetter
                //n.Label = new Graphs.GenericLabel();
                //n.Label.Id = n.Id;
            }


            MatrixLibrary.Matrix A0 = gridg1.calculateAdjacencyMatrix(); // création matrice d'adajcence de g1

            // idem pour g2 (A1)
            for (int i = 0; i < nbNode2; i++)
            {
                gridg2.addNode(graph2.ListNodes[i]);
            }

            for (int i = 0; i < graph2.ListEdges.Count; i++)
            {
                gridg2.addEdge(graph2.ListEdges[i]);
            }

            for (int i = nbNode2; i < N; i++)
            {
                Node n = new Node((i + 2).ToString());
                gridg2.addNode(n);
                n.Label    = nodeepslabel;//new LabelNodeMutagen();
                n.Label.Id = ConstantsAC.EPS_ID;
                //n.Label = new Graphs.GenericLabel();
                //n.Label.Id = n.Id;
            }
            MatrixLibrary.Matrix A1 = gridg2.calculateAdjacencyMatrix(); // création matrice d'adajcence de g2

            // les graphes vont être étiquetés avec un label LabelNodeMolecule (pour les noeuds) et LabelEdgeMolecule (pour les arrêtes)
            // cela va nous permettre d'utiliser notre propre méthode "dissimilarity" pour les noeuds et arrêtes
            // gridg1.DynamicCastLabel(graph1.ListNodes[0].Label, graph1.ListEdges[0].Label);
            //  gridg2.DynamicCastLabel(graph2.ListNodes[0].Label, graph2.ListEdges[0].Label);


            // nb variables du pb : matrices P(N*N), S(N*N) et T(N*N)
            int nbCols = 3 * (N * N);
            // nb contraintes du pb
            int nbRows = N * N + N + N;


            List <double> objList     = new List <double>();
            List <string> colNameList = new List <string>();

            // coût des opérations d'édition des sommets (coeff de P dans la formule de la distance d'édition)
            for (int i = 0; i < N; i++)
            {
                for (int j = 0; j < N; j++)
                {
                    double costNode = gridg1.ListNodes[i].Label.dissimilarity(gridg2.ListNodes[j].Label);
                    objList.Add(costNode);
                    //colNameList.Add("P[" + gridg1.ListNodes[i].Id + "][" + gridg2.ListNodes[j].Id + "]");
                    colNameList.Add("x_" + gridg1.ListNodes[i].Id + "," + gridg2.ListNodes[j].Id + "");
                }
            }


            // coût des opérations d'édition des arrêtes (coeffs de S et T)
            //Edge ee = new Edge((0).ToString());
            //ee.Label = new LabelEdgeMutagen();
            //ee.Label.Id = ConstantsAC.EPS_ID;
            // coeff de S
            for (int i = 0; i < N; i++)
            {
                for (int j = 0; j < N; j++)
                {
                    // dans notre cas, l'opération est soit 0->1 ou 1->0 (insertion ou suppression d'une arrête)
                    // double costNode = ee.Label.dissimilarity(ee.Label) / 2.0;
                    double costNode = edgeepslabel.dissimilarity(edgeepslabel) / 2.0;


                    //double costNode = 0.5 / 2.0;
                    objList.Add(costNode);
                    colNameList.Add("S[" + gridg1.ListNodes[i].Id + "][" + gridg2.ListNodes[j].Id + "]");
                }
            }

            // coeff de T
            for (int i = 0; i < N; i++)
            {
                for (int j = 0; j < N; j++)
                {
                    // dans notre cas, l'opération est soit 0->1 ou 1->0 (insertion ou suppression d'une arrête)
                    //double costNode = ee.Label.dissimilarity(ee.Label) / 2.0;
                    double costNode = edgeepslabel.dissimilarity(edgeepslabel) / 2.0;
                    //  double costNode = 0.5 / 2.0;
                    objList.Add(costNode);
                    colNameList.Add("T[" + gridg1.ListNodes[i].Id + "][" + gridg2.ListNodes[j].Id + "]");
                }
            }

            try
            {
                // Cplex cplex = new Cplex(); // creation du modèle CPLEX

                //ILPMatrix lp_matrix = cplex.AddLPMatrix();  // matrice du pb (initialisée à 0 colonnes et 0 lignes)

                cplex     = new Cplex();
                ilpMatrix = cplex.AddLPMatrix();



                ColumnArray colonnes = cplex.ColumnArray(ilpMatrix, nbCols); // définition des variables-colonnes du pb

                // ajout des variables-colonnes dans la matrice du pb (avec définition des bornes: P[i][j] = 0 ou 1, idem avec S et T)
                INumVar[] x = cplex.NumVarArray(colonnes, 0, 1, NumVarType.Bool, colNameList.ToArray());

                INumVar[,] P = new INumVar[N, N];
                INumVar[,] S = new INumVar[N, N];
                INumVar[,] T = new INumVar[N, N];

                for (int i = 0; i < N; i++)
                {
                    for (int j = 0; j < N; j++)
                    {
                        P[i, j] = x[(N * i) + j];
                    }
                }


                // indice de S et T dans x (utilisés lors de la définition des contraintes)
                int indicedebutS = N * N;       // indice du 1er élément de S dans x
                int indicedebutT = 2 * (N * N); // indice du 1er élément de T dans x

                for (int i = 0; i < N; i++)
                {
                    for (int j = 0; j < N; j++)
                    {
                        S[i, j] = x[indicedebutS + (N * i) + j];
                    }
                }

                for (int i = 0; i < N; i++)
                {
                    for (int j = 0; j < N; j++)
                    {
                        T[i, j] = x[indicedebutT + (N * i) + j];
                    }
                }

                objCoef = objList.ToArray();
                // ajout de la fonction objectif du pb
                cplex.AddMinimize(cplex.ScalProd(x, objCoef));


                // contrainte n°1
                for (int i = 0; i < N; i++)
                {
                    int[]     coeffsA0   = new int[N];     // vecteur des coeffs ligne i de A0
                    INumVar[] coeffsP_A1 = new INumVar[N]; // vecteur des coeffs ligne i de P
                    for (int c = 0; c < N; c++)
                    {
                        coeffsA0[c]   = (int)A0[i, c];
                        coeffsP_A1[c] = P[i, c];
                    }

                    for (int j = 0; j < N; j++)
                    {
                        INumVar[] coeffsP  = new INumVar[N]; // vecteur des coeffs colonne j de P
                        int[]     coeffsA1 = new int[N];     // vecteur des coeffs colonne j de A1
                        for (int c = 0; c < N; c++)
                        {
                            coeffsP[c]  = P[c, j];
                            coeffsA1[c] = (int)A1[c, j];
                        }
                        cplex.AddEq(cplex.Sum(
                                        cplex.Diff(
                                            cplex.ScalProd(coeffsP, coeffsA0), cplex.ScalProd(coeffsP_A1, coeffsA1)),
                                        cplex.Diff(
                                            S[i, j], T[i, j]))
                                    , 0);

                        /* (ANCIEN PRODUIT TERME A TERME)
                         *      cplex.AddEq(cplex.Sum(
                         *          cplex.Diff(
                         *              cplex.Prod(A0[i,j],P[i,j]),cplex.Prod(P[i,j],A1[i,j])),
                         *          cplex.Diff(
                         *              S[i, j], T[i, j]))
                         *          , 0); */
                    }
                }

                // contrainte n°2 (somme des lignes dans P = 1 et somme des colonnes dans P = 1)
                for (int i = 0; i < N; i++)
                {
                    INumVar[] sommeLignes   = new INumVar[N];
                    INumVar[] sommeColonnes = new INumVar[N];
                    for (int j = 0; j < N; j++)
                    {
                        sommeLignes[j]   = x[N * i + j];
                        sommeColonnes[j] = x[N * j + i];
                    }
                    cplex.AddEq(cplex.Sum(sommeLignes), 1);
                    cplex.AddEq(cplex.Sum(sommeColonnes), 1);
                }
            }
            catch (ILOG.Concert.Exception e)
            {
                System.Console.WriteLine("Concert exception `" + e + "` caught");
            }
        }
Exemple #39
0
        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[]   u = cplex.IntVarArray(data.n, 0, (data.n - 1));
                        cplex.Add(u);

                        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);
                        }

                        for (int i = 0; i < data.n; i++)
                        {
                            for (int j = 0; j < data.n; j++)
                            {
                                if (i >= 1 && i != j && j < data.n)
                                {
                                    cplex.AddLe(
                                        cplex.Sum(cplex.Diff(u[i], u[j]),
                                                  cplex.Prod(data.n, x[i][j])),
                                        (data.n - 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);

                        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]);
                            }
                            double[] sol_u = new double[data.n];
                            sol_u = cplex.GetValues(u);

                            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} - u[i] = {sol_u[i]} and u[j] = {sol_u[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();
            }
        }
Exemple #40
0
    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);
        }
    }
Exemple #41
0
        public Dictionary <EdgePair, Double> Solve(FCTPGraph ti)
        {
            Dictionary <EdgePair, Double> edgeFlows = new Dictionary <EdgePair, Double>();
            Dictionary <String, Edge>     edgeMap   = new Dictionary <String, Edge>();
            Dictionary <String, INumVar>  varMap    = new Dictionary <String, INumVar>();
            String currentVar = "";

            try {
                //Model
                Cplex  cplex = new Cplex();
                IModel model = cplex.GetModel();
                //model.Set(GRB.StringAttr.ModelName, "tranportation");

                ILinearNumExpr expr = cplex.LinearNumExpr();

                //edges
                foreach (Edge e in ti.Edges)
                {
                    String xij = edgeVarName(e.Source, e.Sink);
                    edgeMap.Add(xij, e);
                    INumVar var = cplex.NumVar(0, System.Double.MaxValue);
                    var.Name = xij;
                    varMap.Add(xij, var);
                    expr.AddTerm(e.C, var);
                }

                //objective min Sum c_{ij} x_{ij}
                model.Add(cplex.Minimize(expr));


                //supply constraints
                foreach (Node ssource in ti.Sources)
                {
                    List <INumExpr> sourceConstraint = new List <INumExpr>();
                    foreach (Node ssink in ti.Sinks)
                    {
                        String name = edgeVarName(ssource.Id, ssink.Id);
                        sourceConstraint.Add(varMap[name]);
                    }
                    cplex.AddEq(cplex.Sum(sourceConstraint.ToArray()), ssource.Amount);
                }

                //demand constraints
                foreach (Node dsink in ti.Sinks)
                {
                    List <INumExpr> sinkConstraint = new List <INumExpr>();
                    foreach (Node dsource in ti.Sources)
                    {
                        String name = edgeVarName(dsource.Id, dsink.Id);
                        sinkConstraint.Add(varMap[name]);
                    }
                    cplex.AddEq(cplex.Sum(sinkConstraint.ToArray()), dsink.Amount);
                }

                cplex.SetParam(Cplex.BooleanParam.Threads, 1);
                cplex.ExportModel("mipTranportationCplex.lp");

                bool status = cplex.Solve();
                Console.WriteLine("Status: " + status);

                foreach (String s in edgeMap.Keys)
                {
                    currentVar = s;
                    double   flow = cplex.GetValue(varMap[s]);
                    Edge     e    = edgeMap[s];
                    EdgePair ep   = new EdgePair(e.Source, e.Sink);
                    edgeFlows.Add(ep, flow);
                }
                cplex.End();
            } catch (ILOG.Concert.Exception e) {
                Console.Out.WriteLine(currentVar + " - is current var");
                Console.Out.WriteLine(e.ToString());
            }

            return(edgeFlows);
        }
Exemple #42
0
    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");
        }
    }
Exemple #43
0
 protected virtual INumExpr LocalExpression(Cplex model, INumExpr[] input)
 {
     return(null);
 }
Exemple #44
0
        static void Main(string[] args)
        {
            try
            {
                graphFile = args[0];
                int   timeLimit = Convert.ToInt32(args[1]);
                Timer myTimer   = new Timer();
                myTimer.Start();
                myTimer.Interval = timeLimit * 1000;
                startTime        = DateTime.Now;
                myTimer.Elapsed += MyTimer_Elapsed;
                MyGraph graph            = new MyGraph(graphFile, "DIMACS");
                int     maxTime          = 100;
                int     targetCliqueSize = graph.NumberNodes;
                //Эвристически найдем хотя бы что-то похожее на максимальную клику (в пределах 5% ошибки - чтобы вернуть, если не успеет обсчитаться основной обход)
                maxClique = FindMaxClique(graph, maxTime, targetCliqueSize);
                int ub = maxClique.Count;
                Bound = ub;
                List <List <int> > clique = new List <List <int> >();
                //Сортируем вершины по числу соседей, будем вызывать алгоритм для тех вершин, у которых количество соседей наибольшее
                Dictionary <int, int> nodeAndNeighbors = new Dictionary <int, int>();
                for (int i = 0; i < graph.NumberNodes; ++i)
                {
                    int numberNeighbors = graph.NumberNeighbors(i);
                    nodeAndNeighbors.Add(i, numberNeighbors);
                }
                //Сортируем вершины по уменьшению количества соседей
                nodeAndNeighbors = nodeAndNeighbors.OrderByDescending(pair => pair.Value).ToDictionary(pair => pair.Key, pair => pair.Value);
                List <int> colors = new List <int>()
                {
                    1
                };
                //Раскраска графа
                int top = (from v in nodeAndNeighbors.Keys.ToList() select v).ToList <int>()[0];
                Dictionary <int, int> colorizedGraph = new Dictionary <int, int>();
                //Раскрасим граф
                colorizedGraph = colorize(nodeAndNeighbors.Keys.ToList <int>(), graph);
                int cntr = 0;
                //Зададим базовую модель
                Cplex       cplex = new Cplex();
                IRange[][]  rng   = new IRange[1][];
                INumVar[][] var   = new INumVar[1][];
                rng[0] = new IRange[graph.NumberNodes * graph.NumberNodes];
                // add the objective function
                double[] objvals = new double[graph.NumberNodes];
                string[] varname = new string[graph.NumberNodes];
                for (int i = 0; i < graph.NumberNodes; i++)
                {
                    objvals[i] = 1.0;
                    varname[i] = "x" + (i + 1);
                }
                INumVar[] x = cplex.NumVarArray(graph.NumberNodes, 0.0, 1.0, varname);
                var[0] = x;
                //Ограничение, что х лежит от нуля до единицы задали при инициализации
                cplex.AddMaximize(cplex.ScalProd(x, objvals));
                //Получим номер максимального цвета = это количество цветов, в которые окрашен граф
                //Будем иметь в виду, что количество цветов - это верхняя оценка на размер клики, а найденная эвристически клика на первом этапе - нижняя оценка.
                int        colorCount     = colorizedGraph.Values.Max();
                List <int> colorizedNodes = new List <int>();
                int        pointer        = 1;
                //Добавим ограничение, что вершины, входящие в один цветовой класс, не связаны между собой
                for (int i = 1; i <= colorCount; ++i)
                {
                    colorizedNodes = (from t in colorizedGraph where t.Value == i select t.Key).ToList <int>();
                    if (colorizedNodes.Count() != 1)
                    {
                        INumExpr[] constraint = new INumExpr[colorizedNodes.Count()];
                        int        counter    = 0;
                        colorizedNodes.ForEach(node =>
                        {
                            constraint[counter] = cplex.Prod(1.0, x[node]);
                            counter++;
                        });
                        rng[0][pointer] = cplex.AddLe(cplex.Sum(constraint), 1.0, "c" + (pointer));
                        pointer++;
                    }
                }
                for (int i = 0; i < graph.NumberNodes; i++)
                {
                    for (int j = i + 1; j < graph.NumberNodes; j++)
                    {
                        if (!graph.AreAdjacent(i, j))
                        {
                            rng[0][pointer] = cplex.AddLe(cplex.Sum(cplex.Prod(1.0, x[i]), cplex.Prod(1.0, x[j])), 1.0, "c" + (pointer));
                            pointer++;
                        }
                    }
                }

                //------------------------------------------------------------------------
                //-----Пробуем решать задачу ровно до тех пор, пока не получим клику------
                //-----Помним про ограничения на размер клики-----------------------------
                int countOfConstraint = colorCount;
                globalClick = maxClique;
                Branching(cplex, x);
                cplex.End();
                ////Максимальная клика, которую можно найти для вершины - это количество различных цветов, в которые окрашены все ее соседи плюс она  сама
                //foreach (KeyValuePair<int,int> pair in nodeAndNeighbors)
                //{
                //        List<int> neighbors = graph.GetNeighbors(pair.Key);
                //        neighbors.Add(pair.Key);
                //        var cols = (from n in colorizedGraph where neighbors.Exists(t => t == n.Key) select n.Value).Distinct().ToList<int>();
                //        if (cols.Count() >= Bound && cols.Count() >= globalClick.Count())
                //        {
                //            clique.Add(new List<int>());
                //            List<int> cur = new List<int>();
                //            RecursiveSearch(pair.Key, ref cur, ref neighbors, graph);
                //            clique[cntr] = cur;
                //            cntr++;
                //        }
                //}
                TimeSpan time = (DateTime.Now - startTime);
                Console.WriteLine("Time to find " + time);
                Console.WriteLine(globalClick.Count());
                Console.WriteLine(String.Join(" ", globalClick));
                WriteResults(time, globalClick, false);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Fatal: " + ex.Message);
                Console.WriteLine(ex.StackTrace);
                Console.ReadKey();
            }
        }
Exemple #45
0
        //Formlation F1 for the GED problem. Very expressive form.
        // https://hal.archives-ouvertes.fr/hal-01619313

        public override void IsoGraphInexactF1b()
        {
            this.nbRows = nbNode1 + nbEdge1 + nbNode2 + nbEdge2 + 3 * nbEdge1 * nbEdge2;                 //ns + ms+ng+mg+3msmg
            this.nbCols = nbNode1 * nbNode2 + nbEdge1 * nbEdge2 + nbNode1 + nbEdge1 + nbNode2 + nbEdge2; //nsng+msmg+ns+ms+ng+mg
            Graphs.Label nodeepslabel;

            #region objectFunction
            List <double> objList     = new List <double>();
            List <string> colNameList = new List <string>();
            List <char>   typeList    = new List <char>();
            List <Double> ubList      = new List <Double>();
            //the objet funcion
            for (int i = 1; i <= nbNode1; i++)
            {
                for (int k = 1; k <= nbNode2; k++)
                {
                    objList.Add(graph1.ListNodes[i - 1].Label.dissimilarity(graph2.ListNodes[k - 1].Label));
                    colNameList.Add("x_" + graph1.ListNodes[i - 1].Id + "," + graph2.ListNodes[k - 1].Id);
                }
            }

            for (int ij = 1; ij <= nbEdge1; ij++)
            {
                for (int kl = 1; kl <= nbEdge2; kl++)
                {
                    double costEdge = graph1.ListEdges[ij - 1].Label.dissimilarity(graph2.ListEdges[kl - 1].Label);
                    if (copyEdge)
                    {
                        objList.Add(costEdge / 2);
                    }
                    else
                    {
                        objList.Add(costEdge);
                    }
                    colNameList.Add("y_" + graph1.ListEdges[ij - 1].Id + "," + graph2.ListEdges[kl - 1].Id);
                }
            }
            for (int i = 1; i <= nbNode1; i++)
            {
                Type   typeLabel = graph1.ListNodes[i - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;

                objList.Add((graph1.ListNodes[i - 1].Label).dissimilarity(nodeepslabel));
                colNameList.Add("u_" + graph1.ListNodes[i - 1].Id + ",Ins_" + graph1.ListNodes[i - 1].Id);
            }

            for (int ij = 1; ij <= nbEdge1; ij++)
            {
                Type   typeLabel = graph1.ListEdges[ij - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;
                double costEdge = (graph1.ListEdges[ij - 1].Label).dissimilarity(nodeepslabel);
                if (copyEdge)
                {
                    objList.Add(costEdge / 2);
                }
                else
                {
                    objList.Add(costEdge);
                }
                colNameList.Add("e_" + graph1.ListEdges[ij - 1].Id + ",Ins_" + graph1.ListEdges[ij - 1].Id);
            }

            for (int k = 1; k <= nbNode2; k++)
            {
                Type   typeLabel = graph2.ListNodes[k - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;
                objList.Add((graph2.ListNodes[k - 1].Label).dissimilarity(nodeepslabel));
                colNameList.Add("v_Del_" + graph2.ListNodes[k - 1].Id + "," + graph2.ListNodes[k - 1].Id);
            }

            for (int kl = 1; kl <= nbEdge2; kl++)
            {
                Type   typeLabel = graph2.ListEdges[kl - 1].Label.GetType();
                object obj       = Activator.CreateInstance(typeLabel);
                nodeepslabel    = (Graphs.Label)obj;
                nodeepslabel.Id = ConstantsAC.EPS_ID;
                double costEdge = (graph2.ListEdges[kl - 1].Label).dissimilarity(nodeepslabel);
                if (copyEdge)
                {
                    objList.Add(costEdge / 2);
                }
                else
                {
                    objList.Add(costEdge);
                }
                colNameList.Add("f_Del_" + graph2.ListEdges[kl - 1].Id + "," + graph2.ListEdges[kl - 1].Id);
            }
            #endregion

            try
            {
                cplex     = new Cplex();
                ilpMatrix = cplex.AddLPMatrix();

                // add empty corresponding to new variables columns to ilpMatrix
                INumVar[] x = cplex.NumVarArray(cplex.ColumnArray(ilpMatrix, nbCols), 0, 1, NumVarType.Bool, colNameList.ToArray());

                List <Double> lbMatrixList = new List <Double>();
                List <Double> ubMatrixList = new List <Double>();
                Int32[][]     indiceH      = new Int32[nbRows][];
                Double[][]    valeurH      = new Double[nbRows][];
                List <Int32>  jaList; //les indice des valeurs
                List <Double> arList; //les valeurs non zeros dans la ligne

                int rownum = 0;
                #region construir constraintes

                //18.B
                for (int i = 0; i < nbNode1; i++)
                {
                    jaList = new List <int>();
                    arList = new List <Double>();
                    lbMatrixList.Add(1.0);
                    ubMatrixList.Add(1.0);

                    for (int k = 0; k < nbNode2; k++)
                    {
                        jaList.Add(i * nbNode2 + k);
                        arList.Add(1);
                    }
                    jaList.Add(nbNode1 * nbNode2 + nbEdge1 * nbEdge2 + i);
                    arList.Add(1);
                    indiceH[rownum] = jaList.ToArray();
                    valeurH[rownum] = arList.ToArray();
                    rownum++;
                }


                // equation 3
                //18.d
                for (int ij = 0; ij < nbEdge1; ij++)
                {
                    jaList = new List <int>();
                    arList = new List <Double>();
                    lbMatrixList.Add(1.0);
                    ubMatrixList.Add(1.0);
                    for (int kl = 0; kl < nbEdge2; kl++)
                    {
                        jaList.Add(nbNode1 * nbNode2 + ij * nbEdge2 + kl);
                        arList.Add(1);
                    }
                    jaList.Add(nbNode1 * nbNode2 + nbEdge1 * nbEdge2 + nbNode1 + ij);
                    arList.Add(1);

                    indiceH[rownum] = jaList.ToArray();
                    valeurH[rownum] = arList.ToArray();
                    rownum++;
                }

                // contraint: equation [Fb.1]-4
                //
                for (int k = 0; k < nbNode2; k++)
                {
                    jaList = new List <int>();
                    arList = new List <Double>();
                    lbMatrixList.Add(1.0);
                    ubMatrixList.Add(1.0);
                    for (int i = 0; i < nbNode1; i++)
                    {
                        jaList.Add(i * nbNode2 + k);
                        arList.Add(1);
                    }
                    jaList.Add(nbNode1 * nbNode2 + nbEdge1 * nbEdge2 + nbNode1 + nbEdge1 + k);
                    arList.Add(1);

                    indiceH[rownum] = jaList.ToArray();
                    valeurH[rownum] = arList.ToArray();
                    rownum++;
                }


                // equation 5
                for (int kl = 0; kl < nbEdge2; kl++)
                {
                    jaList = new List <int>();    //les indice des valeurs
                    arList = new List <Double>(); //les valeurs non zeros dans la ligne
                    lbMatrixList.Add(1.0);
                    ubMatrixList.Add(1.0);

                    for (int ij = 0; ij < nbEdge1; ij++)
                    {
                        jaList.Add(nbNode1 * nbNode2 + ij * nbEdge2 + kl);
                        arList.Add(1);
                    }
                    jaList.Add(nbNode1 * nbNode2 + nbEdge1 * nbEdge2 + nbNode1 + nbEdge1 + nbNode2 + kl);
                    arList.Add(1);

                    indiceH[rownum] = jaList.ToArray();
                    valeurH[rownum] = arList.ToArray();
                    rownum++;
                }


                //equation 6 7 8
                for (int ij = 0; ij < nbEdge1; ij++)
                {
                    for (int kl = 0; kl < nbEdge2; kl++)
                    {
                        string source_i = graph1.ListEdges[ij].NodeSource.Id;
                        string source_k = graph2.ListEdges[kl].NodeSource.Id;
                        string target_j = graph1.ListEdges[ij].NodeTarget.Id;
                        string target_l = graph2.ListEdges[kl].NodeTarget.Id;

                        //string eij ="e_" + graph1.ListEdges[ij - 1].Id + ",Ins_" + graph1.ListEdges[ij - 1].Id;
                        //string fkl = "f_Del_" + graph2.ListEdges[kl - 1].Id + "," + graph2.ListEdges[kl - 1].Id;

                        string nameVar   = "x_" + source_i + "," + source_k;
                        int    colIndxik = SolverCPLEX.GetIndexByName(x, nameVar);
                        if (colIndxik == -1)
                        {
                            throw new InvalidProgramException();
                        }

                        string nameVar2   = "x_" + target_j + "," + target_l;
                        int    colInd2xjl = SolverCPLEX.GetIndexByName(x, nameVar2);
                        if (colInd2xjl == -1)
                        {
                            throw new InvalidProgramException();
                        }

                        string nameVar3  = "x_" + source_i + "," + target_l;
                        int    colIndxil = SolverCPLEX.GetIndexByName(x, nameVar3);
                        if (colIndxil == -1)
                        {
                            throw new InvalidProgramException();
                        }

                        string nameVar4  = "x_" + target_j + "," + source_k;
                        int    colIndxjk = SolverCPLEX.GetIndexByName(x, nameVar4);
                        if (colIndxjk == -1)
                        {
                            throw new InvalidProgramException();
                        }



                        ////////////////////////////////
                        jaList = new List <int>();
                        arList = new List <Double>();
                        lbMatrixList.Add(0.0);
                        ubMatrixList.Add(2.0);
                        jaList.Add(colIndxik);
                        arList.Add(1);
                        jaList.Add(colIndxil);
                        arList.Add(1);
                        jaList.Add(nbNode1 * nbNode2 + ij * nbEdge2 + kl);
                        arList.Add(-1);
                        indiceH[rownum] = jaList.ToArray();
                        valeurH[rownum] = arList.ToArray();
                        rownum++;

                        ////////////////////////////////
                        jaList = new List <int>();
                        arList = new List <Double>();
                        lbMatrixList.Add(0.0);
                        ubMatrixList.Add(2.0);
                        jaList.Add(colInd2xjl);
                        arList.Add(1);
                        jaList.Add(colIndxjk);
                        arList.Add(1);
                        jaList.Add(nbNode1 * nbNode2 + ij * nbEdge2 + kl);
                        arList.Add(-1);

                        indiceH[rownum] = jaList.ToArray();
                        valeurH[rownum] = arList.ToArray();
                        rownum++;
                    }
                }
                #endregion
                double[] lb = lbMatrixList.ToArray();
                double[] ub = ubMatrixList.ToArray();

                Int32 res = ilpMatrix.AddRows(lb, ub, indiceH, valeurH);

                // add the objective function
                objCoef = objList.ToArray();
                cplex.AddMinimize(cplex.ScalProd(x, objCoef));
            }
            catch (ILOG.Concert.Exception e)
            {
                System.Console.WriteLine("Concert exception '" + e + "' caught");
            }
        }
Exemple #46
0
    public static void Main(string[] args)
    {
        try {
            Cplex cplex = new Cplex();

            int nbWhouses = 4;
            int nbLoads   = 31;

            INumVar[] capVars =
                cplex.NumVarArray(nbWhouses, 0, 10,
                                  NumVarType.Int);    // Used capacities
            double[] capLbs = { 2.0, 3.0, 5.0, 7.0 }; // Minimum usage level
            double[] costs  = { 1.0, 2.0, 4.0, 6.0 }; // Cost per warehouse

            // These variables represent the assigninment of a
            // load to a warehouse.
            INumVar[][] assignVars = new INumVar[nbWhouses][];
            for (int w = 0; w < nbWhouses; w++)
            {
                assignVars[w] = cplex.NumVarArray(nbLoads, 0, 1,
                                                  NumVarType.Int);

                // Links the number of loads assigned to a warehouse with
                // the capacity variable of the warehouse.
                cplex.AddEq(cplex.Sum(assignVars[w]), capVars[w]);
            }

            // Each load must be assigned to just one warehouse.
            for (int l = 0; l < nbLoads; l++)
            {
                INumVar[] aux = new INumVar[nbWhouses];
                for (int w = 0; w < nbWhouses; w++)
                {
                    aux[w] = assignVars[w][l];
                }

                cplex.AddEq(cplex.Sum(aux), 1);
            }

            cplex.AddMinimize(cplex.ScalProd(costs, capVars));
            cplex.SetParam(Cplex.Param.MIP.Strategy.Search, Cplex.MIPSearch.Traditional);

            if (cplex.Solve(new SemiContGoal(capVars, capLbs)))
            {
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine("--------------------------------------------");
                System.Console.WriteLine();
                System.Console.WriteLine("Solution found:");
                System.Console.WriteLine(" Objective value = " + cplex.ObjValue);
                System.Console.WriteLine();
                for (int w = 0; w < nbWhouses; w++)
                {
                    System.Console.WriteLine("Warehouse " + w + ": stored "
                                             + cplex.GetValue(capVars[w]) + " loads");
                    for (int l = 0; l < nbLoads; l++)
                    {
                        if (cplex.GetValue(assignVars[w][l]) > 1e-5)
                        {
                            System.Console.Write("Load " + l + " | ");
                        }
                    }
                    System.Console.WriteLine(); System.Console.WriteLine();
                }
                System.Console.WriteLine("--------------------------------------------");
            }
            else
            {
                System.Console.WriteLine(" No solution found ");
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
        private void Calculate()
        {
            try
            {
                btnCalc.Enabled = false;
                int ret;

                for (int i = 0; i > dgvTransport.ColumnCount; i++)
                {
                    for (int j = 0; j > dgvTransport.RowCount; j++)
                    {
                        if ((int.TryParse(dgvTransport[i, j].Value.ToString(), out ret) == false || dgvTransport[i, j].Value.ToString() != "T") && i != dgvTransport.ColumnCount - 1 && j != dgvTransport.RowCount - 1)
                        {
                            throw new ILOG.Concert.Exception("A beviteli mezők értékének vagy egész számnak, vagy T-nek kell lennie!");
                        }
                    }
                }



                Cplex cplex  = new Cplex();
                int   Supply = (int)nudSourceNum.Value;
                int   Drain  = (int)nudDrainNum.Value;

                int[] temp;

                int SumSources = 0;
                int SumDrains  = 0;
                int sumValue;

                sumValue = 0;
                for (int i = 0; i < dgvTransport.RowCount - 1; i++)
                {
                    int.TryParse(dgvTransport[dgvTransport.ColumnCount - 1, i].Value.ToString(), out sumValue);
                    SumSources += sumValue;
                }

                sumValue = 0;
                for (int i = 0; i < dgvTransport.ColumnCount - 1; i++)
                {
                    int.TryParse(dgvTransport[i, dgvTransport.RowCount - 1].Value.ToString(), out sumValue);
                    SumDrains += sumValue;
                }

                if (SumSources != SumDrains)
                {
                    //Nyílt szállítási feladat

                    if (SumSources < SumDrains)
                    {
                        DataGridViewRow r = new DataGridViewRow();
                        r.HeaderCell.Value = "FIKTÍV";
                        for (int i = 0; i < dgvTransport.ColumnCount - 1; i++)
                        {
                            DataGridViewCell c = new DataGridViewTextBoxCell();
                            c.Value = 0;
                            r.Cells.Add(c);
                        }
                        DataGridViewTextBoxCell cSupply = new DataGridViewTextBoxCell();
                        cSupply.Value = SumDrains - SumSources;
                        r.Cells.Add(cSupply);
                        dgvTransport.Rows.Insert(dgvTransport.RowCount - 1, r);
                        Supply++;
                    }
                    //egyenlő itt nem lehet, mert csak akkor lép be, ha nem egyenlő a két érték
                    else
                    {
                        DataGridViewTextBoxColumn col = new DataGridViewTextBoxColumn();
                        col.HeaderText = "FIKTÍV";
                        dgvTransport.Columns.Insert(dgvTransport.ColumnCount - 1, col);
                        for (int i = 0; i < dgvTransport.RowCount - 1; i++)
                        {
                            dgvTransport[dgvTransport.ColumnCount - 2, i].Value = 0;
                        }
                        dgvTransport[dgvTransport.ColumnCount - 2, dgvTransport.RowCount - 1].Value = SumSources - SumDrains;
                        Drain++;
                    }
                }

                int[][] Cmatrix = new int[Supply][];
                int[]   sources = new int[Supply];
                int[]   drains  = new int[Drain];

                INumVar[][] x = new INumVar[Supply][];
                INumVar[][] y = new INumVar[Supply][];

                for (int i = 0; i < Supply; i++)
                {
                    x[i] = cplex.NumVarArray(Drain, 0.0, int.MaxValue);
                    y[i] = cplex.NumVarArray(Drain, 0.0, int.MaxValue);
                }

                //források

                for (int i = 0; i < dgvTransport.RowCount - 1; i++)
                {
                    int.TryParse(dgvTransport[dgvTransport.ColumnCount - 1, i].Value.ToString(), out sources[i]);
                }
                //nyelők
                for (int i = 0; i < dgvTransport.ColumnCount - 1; i++)
                {
                    int.TryParse(dgvTransport[i, dgvTransport.RowCount - 1].Value.ToString(), out drains[i]);
                }

                //Coef Matrix
                for (int i = 0; i < dgvTransport.RowCount - 1; i++)
                {
                    temp = new int[Drain];
                    for (int j = 0; j < dgvTransport.ColumnCount - 1; j++)
                    {
                        if (dgvTransport[j, i].Value.ToString() != "T")
                        {
                            int.TryParse(dgvTransport[j, i].Value.ToString(), out temp[j]);
                        }
                        else
                        {
                            temp[j] = int.MaxValue;
                        }
                    }
                    Cmatrix[i] = temp;
                }

                for (int i = 0; i < Supply; i++)       // supply must meet demand
                {
                    cplex.AddEq(cplex.Sum(x[i]), sources[i]);
                }

                for (int j = 0; j < Drain; j++)
                {     // demand must meet supply
                    ILinearNumExpr v = cplex.LinearNumExpr();
                    for (int i = 0; i < Supply; i++)
                    {
                        v.AddTerm(1.0, x[i][j]);
                    }
                    cplex.AddEq(v, drains[j]);
                }

                ILinearNumExpr expr = cplex.LinearNumExpr();
                for (int i = 0; i < Supply; ++i)
                {
                    for (int j = 0; j < Drain; ++j)
                    {
                        expr.AddTerm(x[i][j], Cmatrix[i][j]);
                    }
                }

                cplex.AddMinimize(expr);

                cplex.Solve();
                MessageBox.Show("A megoldás: " + cplex.GetStatus().ToString());
                lblSolutionType.Text = "A megoldás: " + cplex.GetStatus().ToString();
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine(" - Solution: ");

                dgvSolution.RowCount    = Supply;
                dgvSolution.ColumnCount = Drain;

                for (int i = 0; i < Supply; ++i)
                {
                    System.Console.Write("   " + i + ": ");
                    for (int j = 0; j < Drain; ++j)
                    {
                        System.Console.Write("" + cplex.GetValue(x[i][j]) + "\t");
                        dgvSolution[j, i].Value = cplex.GetValue(x[i][j]);
                    }
                    System.Console.WriteLine();
                }
                System.Console.WriteLine("   Cost = " + cplex.ObjValue);
                lblZValue.Text = "A célfüggvény értéke: " + cplex.ObjValue;
                cplex.End();
            }
            catch (ILOG.Concert.Exception icex) { MessageBox.Show(icex.Message); }
        }
Exemple #48
0
 protected override INumExpr LocalExpression(Cplex model, INumExpr[] input)
 {
     return(reference);
 }
Exemple #49
0
 public INumExpr Minorize(Cplex model)
 {
     return(model.Sum(m_lastValue, Minorize(model, 1)));
 }
        /// <summary>
        /// Blend Optimizasyon Çözüm Modeli
        /// </summary>
        /// <param name="data"></param>
        /// <returns>BlendResultModel</returns>
        private BlendResultModel Model(BlendDataModel data)
        {
            #region Veriler

            //parametrelerin local değişkenlere aktarılması.

            _modelAdi  = "Blend";
            _dataModel = data;

            cplex = new Cplex();
            #endregion

            #region Karar Değişkenleri

            m  = cplex.NumVarArray(_dataModel.NbElements, 0.0, Double.MaxValue);
            r  = cplex.NumVarArray(_dataModel.NbRaw, 0.0, Double.MaxValue);
            s  = cplex.NumVarArray(_dataModel.NbScrap, 0.0, Double.MaxValue);
            i  = cplex.NumVarArray(_dataModel.NbIngot, 0.0, Double.MaxValue);
            le = new INumVar[_dataModel.NbElements];

            #endregion

            #region Amaç Fonksiyonu

            // Objective Function: Minimize Cost

            cplex.AddMinimize(cplex.Sum(cplex.ScalProd(_dataModel.Cm, m),
                                        cplex.ScalProd(_dataModel.Cr, r),
                                        cplex.ScalProd(_dataModel.Cs, s),
                                        cplex.ScalProd(_dataModel.Ci, i)));
            #endregion

            #region Kısıtlar

            // Min and max quantity of each element in alloy
            for (int j = 0; j < _dataModel.NbElements; j++)
            {
                le[j] = cplex.NumVar(_dataModel._p[j] * _dataModel.Alloy, _dataModel._P[j] * _dataModel.Alloy);
            }

            // Constraint: produce requested quantity of alloy
            cplex.AddEq(cplex.Sum(le), _dataModel.Alloy);

            // Constraints: Satisfy element quantity requirements for alloy
            for (int j = 0; j < _dataModel.NbElements; j++)
            {
                cplex.AddEq(le[j],
                            cplex.Sum(m[j],
                                      cplex.ScalProd(_dataModel.PRaw[j], r),
                                      cplex.ScalProd(_dataModel.PScrap[j], s),
                                      cplex.ScalProd(_dataModel.PIngot[j], i)));
            }

            #endregion

            #region Çözümün işlenmesi
            try
            {
                if (cplex.Solve())
                {
                    if (cplex.GetStatus().Equals(Cplex.Status.Infeasible))
                    {
                        throw new ILOG.Concert.Exception("No feasible solution found!");
                    }
                    #region Sonuçların Alınması

                    Results = new BlendResultModel()
                    {
                        Satatus        = cplex.GetStatus().ToString(),
                        ObjectiveValue = cplex.GetObjValue(),
                        ResultMessage  = "Çözüm başarılı.",

                        BlendResults = new BlendResult()
                        {
                            MVals = cplex.GetValues(m),
                            RVals = cplex.GetValues(r),
                            SVals = cplex.GetValues(s),
                            IVals = cplex.GetValues(i),
                            EVals = cplex.GetValues(le)
                        }
                    };
                    #endregion
                }
                cplex.End();

                return(Results);
            }
            catch (ILOG.Concert.Exception exc)
            {
                //exc.GetBaseException();
                Console.WriteLine("Concert exception '" + exc + "' caught");
                Console.ReadKey();
            }

            return(Results);

            #endregion
        }
Exemple #51
0
        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);
        }
    }
Exemple #53
0
    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 CRegion ILP(CRegion LSCrg, CRegion SSCrg, CStrObjLtDt StrObjLtDt,
                           double[,] adblTD, string strAreaAggregation,
                           ref SortedSet <CRegion> CrgOOMSetSS, ref SortedSet <CRegion> CrgOOMSolveSS, ref SortedSet <CRegion> CrgOOTSetSS, ref SortedSet <CRegion> CrgOOTSolveSS,
                           ref SortedSet <CRegion> CrgCplexError3019SS, ref SortedSet <CRegion> CrgOtherErrorsSS, ref string strOtherErrors)
        {
            long lngStartMemory = GC.GetTotalMemory(true);

            var pStopwatch = Stopwatch.StartNew();

            LSCrg.SetInitialAdjacency();  //also count the number of edges
            AddLineToStrObjLtDt(StrObjLtDt, LSCrg);

            //must be below LSCrg.SetInitialAdjacency();
            System.Console.WriteLine();
            System.Console.WriteLine();
            System.Console.WriteLine("Crg:  ID  " + LSCrg.ID + ";    n  " + LSCrg.GetCphCount() + ";    m  " +
                                     LSCrg.AdjCorrCphsSD.Count + "  " + _ParameterInitialize.strAreaAggregation + "================================="
                                     + LSCrg.ID + "  " + _ParameterInitialize.strAreaAggregation + " " + this.dblTimeLimit + " s " + "==============================");



            //double dblMemoryInMB2 = CHelpFunc.GetConsumedMemoryInMB(true);
            var cplex = new Cplex();
            //double dblMemoryInMB3 = CHelpFunc.GetConsumedMemoryInMB(true);

            var  crg        = new CRegion(-1);
            bool blnSolved  = false;
            bool blnSetting = false;

            try
            {
                //Step 3
                //Cplex cplex = new Cplex();
                IIntVar[][][]     var2;
                IIntVar[][][][]   var3;
                IIntVar[][][][][] var4;
                IRange[][]        rng;

                PopulateByRow(cplex, out var2, out var3, out var4, out rng, LSCrg, SSCrg, adblTD, strAreaAggregation);
                //double dblMemoryInMB4 = CHelpFunc.GetConsumedMemoryInMB(true);
                // Step 11
                //cplex.ExportModel("lpex1.lp");

                // Step 9
                double dblRemainTimeLim = this.dblTimeLimit - Convert.ToDouble(pStopwatch.ElapsedMilliseconds) / 1000;
                if (dblRemainTimeLim > 0)
                {
                    blnSetting = true;

                    cplex.SetParam(Cplex.DoubleParam.TiLim, dblRemainTimeLim);

                    //avoid that optimal solutions from CPELX are not optimal
                    //see https://www-01.ibm.com/support/docview.wss?uid=swg1RS02094
                    cplex.SetParam(Cplex.IntParam.AuxRootThreads, -1);
                    cplex.SetParam(Cplex.IntParam.Reduce, 0);  //really work for me
                    cplex.SetParam(Cplex.DoubleParam.CutLo, 0);

                    if (cplex.Solve())
                    {
                        //***********Gap for ILP************

                        #region Display x, y, z, and s
                        //for (int i = 0; i < var3[0].GetLength(0); i++)
                        //{

                        //    Console.WriteLine("Variable x; Time: " + (i + 1).ToString());

                        //    foreach (var x1 in var3[0][i])
                        //    {
                        //        //CPatch



                        //        double[] x = cplex.GetValues(x1);


                        //        foreach (var x0 in x)
                        //        {
                        //            int intWrite = 0;  //avoid some values like 0.999999997 or 2E-09
                        //            if (x0>0.5)
                        //            {
                        //                intWrite = 1;
                        //            }
                        //            Console.Write(intWrite + "     ");
                        //        }
                        //        Console.WriteLine();

                        //    }
                        //    Console.WriteLine();
                        //}

                        #region Display y and z
                        //if (var4[0] != null)
                        //{
                        //    Console.WriteLine("");
                        //    //Console.WriteLine("Variable y:");
                        //    for (int i = 0; i < var4[0].GetLength(0); i++)
                        //    {
                        //        Console.WriteLine("Variable y; Time: " + (i + 1).ToString());
                        //        foreach (var y2 in var4[0][i])
                        //        {
                        //            foreach (var y1 in y2)
                        //            {

                        //                double[] y = cplex.GetValues(y1);


                        //                foreach (var y0 in y)
                        //                {
                        //                    Console.Write(y0 + "     ");
                        //                }
                        //                Console.WriteLine();
                        //            }

                        //            Console.WriteLine();
                        //        }
                        //        //Console.WriteLine();
                        //    }
                        //}

                        //if (var4[1] != null)
                        //{
                        //    Console.WriteLine("");
                        //    //Console.WriteLine("Variable z:");
                        //    for (int i = 0; i < var4[1].GetLength(0); i++)
                        //    {
                        //        Console.WriteLine("Variable z; Time: " + (i + 1).ToString());
                        //        foreach (var z2 in var4[1][i])
                        //        {
                        //            foreach (var z1 in z2)
                        //            {

                        //                double[] z = cplex.GetValues(z1);


                        //                foreach (var z0 in z)
                        //                {
                        //                    Console.Write(z0 + "     ");
                        //                }
                        //                Console.WriteLine();

                        //            }
                        //            Console.WriteLine();
                        //        }
                        //        //Console.WriteLine();
                        //    }
                        //}
                        #endregion


                        //if (_ParameterInitialize.strAreaAggregation == _strSmallest)
                        //{
                        //    Console.WriteLine("");
                        //    Console.WriteLine("Variable s:");
                        //    if (var2[0] != null)
                        //    {
                        //        for (int i = 0; i < var2[0].GetLength(0); i++)
                        //        {


                        //            double[] s = cplex.GetValues(var2[0][i]);


                        //            foreach (var s0 in s)
                        //            {
                        //                Console.Write(s0 + "     ");
                        //            }
                        //            Console.WriteLine();

                        //        }
                        //    }
                        //}
                        #endregion

                        #region Display other results
                        //double[] dj = cplex.GetReducedCosts(var3[0][0][0]);
                        //double[] dj2 = cplex.GetReducedCosts((var3);
                        //double[] pi = cplex.GetDuals(rng[0]);
                        //double[] slack = cplex.GetSlacks(rng[0]);
                        //Console.WriteLine("");
                        //cplex.Output().WriteLine("Solution status = "
                        //+ cplex.GetStatus());
                        //cplex.Output().WriteLine("Solution value = "
                        //+ cplex.ObjValue);
                        //objDataLt[13] = 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]
                        //    );
                        //}
                        #endregion
                    }

                    Console.WriteLine("");
                    var strStatus = cplex.GetStatus().ToString();
                    Console.WriteLine("Solution status = " + strStatus);

                    if (strStatus == "Optimal")
                    {
                        blnSolved = true;
                        StrObjLtDt.SetLastObj("EstSteps/Gap%", 0.ToString("F4"));  //keep 4 decimal digits
                        StrObjLtDt.SetLastObj("Cost", cplex.ObjValue);
                        Console.WriteLine("Solution value = " + cplex.ObjValue);
                    }
                    else if (strStatus == "Feasible")
                    {
                        //|best integer-best bound(node)|  / 1e-10 + |best integer|
                        //|cplex.ObjValue-cplex.BestObjValue|  /  1e-10 + |cplex.ObjValue|
                        blnSolved = true;
                        StrObjLtDt.SetLastObj("EstSteps/Gap%", (cplex.MIPRelativeGap * 100).ToString("F4"));  //keep 4 decimal digits
                        StrObjLtDt.SetLastObj("Cost", cplex.ObjValue);
                        Console.WriteLine("Solution value = " + cplex.ObjValue);
                    }
                    else //if (strStatus == "Unknown") //we do not find any solution in a time limit
                    {
                        CrgOOTSolveSS.Add(LSCrg);
                        Console.WriteLine("didn't find any solution in the time limit.");
                    }
                }
                else
                {
                    CrgOOTSetSS.Add(LSCrg);
                }
            }
            catch (ILOG.Concert.Exception e)
            {
                if (e.Message == "CPLEX Error  1001: Out of memory.\n")
                {
                    if (blnSetting == false) //this can happen when we are setting up variables and constraints
                    {
                        Console.Write("During Setting: " + e.Message);
                        CrgOOMSetSS.Add(LSCrg);
                    }
                    else
                    {
                        Console.Write("During Solving: " + e.Message);
                        CrgOOMSolveSS.Add(LSCrg);
                    }
                }
                else if (e.Message == "CPLEX Error  3019: Failure to solve MIP subproblem.\n") //this can really happen
                {
                    Console.Write("During Solving: " + e.Message);
                    CrgCplexError3019SS.Add(LSCrg);
                }
                else  //other eroors, e.g., "CPLEX Error  1004: Null pointer for required data.\n"
                {
                    var strError = "ID: " + LSCrg.ID + "  " + "blnSetting == " + blnSetting.ToString() + ";    " + e.Message;
                    Console.Write(strError);
                    strOtherErrors += strError;
                    CrgOtherErrorsSS.Add(LSCrg);
                    //throw;
                }
            }
            catch (System.OutOfMemoryException e2) //this can really happen, though ILOG.Concert.Exception should occur instead
            {
                if (blnSetting == false)
                {
                    Console.WriteLine("During Setting: System exception " + e2.Message);
                    CrgOOMSetSS.Add(LSCrg);
                    //throw;
                }
                else
                {
                    CrgOOMSolveSS.Add(LSCrg);
                    Console.WriteLine("During Solving: System exception " + e2.Message);
                    //throw;
                }
            }
            finally
            {
                double dblMemoryInMB = CHelpFunc.GetConsumedMemoryInMB(false, lngStartMemory);
                if (blnSolved == false)
                {
                    crg.ID = -2;
                    StrObjLtDt.SetLastObj("EstSteps/Gap%", _intNoSolutionEstSteps.ToString("F4"));
                    //StrObjLtDt.SetLastObj("Cost", -1); //the cost value is -1 by default
                    Console.WriteLine("Crg:  ID  " + LSCrg.ID + ";    n  " + LSCrg.GetCphCount() + ";    m  " +
                                      LSCrg.AdjCorrCphsSD.Count + "  could not be solved by ILP!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                }
                StrObjLtDt.SetLastObj("Time_L(ms)", pStopwatch.ElapsedMilliseconds);
                StrObjLtDt.SetLastObj("Time(ms)", pStopwatch.ElapsedMilliseconds);
                StrObjLtDt.SetLastObj("Memory(MB)", dblMemoryInMB);

                cplex.End();
            }



            return(crg);
        }
Exemple #55
0
    public static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            Usage();
            return;
        }
        try {
            bool useLoggingCallback   = false;
            bool useTimeLimitCallback = false;
            bool useAborter           = false;

            Cplex.Aborter myAborter;

            switch (args[1].ToCharArray()[0])
            {
            case 't':
                useTimeLimitCallback = true;
                break;

            case 'l':
                useLoggingCallback = true;
                break;

            case 'a':
                useAborter = true;
                break;

            default:
                Usage();
                return;
            }

            Cplex cplex = new Cplex();

            cplex.ImportModel(args[0]);
            IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator();
            matrixEnum.MoveNext();
            ILPMatrix  lp  = (ILPMatrix)matrixEnum.Current;
            IObjective obj = cplex.GetObjective();

            if (useLoggingCallback)
            {
                // Set an overall node limit in case callback conditions
                // are not met.
                cplex.SetParam(Cplex.Param.MIP.Limits.Nodes, 5000);

                double lastObjVal =
                    (obj.Sense == ObjectiveSense.Minimize) ?
                    System.Double.MaxValue : -System.Double.MaxValue;

                cplex.Use(new LogCallback(lp.NumVars, -100000, lastObjVal));
                // Turn off CPLEX logging
                cplex.SetParam(Cplex.Param.MIP.Display, 0);
            }
            else if (useTimeLimitCallback)
            {
                cplex.Use(new TimeLimitCallback(cplex, false, cplex.CplexTime,
                                                1.0, 10.0));
            }
            else if (useAborter)
            {
                myAborter = new Cplex.Aborter();
                cplex.Use(myAborter);
                // Typically, you would pass the Aborter object to
                // another thread or pass it to an interrupt handler,
                // and  monitor for some event to occur.  When it does,
                // call the Aborter's abort method.
                //
                // To illustrate its use without creating a thread or
                // an interrupt handler, abort immediately by calling
                // abort before the solve.
                //
                myAborter.Abort();
            }

            cplex.Solve();

            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Cplex status = " + cplex.GetCplexStatus());

            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
        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());
        }
Exemple #57
0
        void solve()
        {
            Cplex Model = new Cplex();

            // decision variables
            #region
            //x1-tjs (first stage t = 1),length of a collection period (in days) at collection point j during time period t
            //INumVar[][][] X1 = new INumVar[period][][];
            //for (int i = 0; i < period; i++)
            //{
            //    X1[i] = new INumVar[cpoint][];
            //    for (int ii = 0; ii < cpoint; ii++)
            //    {
            //        X1[i][ii] = new INumVar[scenario];
            //        X1[i][ii] = Model.NumVarArray(scenario, 1, 7, NumVarType.Int);
            //    }
            //}

            //x2-tpjks ,volume of products returned from collection point j to recycling center k during time period t
            INumVar[][][][][] X2 = new INumVar[period][][][][];
            for (int a = 0; a < period; a++)
            {
                X2[a] = new INumVar[ptype][][][];
                for (int aa = 0; aa < ptype; aa++)
                {
                    X2[a][aa] = new INumVar[cpoint][][];
                    for (int bb = 0; bb < cpoint; bb++)
                    {
                        X2[a][aa][bb] = new INumVar[rcenter][];
                        for (int cc = 0; cc < rcenter; cc++)
                        {
                            X2[a][aa][bb][cc] = new INumVar[scenario];
                            X2[a][aa][bb][cc] = Model.NumVarArray(scenario, 0, System.Double.MaxValue, NumVarType.Int);
                        }
                    }
                }
            }

            //x3-tij ,Binary decision variable equals ‘1’ if customer i is allocated to collection point j during time period t and ‘0’ otherwise
            INumVar[][][] X3 = new INumVar[period][][];
            for (int aa = 0; aa < period; aa++)
            {
                X3[aa] = new INumVar[customer][];
                for (int bb = 0; bb < customer; bb++)
                {
                    X3[aa][bb] = new INumVar[cpoint];
                    X3[aa][bb] = Model.NumVarArray(cpoint, 0.0, 1.0, NumVarType.Bool);
                }
            }


            //x4-tj ,Binary decision variable equals ‘1’ if collection point j is rented during time period t and ‘0’ otherwise
            INumVar[][] X4 = new INumVar[period][];
            for (int i = 0; i < period; i++)
            {
                X4[i] = new INumVar[cpoint];
                X4[i] = Model.NumVarArray(cpoint, 0.0, 1.0, NumVarType.Bool);
            }

            //x5-k ,Binary decision variable equals ‘1’ if recycling center k is established and ‘0’ otherwise
            INumVar[] X5 = new INumVar[rcenter];
            X5 = Model.NumVarArray(rcenter, 0, 1, NumVarType.Bool);

            //x6 maximum capacity level option for recycling center k
            INumVar[] X6 = new INumVar[rcenter];
            X6 = Model.NumVarArray(rcenter, 1, 3, NumVarType.Int);

            //X7-tjs Auxiliary variable  x7 the frequency of recylce during a period
            //INumVar[][][] X7 = new INumVar[period][][];
            //for (int i = 0; i < period; i++)
            //{
            //    X7[i] = new INumVar[cpoint][];
            //    for (int ii = 0; ii < cpoint; ii++)
            //    {
            //        X7[i][ii] = new INumVar[scenario];
            //        X7[i][ii] = Model.NumVarArray(scenario, 30, wday, NumVarType.Int);
            //    }
            //}

            #endregion

            Double M = 100000;

            // constraints
            #region
            // formulation (4)
            INumExpr[] expr1 = new INumExpr[1];

            for (int aa = 0; aa < period; aa++)
            {
                for (int bb = 0; bb < customer; bb++)
                {
                    expr1[0] = X3[0][0][0];
                    for (int cc = 0; cc < cpoint; cc++)
                    {
                        expr1[0] = Model.Sum(expr1[0], X3[aa][bb][cc]);
                    }
                    expr1[0] = Model.Sum(expr1[0], Model.Prod(-1.0, X3[0][0][0]));
                    Model.AddEq(expr1[0], 1);
                }
            }


            // formulation (5)
            INumExpr[] expr2 = new INumExpr[1];
            INumExpr[] expr3 = new INumExpr[1];
            for (int aa = 0; aa < period; aa++)
            {
                for (int bb = 0; bb < cpoint; bb++)
                {
                    expr2[0] = X3[0][0][0];
                    expr3[0] = X4[0][0];
                    for (int cc = 0; cc < customer; cc++)
                    {
                        Model.Sum(expr2[0], X3[aa][cc][bb]);
                    }
                    expr2[0] = Model.Sum(expr2[0], Model.Prod(-1.0, X3[0][0][0]));
                    expr3[0] = Model.Prod(M, X4[aa][bb]);
                    expr3[0] = Model.Sum(expr3[0], Model.Prod(-1.0, X4[0][0]));
                    Model.AddLe(expr2[0], expr3[0]);
                }
            }

            // formulation (6)
            INumExpr[] expr4 = new INumExpr[1];
            INumExpr[] expr5 = new INumExpr[1];
            INumExpr[] expr6 = new INumExpr[1];
            for (int aa = 0; aa < period; aa++)
            {
                for (int cc = 0; cc < scenario; cc++)
                {
                    for (int bb = 0; bb < cpoint; bb++)
                    {
                        expr5[0] = X3[0][0][0];
                        for (int dd = 0; dd < customer; dd++)
                        {
                            for (int ee = 0; ee < ptype; ee++)
                            {
                                expr5[0] = Model.Sum(expr5[0], Model.Prod(Model.Prod(r[dd, ee, aa, cc], X3[aa][dd][bb]), vlength));
                            }
                        }
                        expr5[0] = Model.Sum(expr5[0], Model.Prod(-1.0, X3[0][0][0]));

                        expr6[0] = X2[0][0][0][0][0];
                        for (int ff = 0; ff < rcenter; ff++)
                        {
                            for (int ee = 0; ee < ptype; ee++)
                            {
                                expr6[0] = Model.Sum(expr6[0], X2[aa][ee][bb][ff][cc]);
                            }
                        }
                        expr6[0] = Model.Sum(expr6[0], Model.Prod(-1.0, X2[0][0][0][0][0]));
                        Model.AddEq(expr5[0], expr6[0]);
                    }
                }
            }

            // formulation (7-1)
            INumExpr[] expr7 = new INumExpr[1];
            for (int aa = 0; aa < period; aa++)
            {
                for (int bb = 0; bb < rcenter; bb++)
                {
                    for (int cc = 0; cc < scenario; cc++)
                    {
                        for (int dd = 0; dd < cpoint; dd++)
                        {
                            expr7[0] = X2[0][0][0][0][0];
                            for (int ee = 0; ee < ptype; ee++)
                            {
                                expr7[0] = Model.Sum(expr7[0], X2[aa][ee][dd][bb][cc]);
                            }
                            expr7[0] = Model.Sum(expr7[0], Model.Prod(-1.0, X2[0][0][0][0][0]));
                            Model.AddLe(expr7[0], Model.Prod(X5[bb], M));
                        }
                    }
                }
            }

            // formulation (7-2)
            INumExpr[] expr71 = new INumExpr[1];
            for (int aa = 0; aa < period; aa++)
            {
                for (int bb = 0; bb < rcenter; bb++)
                {
                    for (int cc = 0; cc < scenario; cc++)
                    {
                        for (int dd = 0; dd < cpoint; dd++)
                        {
                            expr71[0] = X2[0][0][0][0][0];
                            for (int ee = 0; ee < ptype; ee++)
                            {
                                expr71[0] = Model.Sum(expr71[0], X2[aa][ee][dd][bb][cc]);
                            }
                            expr71[0] = Model.Sum(expr71[0], Model.Prod(-1.0, X2[0][0][0][0][0]));
                            Model.AddLe(expr71[0], Model.Sum(Model.Prod(X6[bb], 1000), Model.Prod(Model.Sum(1, Model.Prod(X5[bb], -1)), M)));
                        }
                    }
                }
            }

            // formulation (8)
            INumExpr[] expr8 = new INumExpr[1];
            for (int a = 0; a < period; a++)
            {
                expr8[0] = X4[0][0];
                for (int b = 0; b < cpoint; b++)
                {
                    expr8[0] = Model.Sum(expr8[0], X4[a][b]);
                }
                expr8[0] = Model.Sum(expr8[0], Model.Prod(-1.0, X4[0][0]));
                Model.AddGe(expr8[0], 1);
            }

            // formulation (9)
            INumExpr[] expr9 = new INumExpr[1];
            expr9[0] = X5[0];
            for (int a = 0; a < rcenter; a++)
            {
                expr9[0] = Model.Sum(expr9[0], X5[a]);
            }
            expr9[0] = Model.Sum(expr9[0], Model.Prod(-1.0, X5[0]));
            Model.AddGe(expr9[0], 1);

            // formulation (10)
            INumExpr[] expr10 = new INumExpr[1];
            for (int a = 0; a < period; a++)
            {
                for (int b = 0; b < rcenter; b++)
                {
                    for (int c = 0; c < scenario; c++)
                    {
                        for (int d = 0; d < cpoint; d++)
                        {
                            expr10[0] = X2[0][0][0][0][0];
                            for (int e = 0; e < ptype; e++)
                            {
                                expr10[0] = Model.Sum(expr10[0], X2[a][e][d][b][c]);
                            }
                            expr10[0] = Model.Sum(expr10[0], Model.Prod(-1.0, X2[0][0][0][0][0]));
                            Model.AddGe(expr10[0], X5[b]);
                        }
                    }
                }
            }


            // formulation (11)
            for (int a = 0; a < period; a++)
            {
                for (int c = 0; c < customer; c++)
                {
                    for (int b = 0; b < cpoint; b++)
                    {
                        Model.AddLe(Model.Prod(d1[c, b], X3[a][c][b]), l);
                    }
                }
            }

            // formulation (12)
            for (int a = 0; a < period; a++)
            {
                for (int aa = 0; aa < ptype; aa++)
                {
                    for (int b = 0; b < cpoint; b++)
                    {
                        for (int c = 0; c < rcenter; c++)
                        {
                            for (int d = 0; d < scenario; d++)
                            {
                                Model.AddGe(X2[a][aa][b][c][d], 0);
                            }
                        }
                    }
                }
            }



            // #endregion
            //formulation (15)  //formulation (1)  objective function -1
            // collection points rent cost

            INumExpr[] expr11 = new INumExpr[1];
            for (int a = 0; a < period; a++)
            {
                expr11[0] = X4[0][0];
                for (int b = 0; b < cpoint; b++)
                {
                    expr11[0] = Model.Sum(expr11[0], Model.Prod(X4[a][b], e1[b]));
                }
                expr11[0] = Model.Sum(expr11[0], Model.Prod(-1.0, X4[0][0]));
            }

            INumExpr[] expr12  = new INumExpr[1];
            INumExpr[] expr121 = new INumExpr[1];

            for (int a = 0; a < period; a++)
            {
                for (int b = 0; b < rcenter; b++)
                {
                    expr121[0] = X5[0];
                    for (int c = 0; c < cpoint; c++)
                    {
                        for (int d = 0; d < ptype; d++)
                        {
                            for (int e = 0; e < customer; e++)
                            {
                                expr12[0] = X2[0][0][0][0][0];
                                for (int f = 0; f < scenario; f++)
                                {
                                    expr12[0] = Model.Sum(expr12[0], Model.Prod(Model.Prod(X2[a][d][c][b][f], e2[d, c, b]), wday / vlength));
                                }
                                expr12[0] = Model.Sum(expr12[0], Model.Prod(-1.0, X2[0][0][0][0][0]));
                            }
                        }
                    }
                    expr121[0] = Model.Sum(expr121[0], Model.Prod(expr12[0], X5[b]));
                }
            }

            INumExpr[] expr13 = new INumExpr[1];
            for (int a = 0; a < period; a++)
            {
                for (int b = 0; b < rcenter; b++)
                {
                    expr13[0] = X5[0];
                    for (int bb = 0; bb < elevel; bb++)
                    {
                        expr13[0] = Model.Sum(expr13[0], Model.Prod(X5[b], e3[b, bb]));
                    }
                    expr13[0] = Model.Sum(expr13[0], Model.Prod(-1.0, X5[0]));
                }
            }


            Model.AddLe(Model.Prod(wday, Model.Sum(expr11[0], expr13[0])), e);  //expr12[0],  ,)
            // #endregion

            // //formulation (1)  objective function -1
            // #region
            INumExpr[] expr15 = new INumExpr[1];
            expr15[0] = X4[0][0];
            for (int i = 0; i < period; i++)
            {
                for (int ii = 0; ii < cpoint; ii++)
                {
                    expr15[0] = Model.Sum(expr15[0], Model.Prod(a[ii], X4[i][ii]));
                }
            }
            expr15[0] = Model.Sum(expr15[0], Model.Prod(-1.0, X4[0][0]));
            // ok


            INumExpr[] expr17 = new INumExpr[1];
            for (int a = 0; a < period; a++)
            {
                for (int aaa = 0; aaa < scenario; aaa++)
                {
                    for (int bb = 0; bb < cpoint; bb++)
                    {
                        for (int bbb = 0; bbb < customer; bbb++)
                        {
                            expr17[0] = X3[0][0][0];
                            for (int aa = 0; aa < ptype; aa++)
                            {
                                expr17[0] = Model.Sum(expr17[0], Model.Prod(Model.Prod(r[bbb, aa, a, aaa] * b[aa], X3[a][bbb][bb]), (vlength + 1) * 0.5));
                            }
                            expr17[0] = Model.Sum(expr17[0], Model.Prod(-1.0, X3[0][0][0]));
                        }
                    }
                }
            }

            INumExpr[] expr18 = new INumExpr[1];
            INumExpr[] expr41 = new INumExpr[1];
            expr18[0] = X5[0];
            for (int a = 0; a < period; a++)
            {
                for (int aa = 0; aa < rcenter; aa++)
                {
                    for (int bb = 0; bb < cpoint; bb++)
                    {
                        for (int b = 0; b < ptype; b++)
                        {
                            for (int aaa = 0; aaa < customer; aaa++)
                            {
                                expr41[0] = X2[0][0][0][0][0];
                                for (int bbb = 0; bbb < scenario; bbb++)
                                {
                                    expr41[0] = Model.Sum(expr41[0], Model.Prod(Model.Prod(X2[a][b][bb][aa][bbb], z[bb, aa, b]), vlength));
                                }
                                expr41[0] = Model.Sum(expr17[0], Model.Prod(-1.0, X2[0][0][0][0][0]));
                            }
                        }
                    }
                    expr18[0] = Model.Prod(expr41[0], X5[aa]);
                }
            }
            expr18[0] = Model.Sum(expr18[0], Model.Prod(-1.0, X5[0]));

            INumExpr[] expr19 = new INumExpr[1];
            for (int i = 0; i < period; i++)
            {
                for (int ii = 0; ii < rcenter; ii++)
                {
                    for (int iii = 0; iii < elevel; iii++)
                    {
                        expr19[0] = X5[0];
                        for (int iiii = 0; iiii < capacity; iiii++)
                        {
                            expr19[0] = Model.Sum(expr19[0], Model.Prod(q[ii, iii, iiii], X5[ii]));
                        }
                    }
                }
            }
            expr19[0] = Model.Sum(expr19[0], Model.Prod(-1.0, X5[0]));



            #endregion
            INumExpr[] expr21 = new INumExpr[1];
            expr21[0] = Model.Prod(Model.Sum(expr15[0], Model.Prod(expr17[0], wday), expr18[0], expr19[0]), lambda); //

            INumExpr[] expr22 = new INumExpr[1];
            expr22[0] = Model.Prod(Model.Sum(expr11[0], expr12[0], expr13[0]), delta); // Model.Prod(Model.Prod(wday, Model.Sum(expr11[0], expr12[0], expr13[0])),delta);

            Model.AddMinimize(Model.Sum(expr21[0], expr22[0]));                        //

            Model.ExportModel("RLND.LP");

            if (Model.Solve())
            {
                Console.WriteLine("statue=" + Model.GetStatus());
                Console.WriteLine("obj=" + Model.ObjValue);
                Console.WriteLine("X2的结果");

                for (int aa2 = 0; aa2 < period; aa2++)
                {
                    for (int bb2 = 0; bb2 < ptype; bb2++)
                    {
                        for (int cc = 0; cc < cpoint; cc++)
                        {
                            for (int dd = 0; dd < rcenter; dd++)
                            {
                                for (int ee = 0; ee < scenario; ee++)
                                {
                                    Console.WriteLine(Model.GetValue(X2[aa2][bb2][cc][dd][ee]));
                                    Console.WriteLine();
                                }
                            }
                        }
                    }
                }

                //for (int a = 0; a < X6.Length; a++)
                //{
                //    Console.WriteLine("result[" + a + "] = " + Model.GetValue(X6[a]));
                //}
                //Console.WriteLine();


                Model.End();
            }
            else
            {
                Model.End();
                Console.WriteLine();
                Console.WriteLine("cannot be solved");
            }
        }
Exemple #58
0
    /// <summary>
    /// The example's main function.
    /// </summary>
    public static void Main(string[] args)
    {
        int   retval = 0;
        Cplex cplex  = null;

        try
        {
            cplex = new Cplex();

            /* ***************************************************************** *
            *                                                                   *
            *    S E T U P   P R O B L E M                                      *
            *                                                                   *
            *  We create the following problem:                                 *
            * Minimize                                                          *
            *  obj: 3x1 - x2 + 3x3 + 2x4 + x5 + 2x6 + 4x7                       *
            * Subject To                                                        *
            *  c1: x1 + x2 = 4                                                  *
            *  c2: x1 + x3 >= 3                                                 *
            *  c3: x6 + x7 <= 5                                                 *
            *  c4: -x1 + x7 >= -2                                               *
            *  q1: [ -x1^2 + x2^2 ] <= 0                                        *
            *  q2: [ 4.25x3^2 -2x3*x4 + 4.25x4^2 - 2x4*x5 + 4x5^2  ] + 2 x1 <= 9.0
            *  q3: [ x6^2 - x7^2 ] >= 4                                         *
            * Bounds                                                            *
            *  0 <= x1 <= 3                                                     *
            *  x2 Free                                                          *
            *  0 <= x3 <= 0.5                                                   *
            *  x4 Free                                                          *
            *  x5 Free                                                          *
            *  x7 Free                                                          *
            * End                                                               *
            *                                                                   *
            * ***************************************************************** */

            INumVar[] x = new INumVar[7];
            x[0] = cplex.NumVar(0, 3, "x1");
            x[1] = cplex.NumVar(System.Double.NegativeInfinity, System.Double.PositiveInfinity, "x2");
            x[2] = cplex.NumVar(0, 0.5, "x3");
            x[3] = cplex.NumVar(System.Double.NegativeInfinity, System.Double.PositiveInfinity, "x4");
            x[4] = cplex.NumVar(System.Double.NegativeInfinity, System.Double.PositiveInfinity, "x5");
            x[5] = cplex.NumVar(0, System.Double.PositiveInfinity, "x6");
            x[6] = cplex.NumVar(System.Double.NegativeInfinity, System.Double.PositiveInfinity, "x7");

            IRange[] linear = new IRange[4];
            linear[0] = cplex.AddEq(cplex.Sum(x[0], x[1]), 4.0, "c1");
            linear[1] = cplex.AddGe(cplex.Sum(x[0], x[2]), 3.0, "c2");
            linear[2] = cplex.AddLe(cplex.Sum(x[5], x[6]), 5.0, "c3");
            linear[3] = cplex.AddGe(cplex.Diff(x[6], x[0]), -2.0, "c4");

            IRange[] quad = new IRange[3];
            quad[0] = cplex.AddLe(cplex.Sum(cplex.Prod(-1, x[0], x[0]),
                                            cplex.Prod(x[1], x[1])), 0.0, "q1");
            quad[1] = cplex.AddLe(cplex.Sum(cplex.Prod(4.25, x[2], x[2]),
                                            cplex.Prod(-2, x[2], x[3]),
                                            cplex.Prod(4.25, x[3], x[3]),
                                            cplex.Prod(-2, x[3], x[4]),
                                            cplex.Prod(4, x[4], x[4]),
                                            cplex.Prod(2, x[0])), 9.0, "q2");
            quad[2] = cplex.AddGe(cplex.Sum(cplex.Prod(x[5], x[5]),
                                            cplex.Prod(-1, x[6], x[6])), 4.0, "q3");

            cplex.AddMinimize(cplex.Sum(cplex.Prod(3.0, x[0]),
                                        cplex.Prod(-1.0, x[1]),
                                        cplex.Prod(3.0, x[2]),
                                        cplex.Prod(2.0, x[3]),
                                        cplex.Prod(1.0, x[4]),
                                        cplex.Prod(2.0, x[5]),
                                        cplex.Prod(4.0, x[6])), "obj");

            /* ***************************************************************** *
            *                                                                   *
            *    O P T I M I Z E   P R O B L E M                                *
            *                                                                   *
            * ***************************************************************** */
            cplex.SetParam(Cplex.Param.Barrier.QCPConvergeTol, 1e-10);
            cplex.Solve();

            /* ***************************************************************** *
            *                                                                   *
            *    Q U E R Y   S O L U T I O N                                    *
            *                                                                   *
            * ***************************************************************** */
            double[] xval   = cplex.GetValues(x);
            double[] slack  = cplex.GetSlacks(linear);
            double[] qslack = cplex.GetSlacks(quad);
            double[] cpi    = cplex.GetReducedCosts(x);
            double[] rpi    = cplex.GetDuals(linear);
            double[] qpi    = getqconstrmultipliers(cplex, xval, ZEROTOL, x, quad);
            // Also store solution in a dictionary so that we can look up
            // values by variable and not only by index.
            IDictionary <INumVar, System.Double> xmap = new Dictionary <INumVar, System.Double>();
            for (int j = 0; j < x.Length; ++j)
            {
                xmap.Add(x[j], xval[j]);
            }

            /* ***************************************************************** *
            *                                                                   *
            *    C H E C K   K K T   C O N D I T I O N S                        *
            *                                                                   *
            *    Here we verify that the optimal solution computed by CPLEX     *
            *    (and the qpi[] values computed above) satisfy the KKT          *
            *    conditions.                                                    *
            *                                                                   *
            * ***************************************************************** */

            // Primal feasibility: This example is about duals so we skip this test.

            // Dual feasibility: We must verify
            // - for <= constraints (linear or quadratic) the dual
            //   multiplier is non-positive.
            // - for >= constraints (linear or quadratic) the dual
            //   multiplier is non-negative.
            for (int i = 0; i < linear.Length; ++i)
            {
                if (linear[i].LB <= System.Double.NegativeInfinity)
                {
                    // <= constraint
                    if (rpi[i] > ZEROTOL)
                    {
                        throw new System.SystemException("Dual feasibility test failed for row " + linear[i]
                                                         + ": " + rpi[i]);
                    }
                }
                else if (linear[i].UB >= System.Double.PositiveInfinity)
                {
                    // >= constraint
                    if (rpi[i] < -ZEROTOL)
                    {
                        throw new System.SystemException("Dual feasibility test failed for row " + linear[i]
                                                         + ": " + rpi[i]);
                    }
                }
                else
                {
                    // nothing to do for equality constraints
                }
            }
            for (int i = 0; i < quad.Length; ++i)
            {
                if (quad[i].LB <= System.Double.NegativeInfinity)
                {
                    // <= constraint
                    if (qpi[i] > ZEROTOL)
                    {
                        throw new System.SystemException("Dual feasibility test failed for quad " + quad[i]
                                                         + ": " + qpi[i]);
                    }
                }
                else if (quad[i].UB >= System.Double.PositiveInfinity)
                {
                    // >= constraint
                    if (qpi[i] < -ZEROTOL)
                    {
                        throw new System.SystemException("Dual feasibility test failed for quad " + quad[i]
                                                         + ": " + qpi[i]);
                    }
                }
                else
                {
                    // nothing to do for equality constraints
                }
            }

            // Complementary slackness.
            // For any constraint the product of primal slack and dual multiplier
            // must be 0.
            for (int i = 0; i < linear.Length; ++i)
            {
                if (System.Math.Abs(linear[i].UB - linear[i].LB) > ZEROTOL &&
                    System.Math.Abs(slack[i] * rpi[i]) > ZEROTOL)
                {
                    throw new System.SystemException("Complementary slackness test failed for row " + linear[i]
                                                     + ": " + System.Math.Abs(slack[i] * rpi[i]));
                }
            }
            for (int i = 0; i < quad.Length; ++i)
            {
                if (System.Math.Abs(quad[i].UB - quad[i].LB) > ZEROTOL &&
                    System.Math.Abs(qslack[i] * qpi[i]) > ZEROTOL)
                {
                    throw new System.SystemException("Complementary slackness test failed for quad " + quad[i]
                                                     + ": " + System.Math.Abs(qslack[i] * qpi[i]));
                }
            }
            for (int j = 0; j < x.Length; ++j)
            {
                if (x[j].UB < System.Double.PositiveInfinity)
                {
                    double slk  = x[j].UB - xval[j];
                    double dual = cpi[j] < -ZEROTOL ? cpi[j] : 0.0;
                    if (System.Math.Abs(slk * dual) > ZEROTOL)
                    {
                        throw new System.SystemException("Complementary slackness test failed for column " + x[j]
                                                         + ": " + System.Math.Abs(slk * dual));
                    }
                }
                if (x[j].LB > System.Double.NegativeInfinity)
                {
                    double slk  = xval[j] - x[j].LB;
                    double dual = cpi[j] > ZEROTOL ? cpi[j] : 0.0;
                    if (System.Math.Abs(slk * dual) > ZEROTOL)
                    {
                        throw new System.SystemException("Complementary slackness test failed for column " + x[j]
                                                         + ": " + System.Math.Abs(slk * dual));
                    }
                }
            }

            // Stationarity.
            // The difference between objective function and gradient at optimal
            // solution multiplied by dual multipliers must be 0, i.E., for the
            // optimal solution x
            // 0 == c
            //      - sum(r in rows)  r'(x)*rpi[r]
            //      - sum(q in quads) q'(x)*qpi[q]
            //      - sum(c in cols)  b'(x)*cpi[c]
            // where r' and q' are the derivatives of a row or quadratic constraint,
            // x is the optimal solution and rpi[r] and qpi[q] are the dual
            // multipliers for row r and quadratic constraint q.
            // b' is the derivative of a bound constraint and cpi[c] the dual bound
            // multiplier for column c.
            IDictionary <INumVar, System.Double> kktsum = new Dictionary <INumVar, System.Double>();
            for (int j = 0; j < x.Length; ++j)
            {
                kktsum.Add(x[j], 0.0);
            }

            // Objective function.
            for (ILinearNumExprEnumerator it = ((ILinearNumExpr)cplex.GetObjective().Expr).GetLinearEnumerator();
                 it.MoveNext(); /* nothing */)
            {
                kktsum[it.NumVar] = it.Value;
            }

            // Linear constraints.
            // The derivative of a linear constraint ax - b (<)= 0 is just a.
            for (int i = 0; i < linear.Length; ++i)
            {
                for (ILinearNumExprEnumerator it = ((ILinearNumExpr)linear[i].Expr).GetLinearEnumerator();
                     it.MoveNext(); /* nothing */)
                {
                    kktsum[it.NumVar] = kktsum[it.NumVar] - rpi[i] * it.Value;
                }
            }

            // Quadratic constraints.
            // The derivative of a constraint xQx + ax - b <= 0 is
            // Qx + Q'x + a.
            for (int i = 0; i < quad.Length; ++i)
            {
                for (ILinearNumExprEnumerator it = ((ILinearNumExpr)quad[i].Expr).GetLinearEnumerator();
                     it.MoveNext(); /* nothing */)
                {
                    kktsum[it.NumVar] = kktsum[it.NumVar] - qpi[i] * it.Value;
                }
                for (IQuadNumExprEnumerator it = ((IQuadNumExpr)quad[i].Expr).GetQuadEnumerator();
                     it.MoveNext(); /* nothing */)
                {
                    INumVar v1 = it.NumVar1;
                    INumVar v2 = it.NumVar2;
                    kktsum[v1] = kktsum[v1] - qpi[i] * xmap[v2] * it.Value;
                    kktsum[v2] = kktsum[v2] - qpi[i] * xmap[v1] * it.Value;
                }
            }

            // Bounds.
            // The derivative for lower bounds is -1 and that for upper bounds
            // is 1.
            // CPLEX already returns dj with the appropriate sign so there is
            // no need to distinguish between different bound types here.
            for (int j = 0; j < x.Length; ++j)
            {
                kktsum[x[j]] = kktsum[x[j]] - cpi[j];
            }

            foreach (INumVar v in x)
            {
                if (System.Math.Abs(kktsum[v]) > ZEROTOL)
                {
                    throw new System.SystemException("Stationarity test failed at " + v
                                                     + ": " + System.Math.Abs(kktsum[v]));
                }
            }

            // KKT conditions satisfied. Dump out the optimal solutions and
            // the dual values.
            System.Console.WriteLine("Optimal solution satisfies KKT conditions.");
            System.Console.WriteLine("   x[] = " + arrayToString(xval));
            System.Console.WriteLine(" cpi[] = " + arrayToString(cpi));
            System.Console.WriteLine(" rpi[] = " + arrayToString(rpi));
            System.Console.WriteLine(" qpi[] = " + arrayToString(qpi));
        }
        catch (ILOG.Concert.Exception e)
        {
            System.Console.WriteLine("IloException: " + e.Message);
            System.Console.WriteLine(e.StackTrace);
            retval = -1;
        }
        finally
        {
            if (cplex != null)
            {
                cplex.End();
            }
        }
        System.Environment.Exit(retval);
    }
Exemple #59
0
    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");
        }
    }
Exemple #60
0
    public static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            Usage();
            return;
        }
        try {
            Cplex cplex = new Cplex();

            // Evaluate command line option and set optimization method accordingly.
            switch (args[1].ToCharArray()[0])
            {
            case 'o': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Auto);
                break;

            case 'p': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Primal);
                break;

            case 'd': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Dual);
                break;

            case 'b': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Barrier);
                cplex.SetParam(Cplex.Param.Barrier.Crossover,
                               Cplex.Algorithm.None);
                break;

            case 'n': cplex.SetParam(Cplex.Param.RootAlgorithm,
                                     Cplex.Algorithm.Network);
                break;

            default:  Usage();
                return;
            }

            cplex.ImportModel(args[0]);


            if (cplex.Solve())
            {
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine("Solution value  = " + cplex.ObjValue);

                IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator();
                matrixEnum.MoveNext();

                ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

                double[] x = cplex.GetValues(lp);
                for (int j = 0; j < x.Length; ++j)
                {
                    System.Console.WriteLine("Variable " + j + ": Value = " + x[j]);
                }
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }