Exemple #1
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 #2
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 #3
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 #4
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);
        }
    }
Exemple #5
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);
    }
        public void Build_RMP_YY(InitialSolution IS)//主问题的建模
        {
            initialPath_num    = IS.PathSet.Count;
            trip_num           = TripList.Count;
            realistic_trip_num = NetWork.num_Physical_trip;

            A_Matrix   = IS.A_Matrix;
            DvarSet    = new List <INumVar>(); //x
            CoefSet    = new List <double>();  //cij
            ObjCoefSet = new List <double>();
            PathSet    = new List <Pairing>(); //列池

            CoefSet = IS.Coefs;                //IS初始解
            PathSet = IS.PathSet;

            ObjCoefSet = IS.ObjCoefs;

            foreach (var p in PathSet)
            {
                ColumnPool.Add(p);
            }

            masterModel = new Cplex();
            Obj         = masterModel.AddMinimize();
            //Constraint = new IRange[realistic_trip_num];
            Ct_cover   = new IRange[NUMBER_CREW];
            Ct_crewNum = new IRange[5][]; //默认每条交路为5天
            ct_nb      = new List <IRange>();

            /**按行建模**/
            //vars and obj function
            int i, j;

            for (j = 0; j < initialPath_num; j++)                          //定义决策变量和目标函数
            {
                INumVar dvar = masterModel.NumVar(0, 1, NumVarType.Float); //INumVar-cplex里面的,定义决策变量。后面括号中的意思是定义var是0-1之间的浮点值
                dvar.Name = "crew_" + PathSet[j].Arcs.First().D_Point.CrewID + "_" + j;

                DvarSet.Add(dvar);
                Obj.Expr = masterModel.Sum(Obj.Expr, masterModel.Prod(CoefSet[j], DvarSet[j]));//后面的小括号里面是一个cij*xj,大括号里面的是累计,包括之前的expr
            }

            /*constraints*/

            //ct:每条交路每条担当的人数满足要求
            #region //该条约束不需要,因为输入已经决定了,只要有可行解,该条约束必然满足

            /*for (i = 0; i < 5; i++)//对每一天
             * {
             *  INumExpr expr = masterModel.NumExpr();
             *  Dictionary<int, List<int>> route_paths_map = new Dictionary<int, List<int>>();
             *  for (j = 0; j < initialPath_num; j++) //对每天的工作链分类
             *  {
             *      if (A_Matrix[j][i] == 0) {
             *          continue;
             *      }
             *      if (!route_paths_map.ContainsKey(A_Matrix[j][i])) {
             *          route_paths_map.Add(A_Matrix[j][i], new List<int>());
             *      }
             *      route_paths_map[A_Matrix[j][i]].Add(j);
             *  }
             *
             *  Ct_crewNum[i] = new IRange[route_paths_map.Count];
             *  foreach (var routePathsPair in route_paths_map) { //对第i天的每条交路
             *      foreach (var xj in routePathsPair.Value)
             *      {
             *          expr = masterModel.Sum(expr, DvarSet[xj]);
             *      }
             *
             *      Ct_crewNum[i][routePathsPair.Key-1] = masterModel.AddGe(expr, 1); //20191004 一条交路1个人 TODO
             *      string name = "day_" + i + "_route_" + routePathsPair.Key;
             *      Ct_crewNum[i][routePathsPair.Key-1].Name = name;
             *
             *      ct_nb.Add(Ct_crewNum[i][routePathsPair.Key - 1]);
             *  }
             * }
             */
            #endregion

            // ct:每个乘务员只能有一条工作链
            Dictionary <int, List <int> > crewID_paths_map = new Dictionary <int, List <int> >();
            for (j = 0; j < initialPath_num; j++)
            {
                Pairing path    = PathSet[j];
                int     crew_id = path.crewID;
                if (!crewID_paths_map.ContainsKey(crew_id))
                {
                    crewID_paths_map.Add(crew_id, new List <int>());
                }
                crewID_paths_map[crew_id].Add(j);
            }
            if (crewID_paths_map.Count != NUMBER_CREW)
            {
                throw new System.Exception("乘务员数量有误");
            }

            foreach (var crewID_paths_pair in crewID_paths_map)
            {
                INumExpr expr = masterModel.NumExpr();
                foreach (var xj in crewID_paths_pair.Value)
                {
                    expr = masterModel.Sum(expr, DvarSet[xj]);
                }
                Ct_cover[crewID_paths_pair.Key - 1] = masterModel.AddEq(expr, 1);
            }
        }
Exemple #7
0
        /// <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

            //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 #8
0
        //Building initial model
        public static INumVar[] BuildModel(Cplex cplex, Instance instance, int nEdges)
        {
            //Init the model's variables
            INumVar[] x = new INumVar[(instance.NNodes - 1) * instance.NNodes / 2];

            /*
             * expr will hold all the expressions that needs to be added to the model
             * initially it will be the optimality's functions
             * later it will be Ax's rows
             */
            ILinearNumExpr expr = cplex.LinearNumExpr();


            //Populating objective function
            for (int i = 0; i < instance.NNodes; i++)
            {
                if (nEdges >= 0)
                {
                    List <int>[] listArray = BuildSL(instance);

                    //Only links (i,i) with i < i are correct
                    for (int j = i + 1; j < instance.NNodes; j++)
                    {
                        //xPos return the correct position where to store the variable corresponding to the actual link (i,i)
                        int position = xPos(i, j, instance.NNodes);
                        if ((listArray[i]).IndexOf(j) < nEdges)
                        {
                            x[position] = cplex.NumVar(0, 1, NumVarType.Bool, "x(" + (i + 1) + "," + (j + 1) + ")");
                        }
                        else
                        {
                            x[position] = cplex.NumVar(0, 0, NumVarType.Bool, "x(" + (i + 1) + "," + (j + 1) + ")");
                        }
                        expr.AddTerm(x[position], Point.Distance(instance.Coord[i], instance.Coord[j], instance.EdgeType));
                    }
                }
                else
                {
                    //Only links (i,i) with i < i are correct
                    for (int j = i + 1; j < instance.NNodes; j++)
                    {
                        //xPos return the correct position where to store the variable corresponding to the actual link (i,i)
                        int position = xPos(i, j, instance.NNodes);
                        x[position] = cplex.NumVar(0, 1, NumVarType.Bool, "x(" + (i + 1) + "," + (j + 1) + ")");
                        expr.AddTerm(x[position], Point.Distance(instance.Coord[i], instance.Coord[j], instance.EdgeType));
                    }
                }
            }

            //Setting the optimality's function
            cplex.AddMinimize(expr);


            //Starting to elaborate Ax
            for (int i = 0; i < instance.NNodes; i++)
            {
                //Resetting expr
                expr = cplex.LinearNumExpr();

                for (int j = 0; j < instance.NNodes; j++)
                {
                    //For each row i only the links (i,i) or (i,i) have coefficent 1
                    //xPos return the correct position where link is stored inside the vector x
                    if (i != j)//No loops wioth only one node
                    {
                        expr.AddTerm(x[xPos(i, j, instance.NNodes)], 1);
                    }
                }

                //Adding to Ax the current equation with known term 2 and name degree(<current i node>)
                cplex.AddEq(expr, 2, "degree(" + (i + 1) + ")");
            }

            //Printing the complete model inside the file <name_file.tsp.lp>
            if (Program.VERBOSE >= -1)
            {
                cplex.ExportModel(instance.InputFile + ".lp");
            }

            return(x);
        }
Exemple #9
0
        private double one_tsp(int dim, int [][] matrix, int [] path)
        {
            int[] lo = new int[dim];

            for (int i = 0; i < dim; i++)
            {
                lo[i] = 1;
            }

            Cplex      cplex   = new Cplex();
            NumVarType varType = NumVarType.Bool;

            INumVar[][] x = new INumVar[dim][];
            for (int i = 0; i < dim; i++)
            {
                x[i] = cplex.NumVarArray(dim, 0, 1);
            }

            for (int i = 0; i < dim; i++)
            {
                for (int j = 0; j < dim; j++)
                {
                    x[i][j] = cplex.BoolVar();
                }
            }

            for (int j = 0; j < dim; j++)
            {
                INumExpr xcolSum = cplex.NumExpr();
                for (int i = 0; i < dim; i++)
                {
                    xcolSum = cplex.Sum(xcolSum, x[i][j]);
                }
                cplex.AddEq(lo[j], xcolSum);
            }

            varType = NumVarType.Float;
            INumVar[] u = new INumVar[dim];
            for (int j = 0; j < dim; j++)
            {
                u[j] = cplex.NumVar(0, 100000);
            }

            for (int j = 1; j < dim; j++)
            {
                cplex.AddGe(u[j], 0);
            }

            for (int i = 1; i < dim; i++)
            {
                for (int j = 1; j < dim; j++)
                {
                    if (i != j)
                    {
                        cplex.AddLe(cplex.Sum(cplex.Diff(u[i], u[j]), cplex.Prod(dim, x[i][j])), dim - 1);
                    }
                }
            }

            for (int i = 0; i < dim; i++)
            {
                INumExpr xrowSum = cplex.NumExpr();
                for (int j = 0; j < dim; j++)
                {
                    xrowSum = cplex.Sum(xrowSum, x[i][j]);
                }
                cplex.AddEq(lo[i], xrowSum);
            }

            INumExpr costSum = cplex.NumExpr();

            for (int i = 0; i < dim; i++)
            {
                for (int j = 0; j < dim; j++)
                {
                    costSum = cplex.Sum(costSum, cplex.Prod(x[i][j], matrix[i][j]));
                }
            }
            cplex.AddMinimize(costSum);

            try
            {
                if (cplex.Solve())
                {
                    //MessageBox.Show("Solution status = " + cplex.GetStatus());
                    //MessageBox.Show("cost = " + cplex.ObjValue);
                    int ipath = 0;
                    int depo  = -1;
                    for (int i = dim - 1; i >= 0; i--)
                    {
                        for (int j = 0; j < dim; j++)
                        {
                            if (Convert.ToInt16(cplex.GetValue(x[i][j])) == 1)
                            {
                                depo = i;
                            }
                        }
                    }
                    path[ipath] = depo;
                    ipath++;
                    while (depo > -1)
                    {
                        for (int j = 0; j < dim; j++)
                        {
                            if (Convert.ToInt16(cplex.GetValue(x[path[ipath - 1]][j])) == 1)
                            {
                                path[ipath] = j;
                                ipath++;
                                if (j == depo)
                                {
                                    depo = -1;
                                }
                                break;
                            }
                        }
                    }
                    return(cplex.ObjValue);
                }
                cplex.End();
            }
            catch (ILOG.Concert.Exception ex)
            {
                System.Console.WriteLine("Concert Error: " + ex);
            }
            return(-1);
        }
Exemple #10
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();
            }
        }
    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 #12
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();
        }
        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 #14
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 #15
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 #16
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.NumVarArray(_nbIngot, 0.0, System.Double.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 Solution");
                    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 #17
0
        private void decomp(int dim, int kts, int[][] dist, List <int> WorkList)
        {
            int[] lo = new int[dim];
            int   dk = dim * kts;

            for (int i = 0; i < dim; i++)
            {
                lo[i] = 1;
            }

            Cplex      cplex   = new Cplex();
            NumVarType varType = NumVarType.Bool;

            INumVar[][] x = new INumVar[dim][];
            for (int i = 0; i < dim; i++)
            {
                x[i] = cplex.NumVarArray(dk, 0, 1);
            }

            for (int i = 0; i < dim; i++)
            {
                for (int j = 0; j < dk; j++)
                {
                    x[i][j] = cplex.BoolVar();
                }
            }

            //****************************************
            //Что тут происходит?
            for (int j = 0; j < dim; j++)
            {
                INumExpr xcolSum = cplex.NumExpr();
                for (int k = 0; k < kts; k++)
                {
                    for (int i = 0; i < dim; i++)
                    {
                        xcolSum = cplex.Sum(xcolSum, x[i][k * dim + j]);
                    }
                }
                cplex.AddEq(lo[j], xcolSum);
            }

            varType = NumVarType.Float;
            INumVar[] u = new INumVar[dk];
            for (int j = 0; j < dk; j++)
            {
                u[j] = cplex.NumVar(0, 100000);
            }

            for (int j = 1; j < dk; j++)
            {
                cplex.AddGe(u[j], 0);
            }

            for (int k = 0; k < kts; k++)
            {
                for (int i = 1; i < dim; i++)
                {
                    for (int j = 1; j < dim; j++)
                    {
                        if (i != j)
                        {
                            if (kts == 1)
                            {
                                cplex.AddLe(cplex.Sum(cplex.Diff(u[k * dim + i], u[k * dim + j]), cplex.Prod(dim, x[i][k * dim + j])), dim - 1);
                            }
                            else
                            {
                                cplex.AddLe(cplex.Sum(cplex.Diff(u[k * dim + i], u[k * dim + j]), cplex.Prod(dim, x[i][k * dim + j])), dim);
                            }
                        }
                    }
                }
            }

            for (int i = 0; i < dim; i++)
            {
                INumExpr xrowSum = cplex.NumExpr();
                for (int j = 0; j < dk; j++)
                {
                    xrowSum = cplex.Sum(xrowSum, x[i][j]);
                }
                cplex.AddEq(lo[i], xrowSum);
            }

            //Условия независимости кластеров
            if (kts > 1)
            {
                int[] a = new int[kts + 1];
                for (int k = 1; k < kts; k++)
                {
                    if (k > 1 && k < kts - 1)
                    {
                        continue;
                    }
                    int p;
                    for (int i = 1; i <= k; i++)
                    {
                        a[i] = i;
                    }
                    p = k;
                    while (p >= 1)
                    {
                        for (int m = 0; m < dim; m++)
                        {
                            INumExpr xcolrowSum = cplex.NumExpr();
                            for (int j = 1; j <= kts; j++)
                            {
                                bool row = false;
                                for (int i = 1; i <= k; i++)
                                {
                                    if (a[i] == j)
                                    {
                                        row = true;
                                    }
                                }
                                if (row)
                                {
                                    for (int t = 0; t < dim; t++)
                                    {
                                        xcolrowSum = cplex.Sum(xcolrowSum, x[m][(j - 1) * dim + t]);
                                    }
                                }
                                else
                                {
                                    for (int t = 0; t < dim; t++)
                                    {
                                        xcolrowSum = cplex.Sum(xcolrowSum, x[t][(j - 1) * dim + m]);
                                    }
                                }
                            }
                            cplex.AddLe(xcolrowSum, lo[m]);
                        }
                        if (a[k] == kts)
                        {
                            p--;
                        }
                        else
                        {
                            p = k;
                        }
                        if (p >= 1)
                        {
                            for (int i = k; i >= p; i--)
                            {
                                a[i] = a[p] + i - p + 1;
                            }
                        }
                    }
                }
            }

            INumExpr costSum = cplex.NumExpr();

            INumExpr[] costSum1 = new INumExpr[kts];

            if (kts == 1)
            {
                for (int i = 0; i < dim; i++)
                {
                    for (int j = 0; j < dim; j++)
                    {
                        costSum = cplex.Sum(costSum, cplex.Prod(x[i][j], dist[i][j]));
                    }
                }
                cplex.AddMinimize(costSum);
            }
            else
            {
                for (int k = 0; k < kts; k++)
                {
                    costSum1[k] = cplex.NumExpr();
                    for (int i = 0; i < dim; i++)
                    {
                        for (int j = 0; j < dim; j++)
                        {
                            costSum1[k] = cplex.Sum(costSum1[k], cplex.Prod(x[i][k * dim + j], dist[i][j]));
                        }
                    }
                    //cplex.AddLe(costSum1[k], costSum);
                }
                costSum = cplex.Max(costSum1);
                cplex.AddMinimize(costSum);
            }

            try
            {
                if (cplex.Solve())
                {
                    textBox1.Text += "lambda = " + cplex.ObjValue + Environment.NewLine;
                    textBox1.Text += DateTime.Now.ToString() + Environment.NewLine;

                    WorkList.Clear();
                    int num_clust = 0;
                    for (int k = 0; k < kts; k++)
                    {
                        int dim1 = 0;
                        for (int i = 0; i < dim; i++)
                        {
                            for (int j = 0; j < dim; j++)
                            {
                                if (Convert.ToInt16(cplex.GetValue(x[i][k * dim + j])) == 1)
                                {
                                    dim1++;
                                }
                            }
                        }

                        if (dim1 > 0)
                        {
                            num_clust++;
                            for (int i = 0; i < dim; i++)
                            {
                                for (int j = 0; j < dim; j++)
                                {
                                    if (Convert.ToInt16(cplex.GetValue(x[i][k * dim + j])) == 1)
                                    {
                                        WorkList.Add(i);
                                        break;
                                    }
                                }
                            }

                            WorkList.Add(-1);
                        }
                    }
                    textBox1.Text += DateTime.Now.ToString() + Environment.NewLine;
                }
                else
                {
                    textBox1.Text += "Нет решения" + Environment.NewLine;
                    textBox1.Text += DateTime.Now.ToString() + Environment.NewLine;
                }
                cplex.End();
            }
            catch (ILOG.Concert.Exception ex)
            {
                textBox1.Text += "Concert Error: " + ex + Environment.NewLine;
                textBox1.Text += DateTime.Now.ToString() + Environment.NewLine;
            }
        }
        static void Main(string[] args)
        {
            double[] Demand = new double[] { 15, 18, 14, 20 };
            double[] Capacity = new double[] { 20, 22, 17, 19, 18 };
            double[,] ShipCosts =
                new double[,] { { 4000, 2500, 1200, 2200 }, 
                { 2000, 2600, 1800, 2600 }, 
                { 3000, 3400, 2600, 3100 }, 
                { 2500, 3000, 4100, 3700 },
                { 4500, 4000, 3000, 3200 } };
            int nWarehouses = Capacity.Length;
            int nCustomers = Demand.Length;

            Cplex m = new Cplex();

            INumVar[,] Ship = new INumVar[nWarehouses, nCustomers];
            for (int i = 0; i < nWarehouses; ++i)
                for (int j = 0; j < nCustomers; ++j)
                    Ship[i, j] = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "ship." + i + "." + j);

            INumVar[] Shortage = new INumVar[nCustomers];
            for (int j = 0; j < nCustomers; ++j)
                Shortage[j] = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "shortage." + j);

            INumVar TotalShortage = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "TotalShortage");
            INumVar TotalShippingCost = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "TotalShippingCost");
            IObjective obj = m.AddMinimize(TotalShippingCost);

            IConstraint[] DemandCon = new IConstraint[nCustomers];
            for (int j = 0; j < nCustomers; ++j)
            {
                INumExpr lhs = m.LinearNumExpr(0.0);
                INumExpr rhs = m.LinearNumExpr(Demand[j]);
                for (int i = 0; i < nWarehouses; ++i)
                    lhs = m.Sum(lhs, Ship[i, j]);
                lhs = m.Sum(lhs, Shortage[j]);
                DemandCon[j] = m.AddEq(lhs, rhs, "demand." + j);
            }

            IConstraint[] CapacityCon = new IConstraint[nWarehouses];
            for (int i = 0; i < nWarehouses; ++i)
            {
                INumExpr lhs = m.LinearNumExpr(0.0);
                for (int j = 0; j < nCustomers; ++j)
                    lhs = m.Sum(lhs, Ship[i, j]);
                CapacityCon[i] = m.AddLe(lhs, Capacity[i], "capacity." + i);
            }

            INumExpr expr = m.Sum(Shortage);
            IConstraint TotalShortageCon = m.AddEq(expr, TotalShortage, "total_shortage");

            expr = m.LinearNumExpr(0.0);
            for (int i = 0; i < nWarehouses; ++i)
                for (int j = 0; j < nCustomers; ++j)
                    expr = m.Sum(expr, m.Prod(ShipCosts[i, j], Ship[i, j]));
            IConstraint TotalShippingCon = m.AddEq(expr, TotalShippingCost, "total_shipping");
            m.ExportModel("Facility.lp");
            while (true)
            {
                Console.WriteLine("\nSolver Output:");
                m.Solve();
                double OptShortage = m.GetValue(TotalShortage);
                double OptShipping = m.GetValue(TotalShippingCost);
                Console.WriteLine("\nFacility Program Output:");
                Console.WriteLine("\nTotalShortage = {0}", OptShortage);
                Console.WriteLine("TotalShippingCost= {0}\n", OptShipping);
                if (OptShortage < EPS) break;
                INumVar[] varArr = new INumVar[26];
                double[] ubs = new double[26];
                double[] lbs = new double[26];
                varArr[0] = TotalShortage;
                varArr[1] = TotalShippingCost;
                for (int i = 0; i < nWarehouses; ++i)
                    for (int j = 0; j < nCustomers; ++j)
                        varArr[4 * i + j + 2] = Ship[i, j];
                for (int j = 0; j < nCustomers; ++j)
                    varArr[j + 22] = Shortage[j];
                m.GetObjSA(lbs, ubs, varArr);
                double ObjectiveBound = ubs[0];
                m.SetLinearCoef(obj, ((1 + EPS) * ObjectiveBound), TotalShortage);
            } // end while

            for (int i = 0; i < nWarehouses; ++i)
                for (int j = 0; j < nCustomers; ++j)
                    Console.WriteLine("{0} = {1}", Ship[i, j].Name, m.GetValue(Ship[i, j]));
            for (int j = 0; j < nCustomers; ++j)
                Console.WriteLine("{0} = {1}", Shortage[j].Name, m.GetValue(Shortage[j]));
            Console.WriteLine("{0} = {1}", TotalShortage.Name, m.GetValue(TotalShortage));
            Console.WriteLine("{0} = {1}", TotalShippingCost.Name, m.GetValue(TotalShippingCost));
        } // end Main
Exemple #19
0
        /// <summary>
        /// Getting maximum congruency for naming parameter sets A or B. Linear Programming optimization model.
        /// Eq. (4) and Table II in DOI:10.1109/CEC.2019.8790261
        /// The matrices need to be manually entered here in the script (cTopA, cTopB, cBtmA, cBtmB)
        /// </summary>
        internal static void IdentifyTwoBestParameterSets(string caseSolver)
        {
            Cplex cpl = new Cplex();

            int N = 7;

            //string caseSolver = "ES"; //"SGA" (default), "ES", "PSO", "FIPS"

            int[] cTopA;
            int[] cTopB;
            int[] cBtmA;
            int[] cBtmB;
            switch (caseSolver)
            {
            default:
                cTopA = new int[] { 11, 1, 1, 13, 0, 0, 2 };
                cTopB = new int[] { 0, 5, 3, 0, 5, 5, 5 };
                cBtmA = new int[] { 2, 12, 12, 0, 14, 14, 9 };
                cBtmB = new int[] { 4, 0, 1, 4, 0, 0, 0 };
                break;

            case "ES":
                cTopA = new int[] { 4, 6, 9, 3, 11, 11, 5 };
                cTopB = new int[] { 2, 3, 1, 3, 1, 3, 3 };
                cBtmA = new int[] { 4, 5, 2, 8, 0, 0, 6 };
                cBtmB = new int[] { 3, 1, 3, 2, 5, 3, 2 };
                break;

            case "PSO":
                cTopA = new int[] { 1, 3, 2, 3, 3, 7, 5 };
                cTopB = new int[] { 12, 11, 3, 1, 7, 8, 5 };
                cBtmA = new int[] { 7, 5, 6, 5, 5, 1, 3 };
                cBtmB = new int[] { 0, 1, 9, 11, 5, 4, 7 };
                break;

            case "FIPS":
                cTopA = new int[] { 6, 6, 7, 3, 5, 0, 8 };
                cTopB = new int[] { 4, 6, 6, 9, 5, 9, 1 };
                cBtmA = new int[] { 4, 4, 3, 7, 5, 10, 2 };
                cBtmB = new int[] { 6, 4, 4, 1, 5, 1, 9 };
                break;
            }


            INumVar[]      xTopA = new INumVar[N];
            INumVar[]      xBtmB = new INumVar[N];
            INumVar[]      xTopB = new INumVar[N];
            INumVar[]      xBtmA = new INumVar[N];
            ILinearNumExpr value = cpl.LinearNumExpr();

            for (int n = 0; n < N; n++)
            {
                xTopA[n] = cpl.BoolVar();
                xBtmB[n] = cpl.BoolVar();
                xTopB[n] = cpl.BoolVar();
                xBtmA[n] = cpl.BoolVar();
                cpl.AddEq(cpl.Sum(xTopB[n], xTopA[n]), 1);
                cpl.AddEq(cpl.Sum(xBtmA[n], xBtmB[n]), 1);
                cpl.AddEq(cpl.Sum(xTopA[n], xBtmA[n]), 1);
                cpl.AddEq(cpl.Sum(xTopB[n], xBtmB[n]), 1);
                value.AddTerm(xTopA[n], cTopA[n]);
                value.AddTerm(xTopB[n], cTopB[n]);
                value.AddTerm(xBtmA[n], cBtmA[n]);
                value.AddTerm(xBtmB[n], cBtmB[n]);
            }

            cpl.AddMaximize(value);
            cpl.Solve();

            Console.WriteLine("Parameter Grouping for Solver: {0}", caseSolver);
            for (int n = 0; n < N; n++)
            {
                Console.WriteLine("n: {0}", n);
                Console.WriteLine("xtopA: ;{0};, _____, xTopB: ;{1};", cpl.GetValue(xTopA[n]), cpl.GetValue(xTopB[n]));
                Console.WriteLine("xbtmB: ;{0};, _____, xBtmA: ;{1};", cpl.GetValue(xBtmB[n]), cpl.GetValue(xBtmA[n]));
            }
            Console.WriteLine("cost: {0}", cpl.GetObjValue());
            Console.ReadKey();
        }
Exemple #20
0
   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 #21
0
    public static void Main(string[] args)
    {
        if ( args.Length < 1 ) {
         System.Console.WriteLine("Usage: Transport <type>");
         System.Console.WriteLine("  type = 0 -> convex  piecewise linear model");
         System.Console.WriteLine("  type = 1 -> concave piecewise linear model");
         return;
         }

         try {
        Cplex cplex = new Cplex();

        int nbDemand = 4;
        int nbSupply = 3;
        double[] supply = {1000.0, 850.0, 1250.0};
        double[] demand = {900.0, 1200.0, 600.0, 400.0};

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

        for (int i = 0; i < nbSupply; i++) {
           x[i] = cplex.NumVarArray(nbDemand, 0.0, System.Double.MaxValue);
           y[i] = cplex.NumVarArray(nbDemand, 0.0, System.Double.MaxValue);
        }

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

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

        double[] points;
        double[] slopes;
        if ( args[0].ToCharArray()[0] == '0' ) {         // convex case
           points = new double[] {200.0, 400.0};
           slopes = new double[] { 30.0, 80.0, 130.0};
        }
        else {                                  // concave case
           points = new double[] {200.0, 400.0};
           slopes = new double[] {120.0, 80.0, 50.0};
        }
        for (int i = 0; i < nbSupply; ++i) {
           for (int j = 0; j < nbDemand; ++j) {
              cplex.AddEq(y[i][j],
                          cplex.PiecewiseLinear(x[i][j],
                                                points, slopes, 0.0, 0.0));
           }
        }

        ILinearNumExpr expr = cplex.LinearNumExpr();
        for (int i = 0; i < nbSupply; ++i) {
           for (int j = 0; j < nbDemand; ++j) {
              expr.AddTerm(y[i][j], 1.0);
           }
        }

        cplex.AddMinimize(expr);

        if ( cplex.Solve() ) {
           System.Console.WriteLine("Solution status = " + cplex.GetStatus());
           System.Console.WriteLine(" - Solution: ");
           for (int i = 0; i < nbSupply; ++i) {
              System.Console.Write("   " + i + ": ");
              for (int j = 0; j < nbDemand; ++j)
                 System.Console.Write("" + cplex.GetValue(x[i][j]) + "\t");
              System.Console.WriteLine();
           }
           System.Console.WriteLine("   Cost = " + cplex.ObjValue);
         }
         cplex.End();
          }
          catch (ILOG.Concert.Exception exc) {
         System.Console.WriteLine(exc);
          }
    }
Exemple #22
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 #23
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);
          }
    }
Exemple #24
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 #25
0
    public static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            System.Console.WriteLine("Usage: Transport <type>");
            System.Console.WriteLine("  type = 0 -> convex  piecewise linear model");
            System.Console.WriteLine("  type = 1 -> concave piecewise linear model");
            return;
        }

        try {
            Cplex cplex = new Cplex();

            int      nbDemand = 4;
            int      nbSupply = 3;
            double[] supply   = { 1000.0, 850.0, 1250.0 };
            double[] demand   = { 900.0, 1200.0, 600.0, 400.0 };

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

            for (int i = 0; i < nbSupply; i++)
            {
                x[i] = cplex.NumVarArray(nbDemand, 0.0, System.Double.MaxValue);
                y[i] = cplex.NumVarArray(nbDemand, 0.0, System.Double.MaxValue);
            }

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

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

            double[] points;
            double[] slopes;
            if (args[0].ToCharArray()[0] == '0')         // convex case
            {
                points = new double[] { 200.0, 400.0 };
                slopes = new double[] { 30.0, 80.0, 130.0 };
            }
            else                                // concave case
            {
                points = new double[] { 200.0, 400.0 };
                slopes = new double[] { 120.0, 80.0, 50.0 };
            }
            for (int i = 0; i < nbSupply; ++i)
            {
                for (int j = 0; j < nbDemand; ++j)
                {
                    cplex.AddEq(y[i][j],
                                cplex.PiecewiseLinear(x[i][j],
                                                      points, slopes, 0.0, 0.0));
                }
            }

            ILinearNumExpr expr = cplex.LinearNumExpr();
            for (int i = 0; i < nbSupply; ++i)
            {
                for (int j = 0; j < nbDemand; ++j)
                {
                    expr.AddTerm(y[i][j], 1.0);
                }
            }

            cplex.AddMinimize(expr);

            if (cplex.Solve())
            {
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine(" - Solution: ");
                for (int i = 0; i < nbSupply; ++i)
                {
                    System.Console.Write("   " + i + ": ");
                    for (int j = 0; j < nbDemand; ++j)
                    {
                        System.Console.Write("" + cplex.GetValue(x[i][j]) + "\t");
                    }
                    System.Console.WriteLine();
                }
                System.Console.WriteLine("   Cost = " + cplex.ObjValue);
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception exc) {
            System.Console.WriteLine(exc);
        }
    }
Exemple #26
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 #27
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 #28
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 #29
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 #30
0
        private void button1_Click(object sender, EventArgs e)
        {
            int[,] A = new int[, ]
            {
                { 1, 1, 1, 1, 0 },
                { 1, 1, 0, 1, 1 },
                { 0, 1, 1, 1, 1 }
            };

            double[] L = new double[] { 8, 5, 7, 8, 4 };

            double G = 10.7;

            double[] N_Max = new double[] { 2, 2, 2 };

            int nbOfWorkers = A.GetLength(0);
            int nbOfTasks   = A.GetLength(1);

            Cplex cplex = new Cplex();

            INumVar[,] X = new INumVar[nbOfWorkers, nbOfTasks];  // C라는 2차원 인덱스가 0이면, 행의 개수을 받겠다
            // C라는 2차원 인덱스가 1이면 열의 개수를 받겠다.
            for (int i = 0; i < A.GetLength(0); i++)
            {
                for (int j = 0; j < A.GetLength(1); j++)
                {
                    X[i, j] = cplex.BoolVar();
                }
            }

            List <INumVar> D_negative = new List <INumVar>();

            for (int i = 0; i < nbOfWorkers; i++)
            {
                D_negative.Add(cplex.NumVar(0, double.MaxValue));
            }


            List <INumVar> D_positive = new List <INumVar>();

            for (int i = 0; i < nbOfWorkers; i++)
            {
                D_positive.Add(cplex.NumVar(0, double.MaxValue));
            }

            //목적함수
            ILinearNumExpr objectiveFunction = cplex.LinearNumExpr();

            for (int i = 0; i < nbOfWorkers; i++)
            {
                objectiveFunction.AddTerm(1, D_negative[i]);
            }

            for (int i = 0; i < nbOfWorkers; i++)
            {
                objectiveFunction.AddTerm(1, D_positive[i]); // C[i, j], X[i, j] 두개를 곱해서 objectiveFunction 에 넣겠다.
            }
            //과제
            for (int i = 0; i < nbOfWorkers; i++)
            {
                ILinearNumExpr constLeft1 = cplex.LinearNumExpr();
                for (int j = 0; j < nbOfTasks; j++)
                {
                    constLeft1.AddTerm(L[j], X[i, j]);
                }
                constLeft1.AddTerm(1, D_negative[i]);
                constLeft1.AddTerm(-1, D_positive[i]);
                cplex.AddEq(constLeft1, G);
            }


            for (int j = 0; j < nbOfTasks; j++)
            {
                ILinearNumExpr constLeft2 = cplex.LinearNumExpr();
                for (int i = 0; i < X.GetLength(0); i++)
                {
                    constLeft2.AddTerm(1, X[i, j]);
                }
                cplex.AddEq(constLeft2, 1);
            }

            for (int i = 0; i < nbOfWorkers; i++)
            {
                for (int j = 0; j < nbOfTasks; j++)
                {
                    cplex.AddLe(X[i, j], A[i, j]);
                }
            }

            for (int i = 0; i < nbOfWorkers; i++)
            {
                ILinearNumExpr constLeft4 = cplex.LinearNumExpr();
                for (int j = 0; j < nbOfTasks; j++)
                {
                    constLeft4.AddTerm(1, X[i, j]);
                }
                cplex.AddLe(constLeft4, N_Max[i]);
            }

            cplex.AddMinimize(objectiveFunction);
            cplex.Solve();

            string solution  = "";
            double tolerance = cplex.GetParam(Cplex.Param.MIP.Tolerances.Integrality); //tolerance를 정의함

            for (int i = 0; i < A.GetLength(0); i++)
            {
                for (int j = 0; j < A.GetLength(1); j++)
                {
                    if (cplex.GetValue(X[i, j]) >= 1 - tolerance)
                    {
                        solution += "(" + (i + 1).ToString() + " ," + (j + 1).ToString() + ")";
                    }
                }
            }

            MessageBox.Show("목적함수 값은 =" + cplex.GetObjValue() + "\r\n" + "선택된 변수는 =" + solution);
        }