Пример #1
0
 static void Main(string[] args)
 {
     Cplex m = new Cplex();
     INumVar x1 = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "food.1");
     INumVar x2 = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "food.2");
     INumVar x3 = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "food.3");
     INumVar x4 = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "food.4");
     INumVar x5 = m.NumVar(0, System.Double.MaxValue, NumVarType.Float, "food.5");
     IObjective obj = m.AddMinimize(m.Sum(
         m.Prod(x1, 20), m.Prod(x2, 10), m.Prod(x3, 31), m.Prod(x4, 11), m.Prod(x5, 12)));
     INumExpr ironLHS = m.Sum(m.Prod(x1, 2), m.Prod(x3, 3), m.Prod(x4, 1), m.Prod(x5, 2));
     IRange con1 = m.AddGe(ironLHS, 21, "nutrient.iron");
     INumExpr calciumLHS = m.Sum(m.Prod(x2, 1), m.Prod(x3, 2), m.Prod(x4, 2), m.Prod(x5, 1));
     IRange con2 = m.AddGe(calciumLHS, 12, "nutrient.calcium");
     Console.WriteLine("**** Solver Output:\n");
     m.Solve();
     m.ExportModel("diet.lp");
     Console.WriteLine("\n**** Diet Program Output:\n");
     Console.WriteLine("Objective Value = {0}", m.GetObjValue());
     Console.WriteLine("{0} = {1}, reduced cost = {2}", x1.Name, m.GetValue(x1), m.GetReducedCost(x1));
     Console.WriteLine("{0} = {1}, reduced cost = {2}", x2.Name, m.GetValue(x2), m.GetReducedCost(x2));
     Console.WriteLine("{0} = {1}, reduced cost = {2}", x3.Name, m.GetValue(x3), m.GetReducedCost(x3));
     Console.WriteLine("{0} = {1}, reduced cost = {2}", x4.Name, m.GetValue(x4), m.GetReducedCost(x4));
     Console.WriteLine("{0} = {1}, reduced cost = {2}", x5.Name, m.GetValue(x5), m.GetReducedCost(x5));
     Console.WriteLine("{0}, slack = {1}, pi = {2}", con1.Name, m.GetSlack(con1), m.GetDual(con1));
     Console.WriteLine("{0}, slack = {1}, pi = {2}", con2.Name, m.GetSlack(con2), m.GetDual(con2));
     m.End();
 }
Пример #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);
          }
    }
Пример #3
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");
          }
    }
Пример #4
0
    public static void Main( string[] args )
    {
        try {
         Cplex cplex = new Cplex();

         INumVar[]  inside = new INumVar[_nbProds];
         INumVar[] outside = new INumVar[_nbProds];

         IObjective obj = cplex.AddMinimize();

         // Must meet demand for each product

         for(int p = 0; p < _nbProds; p++) {
            IRange demRange = cplex.AddRange(_demand[p], _demand[p]);
            inside[p] = cplex.NumVar(cplex.Column(obj, _insideCost[p]).And(
                                     cplex.Column(demRange, 1.0)),
                                     0.0, System.Double.MaxValue);

            outside[p] = cplex.NumVar(cplex.Column(obj, _outsideCost[p]).And(
                                      cplex.Column(demRange, 1.0)),
                                      0.0, System.Double.MaxValue);
         }

         // Must respect capacity constraint for each resource

         for(int r = 0; r < _nbResources; r++)
            cplex.AddLe(cplex.ScalProd(_consumption[r], inside), _capacity[r]);

         cplex.Solve();

         if ( !cplex.GetStatus().Equals(Cplex.Status.Optimal) ) {
            System.Console.WriteLine("No optimal solution found");
            return;
         }

         System.Console.WriteLine("Solution status = " + cplex.GetStatus());
         DisplayResults(cplex, inside, outside);
         System.Console.WriteLine("----------------------------------------");
         cplex.End();
          }
          catch (ILOG.Concert.Exception exc) {
         System.Console.WriteLine("Concert exception '" + exc + "' caught");
          }
    }
Пример #5
0
    public static void Main( string[] args )
    {
        try {
         string filename = "../../../../examples/data/rates.dat";
         if (args.Length > 0)
            filename = args[0];
         ReadData(filename);

         Cplex cplex = new Cplex();

         INumVar[] production = new INumVar[_generators];
         for (int j = 0; j < _generators; ++j) {
            production[j] = cplex.SemiContVar(_minArray[j], _maxArray[j],
                                              NumVarType.Float);
         }

         cplex.AddMinimize(cplex.ScalProd(_cost, production));
         cplex.AddGe(cplex.Sum(production), _demand);

         cplex.ExportModel("rates.lp");
         if ( cplex.Solve() ) {
            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            for (int j = 0; j < _generators; ++j) {
               System.Console.WriteLine("   generator " + j + ": " +
                                  cplex.GetValue(production[j]));
            }
            System.Console.WriteLine("Total cost = " + cplex.ObjValue);
         }
         else
            System.Console.WriteLine("No solution");

         cplex.End();
          }
          catch (ILOG.Concert.Exception exc) {
         System.Console.WriteLine("Concert exception '" + exc + "' caught");
          }
          catch (System.IO.IOException exc) {
         System.Console.WriteLine("Error reading file " + args[0] + ": " + exc);
          }
          catch (InputDataReader.InputDataReaderException exc) {
         System.Console.WriteLine(exc);
          }
    }
Пример #6
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");
          }
    }
Пример #7
0
    static void Main(string[] args)
    {
        try {
            string filename = "../../../../examples/data/etsp.dat";
            if (args.Length > 0)
            {
                filename = args[0];
            }

            Data  data  = new Data(filename);
            Cplex cplex = new Cplex();

            // Create start variables
            INumVar[][] s = new INumVar[data.nJobs][];
            for (int j = 0; j < data.nJobs; j++)
            {
                s[j] = cplex.NumVarArray(data.nResources, 0.0, Horizon);
            }

            // State precedence constraints
            for (int j = 0; j < data.nJobs; j++)
            {
                for (int i = 1; i < data.nResources; i++)
                {
                    cplex.AddGe(s[j][i], cplex.Sum(s[j][i - 1], data.duration[j][i - 1]));
                }
            }

            // State disjunctive constraints for each resource
            for (int i = 0; i < data.nResources; i++)
            {
                int end = data.nJobs - 1;
                for (int j = 0; j < end; j++)
                {
                    int a = data.activityOnResource[i][j];
                    for (int k = j + 1; k < data.nJobs; k++)
                    {
                        int b = data.activityOnResource[i][k];
                        cplex.Add(cplex.Or(
                                      cplex.Ge(s[j][a], cplex.Sum(s[k][b], data.duration[k][b])),
                                      cplex.Ge(s[k][b], cplex.Sum(s[j][a], data.duration[j][a]))
                                      ));
                    }
                }
            }

            // The cost is the sum of earliness or tardiness costs of each job
            int      last    = data.nResources - 1;
            INumExpr costSum = cplex.NumExpr();
            for (int j = 0; j < data.nJobs; j++)
            {
                double[] points = { data.dueDate[j] };
                double[] slopes = { -data.earlinessCost[j],
                                    data.tardinessCost[j] };
                costSum = cplex.Sum(costSum,
                                    cplex.PiecewiseLinear(
                                        cplex.Sum(s[j][last], data.duration[j][last]),
                                        points, slopes, data.dueDate[j], 0)
                                    );
            }
            cplex.AddMinimize(costSum);

            cplex.SetParam(Cplex.Param.Emphasis.MIP, 4);

            if (cplex.Solve())
            {
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine(" Optimal Value = " + cplex.ObjValue);
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
        catch (InputDataReader.InputDataReaderException ex) {
            System.Console.WriteLine("Data Error: " + ex);
        }
        catch (System.IO.IOException ex) {
            System.Console.WriteLine("IO Error: " + ex);
        }
    }
Пример #8
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");
            }
        }
Пример #9
0
    public static void Main(string[] args)
    {
        try {
            string datafile = "../../../../examples/data/cutstock.dat";
            if (args.Length > 0)
            {
                datafile = args[0];
            }
            ReadData(datafile);

            /// CUTTING-OPTIMIZATION PROBLEM ///

            Cplex cutSolver = new Cplex();

            IObjective RollsUsed = cutSolver.AddMinimize();
            IRange[]   Fill      = new IRange[_amount.Length];
            for (int f = 0; f < _amount.Length; f++)
            {
                Fill[f] = cutSolver.AddRange(_amount[f], System.Double.MaxValue);
            }

            System.Collections.ArrayList Cut = new System.Collections.ArrayList();

            int nWdth = _size.Length;
            for (int j = 0; j < nWdth; j++)
            {
                Cut.Add(cutSolver.NumVar(cutSolver.Column(RollsUsed, 1.0).And(
                                             cutSolver.Column(Fill[j],
                                                              (int)(_rollWidth / _size[j]))),
                                         0.0, System.Double.MaxValue));
            }

            cutSolver.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Primal);

            /// PATTERN-GENERATION PROBLEM ///

            Cplex patSolver = new Cplex();

            IObjective ReducedCost = patSolver.AddMinimize();
            INumVar[]  Use         = patSolver.NumVarArray(nWdth,
                                                           0.0, System.Double.MaxValue,
                                                           NumVarType.Int);
            patSolver.AddRange(-System.Double.MaxValue,
                               patSolver.ScalProd(_size, Use),
                               _rollWidth);

            /// COLUMN-GENERATION PROCEDURE ///

            double[] newPatt = new double[nWdth];

            /// COLUMN-GENERATION PROCEDURE ///

            for (;;)
            {
                /// OPTIMIZE OVER CURRENT PATTERNS ///

                cutSolver.Solve();
                Report1(cutSolver, Cut, Fill);

                /// FIND AND ADD A NEW PATTERN ///

                double[] price = cutSolver.GetDuals(Fill);
                ReducedCost.Expr = patSolver.Diff(1.0,
                                                  patSolver.ScalProd(Use, price));

                patSolver.Solve();
                Report2(patSolver, Use);

                if (patSolver.ObjValue > -RC_EPS)
                {
                    break;
                }

                newPatt = patSolver.GetValues(Use);

                Column column = cutSolver.Column(RollsUsed, 1.0);
                for (int p = 0; p < newPatt.Length; p++)
                {
                    column = column.And(cutSolver.Column(Fill[p], newPatt[p]));
                }

                Cut.Add(cutSolver.NumVar(column, 0.0, System.Double.MaxValue));
            }

            for (int i = 0; i < Cut.Count; i++)
            {
                cutSolver.Add(cutSolver.Conversion((INumVar)Cut[i],
                                                   NumVarType.Int));
            }

            cutSolver.Solve();
            System.Console.WriteLine("Solution status = " + cutSolver.GetStatus());
            Report3(cutSolver, Cut);

            cutSolver.End();
            patSolver.End();
        }
        catch (ILOG.Concert.Exception exc) {
            System.Console.WriteLine("Concert exception '" + exc + "' caught");
        }
        catch (System.IO.IOException exc) {
            System.Console.WriteLine("Error reading file " + args[0] + ": " + exc);
        }
        catch (InputDataReader.InputDataReaderException exc) {
            System.Console.WriteLine(exc);
        }
    }
Пример #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     Q = cplex.IntVar(1, 250, "Q");

                        for (int i = 0; i < data.n; i++)
                        {
                            x[i] = cplex.BoolVarArray(data.n);
                            cplex.Add(x[i]);
                        }
                        #endregion

                        #region [Objective Function]
                        INumExpr obj = cplex.NumExpr();
                        for (int i = 0; i < data.n; i++)
                        {
                            for (int j = 0; j < data.n; j++)
                            {
                                if (i != j)
                                {
                                    obj = cplex.Sum(obj,
                                                    cplex.Prod(
                                                        (
                                                            (timeFactor * data.timeNormalized[i][j]) +
                                                            (distanceFactor * data.distanceNormalized[i][j])
                                                        ), x[i][j]));
                                }
                            }
                        }
                        cplex.AddMinimize(obj);
                        #endregion

                        #region [Restrictions]
                        for (int j = 0; j < data.n; j++)
                        {
                            ILinearNumExpr sumj = cplex.LinearNumExpr();
                            for (int i = 0; i < data.n; i++)
                            {
                                if (i != j)
                                {
                                    sumj.AddTerm(1, x[i][j]);
                                }
                            }
                            cplex.AddEq(sumj, 1);
                        }

                        for (int i = 0; i < data.n; i++)
                        {
                            ILinearNumExpr sumi = cplex.LinearNumExpr();
                            for (int j = 0; j < data.n; j++)
                            {
                                if (i != j)
                                {
                                    sumi.AddTerm(1, x[i][j]);
                                }
                            }
                            cplex.AddEq(sumi, 1);
                        }
                        #endregion

                        cplex.SetParam(Cplex.DoubleParam.WorkMem, 4000.0);
                        cplex.SetParam(Cplex.Param.MIP.Strategy.File, 2);
                        cplex.SetParam(Cplex.DoubleParam.EpGap, 0.1);
                        cplex.SetParam(Cplex.BooleanParam.MemoryEmphasis, true);
                        cplex.SetParam(Cplex.IntParam.VarSel, 4);

SOLVE:

                        Stopwatch stopWatch = new Stopwatch();
                        stopWatch.Start();
                        if (cplex.Solve())
                        {
                            stopWatch.Stop();
                            double[][] sol_x = new double[data.n][];
                            for (int i = 0; i < data.n; i++)
                            {
                                sol_x[i] = cplex.GetValues(x[i]);
                            }
                            int[] tour = FindSubTour(sol_x);
                            if (tour.Length < data.n)
                            {
                                ILinearNumExpr sumx = cplex.LinearNumExpr();
                                for (int i = 0; i < tour.Length; i++)
                                {
                                    for (int j = 0; j < tour.Length; j++)
                                    {
                                        sumx.AddTerm(1, x[tour[i]][tour[j]]);
                                    }
                                }
                                cplex.AddLazyConstraint(cplex.AddLe(cplex.Diff(sumx, tour.Length), -1));
                                goto SOLVE;
                            }

                            double timeTotal     = 0;
                            double distanceTotal = 0;
                            for (int i = 0; i < data.n; i++)
                            {
                                for (int j = 0; j < data.n; j++)
                                {
                                    timeTotal     += data.time[i][j] * sol_x[i][j];
                                    distanceTotal += data.distance[i][j] * sol_x[i][j];
                                }
                            }

                            StreamWriter file = new StreamWriter(resultFilename, true);
                            file.WriteLine($"{timeFactor},{distanceFactor},{stopWatch.Elapsed.TotalSeconds},{cplex.ObjValue},{timeTotal},{distanceTotal}");
                            file.Close();

                            StreamWriter fileRouteResult = new StreamWriter($"./ResultFiles/Route-{routeCounter}.txt");
                            for (int i = 0; i < data.n; i++)
                            {
                                for (int j = 0; j < data.n; j++)
                                {
                                    if (sol_x[i][j] == 1)
                                    {
                                        fileRouteResult.WriteLine($"From city {i} to city {j}");
                                    }
                                }
                            }
                            fileRouteResult.Close();
                        }
                        cplex.End();
                    }

                    timeFactor     += step;
                    distanceFactor -= step;
                    routeCounter++;
                } while (timeFactor <= 1);
            }
            catch (ILOG.Concert.Exception ex)
            {
                StreamWriter errorfile = new StreamWriter("./ErrorLog.txt");
                errorfile.WriteLine("Exception Kind: ILOG.Concert.Exception (Concert Error)");
                errorfile.WriteLine("Message: " + ex.Message);
                errorfile.WriteLine("StackTrace: " + ex.StackTrace);
                errorfile.Close();
            }
            catch (InputDataReader.InputDataReaderException ex)
            {
                StreamWriter errorfile = new StreamWriter("./ErrorLog.txt");
                errorfile.WriteLine("Exception Kind: InputDataReader.InputDataReaderException (Data Error)");
                errorfile.WriteLine("Message: " + ex.Message);
                errorfile.WriteLine("StackTrace: " + ex.StackTrace);
                errorfile.Close();
            }
            catch (System.IO.IOException ex)
            {
                StreamWriter errorfile = new StreamWriter("./ErrorLog.txt");
                errorfile.WriteLine("Exception Kind: System.IO.IOException (IO Error)");
                errorfile.WriteLine("Message: " + ex.Message);
                errorfile.WriteLine("StackTrace: " + ex.StackTrace);
                errorfile.Close();
            }
        }
Пример #11
0
        private bool SolveAtCurrentPoint(double tau, bool suppress, out double optVal)
        {
            // values should be set in each variable by this point, for starting
            model.ClearModel();

            // update values and gradients for all functions based on last set var values
            UpdateFuncGraph();

            // add variables to model
            for (int j = 0; j < _variables.Count; j++)
            {
                AddCplexVar(model, _variables[j]);
            }

            // create slacks for each inequality constraint
            INumVar[] si = model.NumVarArray(_inequalities.Count, 0, double.MaxValue, NumVarType.Float);

            // set up objective
            INumExpr f0  = _objective.f.AddExpression(model);
            INumExpr g0  = _objective.g.Minorize(model);
            INumExpr slc = model.Prod(tau, model.Sum(si));

            model.AddMinimize(model.Sum(model.Diff(f0, g0), slc));

            // add equality/inequality constraints
            for (int i = 0; i < _equalities.Count; i++)
            {
                AddCplexEqual(model, _equalities[i]);
            }

            for (int i = 0; i < _inequalities.Count; i++)
            {
                AddCplexLEqual(model, _inequalities[i], si[i]);
            }

            // solve the simplified model
            optVal = double.PositiveInfinity;
            bool solved = true;

            model.SetOut(null);
            if (model.Solve())
            {
                optVal = model.GetObjValue();
                dc_Utility.WriteLineIf(!suppress, "");
                dc_Utility.WriteLineIf(!suppress, "Solved on Simple Model! Value: " + optVal);

                // set new values
                for (int i = 0; i < _variables.Count; i++)
                {
                    _variables[i].SetValue(model.GetValue(_variables[i].reference));
                }
            }
            else
            {
                solved = false;
                dc_Utility.WriteLineIf(!suppress, "");
                dc_Utility.WriteLineIf(!suppress, "Simple Model Failed...");
            }

            // clear cplex references
            for (int i = 0; i < _variables.Count; i++)
            {
                _variables[i].reference = null;
            }

            // clean up
            model.ClearModel();

            return(solved);
        }
Пример #12
0
        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);
            }
        }
Пример #13
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);
          }
    }
        static void Main(string[] args)
        {
            double BinCap = 0;
            var    dict   = InputReader.ReadDataFile(ref BinCap);

            Cplex cplex = new Cplex();
            Dictionary <string, INumVar> dictvariables   = new Dictionary <string, INumVar>();
            Dictionary <string, IRange>  dictconstraints = new Dictionary <string, IRange>();
            IObjective objective = cplex.AddMinimize();

            foreach (var vari in dict.Keys)
            {
                var cname = "C" + vari;
                dictconstraints.Add(cname, cplex.AddRange(1, Int32.MaxValue, cname));
            }

            Dictionary <int, Set> InitialSets = new Dictionary <int, Set>();;

            InitialSets.Add(1, new Set(new List <int> {
                1, 5
            }));
            InitialSets.Add(2, new Set(new List <int> {
                2, 5
            }));
            InitialSets.Add(3, new Set(new List <int> {
                3, 5
            }));
            InitialSets.Add(4, new Set(new List <int> {
                4, 5
            }));

            //Add intial sets to the model
            foreach (var vari in InitialSets)
            {
                var    setID  = vari.Key.ToString();
                Column VarSet = cplex.Column(objective, 1);
                foreach (var members in vari.Value.member)
                {
                    var cname = "C" + members;
                    VarSet = VarSet.And(cplex.Column(dictconstraints[cname], 1));
                }

                dictvariables.Add(setID, cplex.NumVar(VarSet, 0, 1, NumVarType.Float));
            }
            cplex.Solve();
            var duals    = getDuals(cplex, dictconstraints);
            var solution = getSolution(cplex, dictvariables);

            Console.WriteLine("The objective value is {0}", cplex.GetObjValue());

            int piter     = 0;
            int fixediter = 0;
            Dictionary <string, INumVar> Fixedvar = new Dictionary <string, INumVar>();

            while (true)
            {
                //Formulate Pricing Problem
                Cplex      pcplex     = new Cplex();
                IObjective pobjective = pcplex.AddMaximize();
                piter++;
                //Add Bin Capacity Constraint
                IRange Knapsack = pcplex.AddRange(0, BinCap, "Bin");
                Dictionary <string, INumVar> pdictvar = new Dictionary <string, INumVar>();
                foreach (var vari in dict.Keys)
                {
                    var    varname  = vari.ToString();
                    var    objcoeff = duals["C" + varname];
                    Column item     = pcplex.Column(pobjective, objcoeff);
                    item = item.And(pcplex.Column(Knapsack, dict[vari]));
                    pdictvar.Add(varname, pcplex.NumVar(item, 0, 1, NumVarType.Int));
                }

                pcplex.Solve();
                if (pcplex.GetObjValue() > 1)
                {
                    Console.WriteLine("Pricing Iteration: {0} and obj value is {1} ", piter, pcplex.GetObjValue());
                    var        psolution = getSolution(pcplex, pdictvar);
                    List <int> sol       = new List <int>();
                    foreach (var vari in psolution.Keys)
                    {
                        sol.Add(Convert.ToInt32(vari));
                    }
                    InitialSets.Add(InitialSets.Count + 1, new Set(sol));

                    var    setID   = (InitialSets.Count).ToString();
                    Column VarSet1 = cplex.Column(objective, 1);
                    foreach (var members in sol)
                    {
                        var cname = "C" + members;
                        VarSet1 = VarSet1.And(cplex.Column(dictconstraints[cname], 1));
                    }

                    dictvariables.Add(setID, cplex.NumVar(VarSet1, 0, 1, NumVarType.Float));

                    cplex.Solve();
                    Console.WriteLine("The objective value of cplex after adding column  is {0}", cplex.GetObjValue());
                    duals    = getDuals(cplex, dictconstraints);
                    solution = getSolution(cplex, dictvariables);
                }
                else
                {
                    fixediter++;
                    bool fixedsomething = false;
                    //fix variables above 0.5
                    foreach (var val in solution)
                    {
                        if (val.Value > 0.5 && !Fixedvar.ContainsKey(val.Key))
                        {
                            Fixedvar.Add(val.Key, dictvariables[val.Key]);
                            dictvariables[val.Key].LB = 1;
                            fixedsomething            = true;
                        }
                    }
                    if (!fixedsomething)
                    {
                        break;
                    }
                    cplex.Solve();
                    Console.WriteLine("The Fixing iterations is {0}", cplex.GetObjValue());
                    duals = getDuals(cplex, dictconstraints);
                }
            }

            foreach (var vari in Fixedvar.Values)
            {
                vari.LB = 0;
            }
            IConversion IP = cplex.Conversion(dictvariables.Values.ToArray(), NumVarType.Int);

            cplex.Add(IP);
            cplex.SetParam(Cplex.DoubleParam.TiLim, 600);
            cplex.Solve();

            solution = getSolution(cplex, dictvariables);
            Console.WriteLine("The objective value is {0}", cplex.GetObjValue());
        }
Пример #15
0
        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
Пример #16
0
 void AddFuncaoObjetivo(EntradaViewModel entrada)
 {
     double[] calculoFuncaoObjetivo = { };
     _cplex.AddMinimize(_cplex.ScalProd(_variaveis[1], calculoFuncaoObjetivo));
 }
Пример #17
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);
        }
    }
Пример #18
0
        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); }
        }
Пример #19
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");
        }
    }
Пример #20
0
    static void Main(string[] args)
    {
        try {
         string filename = "../../../../examples/data/etsp.dat";
         if ( args.Length > 0)
            filename = args[0];

         Data  data  = new Data(filename);
         Cplex cplex = new Cplex();

         // Create start variables
         INumVar[][] s = new INumVar[data.nJobs][];
         for (int j = 0; j < data.nJobs; j++)
            s[j] = cplex.NumVarArray(data.nResources, 0.0, Horizon);

         // State precedence constraints
         for (int j = 0; j < data.nJobs; j++) {
            for (int i = 1; i < data.nResources; i++)
               cplex.AddGe(s[j][i], cplex.Sum(s[j][i-1], data.duration[j][i-1]));
         }

         // State disjunctive constraints for each resource
         for (int i = 0; i < data.nResources; i++) {
            int end = data.nJobs - 1;
            for (int j = 0; j < end; j++) {
               int a = data.activityOnResource[i][j];
               for (int k = j + 1; k < data.nJobs; k++) {
                  int b = data.activityOnResource[i][k];
                  cplex.Add(cplex.Or(
                     cplex.Ge(s[j][a], cplex.Sum(s[k][b], data.duration[k][b])),
                     cplex.Ge(s[k][b], cplex.Sum(s[j][a], data.duration[j][a]))
                  ));
               }
            }
         }

         // The cost is the sum of earliness or tardiness costs of each job
         int last = data.nResources - 1;
         INumExpr costSum = cplex.NumExpr();
         for (int j = 0; j < data.nJobs; j++) {
            double[] points = { data.dueDate[j] };
            double[] slopes = { -data.earlinessCost[j],
                                data.tardinessCost[j] };
            costSum = cplex.Sum(costSum,
               cplex.PiecewiseLinear(
                  cplex.Sum(s[j][last], data.duration[j][last]),
                  points, slopes, data.dueDate[j], 0)
            );
         }
         cplex.AddMinimize(costSum);

         cplex.SetParam(Cplex.Param.Emphasis.MIP, 4);

         if ( cplex.Solve() ) {
           System.Console.WriteLine("Solution status = " + cplex.GetStatus());
           System.Console.WriteLine(" Optimal Value = " + cplex.ObjValue);
         }
         cplex.End();
          }
          catch (ILOG.Concert.Exception e) {
         System.Console.WriteLine("Concert exception caught: " + e);
          }
          catch (InputDataReader.InputDataReaderException ex) {
         System.Console.WriteLine("Data Error: " + ex);
          }
          catch (System.IO.IOException ex) {
         System.Console.WriteLine("IO Error: " + ex);
          }
    }
Пример #21
0
        protected void InitRMPModel()
        {
            #region                                      //////////////初始化变量//////////////
            Var1    = new Dictionary <int, INumVar[]>(); //INumVar[Data.TimeHorizon - alpha - 1][];
            Var2    = new Dictionary <int, INumVar>();   // RMPModel.NumVarArray(Data.TimeHorizon - alpha - 1, 0, double.MaxValue);
            AggVar1 = RMPModel.NumVarArray(Data.RS.Count, 0, double.MaxValue);
            AggVar2 = RMPModel.NumVar(0, double.MaxValue);

            V       = new Dictionary <int, double[]>();
            Sita    = new Dictionary <int, double>();
            AggV    = new double[Data.RS.Count];
            AggSita = 0;

            constraints    = new Dictionary <int, Dictionary <IALPDecision, IRange> >();
            Aggconstraints = new Dictionary <IALPDecision, IRange>();

            for (int i = alpha + 1; i < Data.TimeHorizon; i++)
            {
                constraints.Add(i, new Dictionary <IALPDecision, IRange>());
                Var1.Add(i, RMPModel.NumVarArray(Data.RS.Count, 0, double.MaxValue));
                Var2.Add(i, RMPModel.NumVar(0, double.MaxValue));
                V.Add(i, new double[Data.RS.Count]);
                Sita.Add(i, 0);
            }
            #endregion

            #region //////////////生成目标//////////////
            INumExpr exp5 = RMPModel.NumExpr();
            exp5 = RMPModel.Sum(exp5, AggVar2);
            foreach (IALPResource re in Data.RS)
            {
                exp5 = RMPModel.Sum(exp5, RMPModel.Prod((Data.InitialState as IALPState)[re], AggVar1[Data.RS.IndexOf(re)]));
            }
            IObjective cost = RMPModel.AddMinimize(exp5);
            #endregion

            #region //////////////生成基本约束//////////////
            for (int t = alpha + 1; t < Data.TimeHorizon; t++)
            {
                if (t < Data.TimeHorizon - 1)
                {
                    foreach (IALPResource re in Data.RS)
                    {
                        INumExpr exp2 = RMPModel.Sum(Var1[t][Data.RS.IndexOf(re)], RMPModel.Prod(-1, Var1[t + 1][Data.RS.IndexOf(re)]));
                        RMPModel.AddGe(exp2, 0);
                    }
                    INumExpr exp3 = RMPModel.Sum(Var2[t], RMPModel.Prod(-1, Var2[t + 1]));
                    RMPModel.AddGe(exp3, 0);
                }
            }
            foreach (IALPResource re in Data.RS)
            {
                INumExpr exp6 = RMPModel.NumExpr();
                exp6 = RMPModel.Sum(AggVar1[Data.RS.IndexOf(re)], RMPModel.Prod(-1, Var1[alpha + 1][Data.RS.IndexOf(re)]));
                RMPModel.AddGe(exp6, 0);
            }

            INumExpr exp4 = RMPModel.NumExpr();
            exp4 = RMPModel.Sum(exp4, AggVar2, RMPModel.Prod(-1, Var2[alpha + 1]));
            RMPModel.AddGe(exp4, 0);

            #endregion

            RMPModel.SetOut(null);
        }
Пример #22
0
        /// <summary>建立最初的RMP
        /// 依据初始解
        /// </summary>
        /// <param name="IS"></param>
        public void Build_RMP(InitialSolution IS)//主问题的建模
        {
            initialPath_num    = IS.PathSet.Count;
            trip_num           = TripList.Count;
            realistic_trip_num = NetWork.num_Physical_trip;

            DvarSet       = new List <INumVar>(); //x
            CoefSet       = new List <double>();  //cij
            AccumuWorkSet = new List <double>();  //每条交路累计工作时间
            ObjCoefSet    = new List <double>();
            A_Matrix      = new List <int[]>();   //aij
            PathSet       = new List <Pairing>(); //列池
            //int n = 196;//n代表的是整个高一车队每天所需要的乘务员和乘务长的总和


            CoefSet       = IS.Coefs;//IS初始解
            AccumuWorkSet = IS.AccumuWorkSet;
            A_Matrix      = IS.A_Matrix;
            PathSet       = IS.PathSet;
            ObjCoefSet    = IS.ObjCoefs;

            //for(int k = 0 ; k < IS.Coefs.Count ; k++)
            //{
            //    ObjCoefSet.Add(Network.GetObjCoef(IS.AccumuWorkSet[k] , IS.Coefs[k]));
            //}

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

            int i, j;

            masterModel = new Cplex();
            Obj         = masterModel.AddMinimize();
            Constraint  = new IRange[realistic_trip_num];//这种I打头的都是cplex里面的东西
            /**按行建模**/
            //vars and obj function
            for (j = 0; j < initialPath_num; j++)                                               //定义决策变量和目标函数
            {
                INumVar var = masterModel.NumVar(0, 1, NumVarType.Float);                       //INumVar-cplex里面的,定义决策变量。后面括号中的意思是定义var是0-1之间的浮点值
                DvarSet.Add(var);
                Obj.Expr = masterModel.Sum(Obj.Expr, masterModel.Prod(CoefSet[j], DvarSet[j])); //后面的小括号里面是一个cij*xj,大括号里面的是累计,包括之前的expr
            }
            //constraints
            for (i = 0; i < realistic_trip_num; i++) //对每一行    这部分的内容是aij*xj>=n
            {
                INumExpr expr = masterModel.NumExpr();

                for (j = 0; j < initialPath_num; j++) //对每一列
                {
                    expr = masterModel.Sum(expr,
                                           masterModel.Prod(A_Matrix[j][i], DvarSet[j])); //在从初始解传值给A_Matrix,已经针对网络复制作了处理
                }//小括号路里aij*xj

                Constraint[i] = masterModel.AddGe(expr, NUMBER_CREW); //约束list addge表示返回一个大于等于n的数
            }

            for (j = 0; j < initialPath_num; j++)//对每一列
            {
                INumExpr expr = masterModel.NumExpr();
                expr = masterModel.Sum(expr, DvarSet[j]);//在从初始解传值给A_Matrix,已经针对网络复制作了处理
            }


            //这里怎样使约束expr的值等于1????????????????????????????????????????????????
        }
Пример #23
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");
            }
        }
Пример #24
0
    public static void Main( string[] args )
    {
        try {
         string datafile = "../../../../examples/data/cutstock.dat";
         if (args.Length > 0)
            datafile = args[0];
         ReadData(datafile);

         /// CUTTING-OPTIMIZATION PROBLEM ///

         Cplex cutSolver = new Cplex();

         IObjective RollsUsed = cutSolver.AddMinimize();
         IRange[]   Fill = new IRange[_amount.Length];
         for (int f = 0; f < _amount.Length; f++ ) {
            Fill[f] = cutSolver.AddRange(_amount[f], System.Double.MaxValue);
         }

         System.Collections.ArrayList Cut = new System.Collections.ArrayList();

         int nWdth = _size.Length;
         for (int j = 0; j < nWdth; j++)
            Cut.Add(cutSolver.NumVar(cutSolver.Column(RollsUsed, 1.0).And(
                                     cutSolver.Column(Fill[j],
                                                      (int)(_rollWidth/_size[j]))),
                                     0.0, System.Double.MaxValue));

         cutSolver.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Primal);

         /// PATTERN-GENERATION PROBLEM ///

         Cplex patSolver = new Cplex();

         IObjective ReducedCost = patSolver.AddMinimize();
         INumVar[] Use = patSolver.NumVarArray(nWdth,
                                               0.0, System.Double.MaxValue,
                                               NumVarType.Int);
         patSolver.AddRange(-System.Double.MaxValue,
                            patSolver.ScalProd(_size, Use),
                            _rollWidth);

         /// COLUMN-GENERATION PROCEDURE ///

         double[] newPatt = new double[nWdth];

         /// COLUMN-GENERATION PROCEDURE ///

         for (;;) {
            /// OPTIMIZE OVER CURRENT PATTERNS ///

            cutSolver.Solve();
            Report1(cutSolver, Cut, Fill);

            /// FIND AND ADD A NEW PATTERN ///

            double[] price = cutSolver.GetDuals(Fill);
            ReducedCost.Expr = patSolver.Diff(1.0,
                                              patSolver.ScalProd(Use, price));

            patSolver.Solve();
            Report2 (patSolver, Use);

            if ( patSolver.ObjValue > -RC_EPS )
               break;

            newPatt = patSolver.GetValues(Use);

            Column column = cutSolver.Column(RollsUsed, 1.0);
            for ( int p = 0; p < newPatt.Length; p++ )
               column = column.And(cutSolver.Column(Fill[p], newPatt[p]));

            Cut.Add( cutSolver.NumVar(column, 0.0, System.Double.MaxValue) );
         }

         for ( int i = 0; i < Cut.Count; i++ ) {
            cutSolver.Add(cutSolver.Conversion((INumVar)Cut[i],
                                               NumVarType.Int));
         }

         cutSolver.Solve();
         System.Console.WriteLine("Solution status = " + cutSolver.GetStatus());
         Report3 (cutSolver, Cut);

         cutSolver.End();
         patSolver.End();
          }
          catch ( ILOG.Concert.Exception exc ) {
         System.Console.WriteLine("Concert exception '" + exc + "' caught");
          }
          catch (System.IO.IOException exc) {
         System.Console.WriteLine("Error reading file " + args[0] + ": " + exc);
          }
          catch (InputDataReader.InputDataReaderException exc ) {
         System.Console.WriteLine(exc);
          }
    }
Пример #25
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);
    }
Пример #26
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);
    }
Пример #27
0
        public override void IsoGraphInexactF1b()
        {
            this.nbRows = nbNode1 + nbEdge1 + nbNode2 + nbEdge2 + 3 * nbEdge1 * nbEdge2;                 //ns + ms+ng+mg+3msmg
            this.nbCols = nbNode1 * nbNode2 + nbEdge1 * nbEdge2 + nbNode1 + nbEdge1 + nbNode2 + nbEdge2; //nsng+msmg+ns+ms+ng+mg
            Graphs.Label nodeepslabel;

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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


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

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

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


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

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

                        string nameVar2 = "x_" + target_i + "," + target_k;
                        int    colInd2  = SolverCPLEX.GetIndexByName(x, nameVar2);
                        if (colInd2 == -1)
                        {
                            throw new InvalidProgramException();
                        }

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

                        ////////////////////////////////
                        jaList = new List <int>();
                        arList = new List <Double>();
                        lbMatrixList.Add(0.0);
                        ubMatrixList.Add(1.0);


                        jaList.Add(colInd2);
                        arList.Add(1);
                        jaList.Add(nbNode1 * nbNode2 + ij * nbEdge2 + kl);
                        arList.Add(-1);

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

                        ////////////////////////////////////////

                        /* jaList = new List<int>();
                         * arList = new List<Double>();
                         * lbMatrixList.Add(-1.0);
                         * ubMatrixList.Add(1.0);
                         *
                         * jaList.Add(colInd);
                         * arList.Add(1);
                         * jaList.Add(colInd2);
                         * arList.Add(1);
                         * jaList.Add(nbNode1 * nbNode2 + ij * nbEdge2 + kl);
                         * arList.Add(-1);
                         *
                         * indiceH[rownum] = jaList.ToArray();
                         * valeurH[rownum] = arList.ToArray();
                         * rownum++;*/
                    }
                }
                #endregion
                double[] lb = lbMatrixList.ToArray();
                double[] ub = ubMatrixList.ToArray();

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

                // add the objective function
                objCoef = objList.ToArray();
                cplex.AddMinimize(cplex.ScalProd(x, objCoef));
            }
            catch (ILOG.Concert.Exception e)
            {
                System.Console.WriteLine("Concert exception '" + e + "' caught");
            }
        }
Пример #28
0
        // The constructor sets up the Cplex instance to solve the worker LP,
        // and creates the worker LP (i.e., the dual of flow constraints and
        // capacity constraints of the flow MILP)
        //
        // Modeling variables:
        // forall k in V0, i in V:
        //    u(k,i) = dual variable associated with flow constraint (k,i)
        //
        // forall k in V0, forall (i,j) in A:
        //    v(k,i,j) = dual variable associated with capacity constraint (k,i,j)
        //
        // Objective:
        // minimize sum(k in V0) sum((i,j) in A) x(i,j) * v(k,i,j)
        //          - sum(k in V0) u(k,0) + sum(k in V0) u(k,k)
        //
        // Constraints:
        // forall k in V0, forall (i,j) in A: u(k,i) - u(k,j) <= v(k,i,j)
        //
        // Nonnegativity on variables v(k,i,j)
        // forall k in V0, forall (i,j) in A: v(k,i,j) >= 0
        //
        internal WorkerLP(int numNodes)
        {
            this.numNodes = numNodes;
             int i, j, k;

             // Set up Cplex instance to solve the worker LP

             cplex = new Cplex();
             cplex.SetOut(null);

             // Turn off the presolve reductions and set the CPLEX optimizer
             // to solve the worker LP with primal simplex method.

             cplex.SetParam(Cplex.Param.Preprocessing.Reduce, 0);
             cplex.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Primal);

             // Create variables v(k,i,j) forall k in V0, (i,j) in A
             // For simplicity, also dummy variables v(k,i,i) are created.
             // Those variables are fixed to 0 and do not partecipate to
             // the constraints.

             v = new INumVar[numNodes-1][][];
             for (k = 1; k < numNodes; ++k)
             {
            v[k-1] = new INumVar[numNodes][];
            for (i = 0; i < numNodes; ++i)
            {
               v[k-1][i] = new INumVar[numNodes];
               for (j = 0; j < numNodes; ++j)
               {
                  v[k-1][i][j] = cplex.NumVar(0.0, System.Double.MaxValue, "v." + k + "." + i + "." + j);
                  cplex.Add(v[k-1][i][j]);
               }
               v[k-1][i][i].UB = 0.0;
            }
             }

             // Create variables u(k,i) forall k in V0, i in V

             u = new INumVar[numNodes-1][];
             for (k = 1; k < numNodes; ++k)
             {
            u[k-1] = new INumVar[numNodes];
            for (i = 0; i < numNodes; ++i)
            {
               u[k-1][i] = cplex.NumVar(-System.Double.MaxValue, System.Double.MaxValue, "u." + k + "." + i);
               cplex.Add(u[k-1][i]);
            }
             }

             // Initial objective function is empty

             cplex.AddMinimize();

             // Add constraints:
             // forall k in V0, forall (i,j) in A: u(k,i) - u(k,j) <= v(k,i,j)

             for (k = 1; k < numNodes; ++k)
             {
            for (i = 0; i < numNodes; ++i)
            {
               for (j = 0; j < numNodes; ++j)
               {
                  if ( i != j )
                  {
                     ILinearNumExpr expr = cplex.LinearNumExpr();
                     expr.AddTerm(v[k-1][i][j], -1.0);
                     expr.AddTerm(u[k-1][i], 1.0);
                     expr.AddTerm(u[k-1][j], -1.0);
                     cplex.AddLe(expr, 0.0);
                  }
               }
            }
             }
        }
Пример #29
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);
        }
    }
Пример #30
0
        public static Cplex Build_CLP1_Model(IALPFTMDP aff)
        {
            Cplex model = new Cplex();

            INumVar[][] Var1 = new INumVar[aff.TimeHorizon][];
            INumVar[]   Var2 = model.NumVarArray(aff.TimeHorizon, 0, double.MaxValue);

            #region //////////////生成变量//////////////
            for (int i = 0; i < aff.TimeHorizon; i++)
            {
                Var1[i] = model.NumVarArray(aff.RS.Count, 0, double.MaxValue);// new INumVar[aff.DS.Count];
            }
            #endregion

            #region //////////////生成约束//////////////
            for (int t = 0; t < aff.TimeHorizon; t++)
            {
                foreach (IALPDecision a in aff.DS)
                {
                    INumExpr exp1 = model.NumExpr();
                    if (t < aff.TimeHorizon - 1)
                    {
                        exp1 = model.Sum(Var2[t], model.Prod(-1, Var2[t + 1]));
                        foreach (IALPResource re in aff.RS)
                        {
                            if (a.UseResource(re))
                            {
                                exp1 = model.Sum(exp1, Var1[t][aff.RS.IndexOf(re)], model.Prod(aff.Qti(t, re, a) - 1, Var1[t + 1][aff.RS.IndexOf(re)]));
                            }
                        }
                    }
                    else
                    {
                        exp1 = model.Sum(exp1, Var2[t]);
                        foreach (IALPResource re in aff.RS)
                        {
                            if (a.UseResource(re))
                            {
                                exp1 = model.Sum(exp1, Var1[t][aff.RS.IndexOf(re)]);
                            }
                        }
                    }
                    model.AddGe(exp1, aff.Rt(t, a));
                }
                if (t < aff.TimeHorizon - 1)
                {
                    foreach (IALPResource re in aff.RS)
                    {
                        INumExpr exp2 = model.NumExpr();
                        exp2 = model.Sum(Var1[t][aff.RS.IndexOf(re)], model.Prod(-1, Var1[t + 1][aff.RS.IndexOf(re)]));
                        model.AddGe(exp2, 0);
                    }
                    INumExpr exp3 = model.NumExpr();
                    exp3 = model.Sum(exp3, Var2[t], model.Prod(-1, Var2[t + 1]));
                    model.AddGe(exp3, 0);
                }
            }
            #endregion

            #region //////////////生成目标//////////////
            INumExpr exp5 = model.NumExpr();
            exp5 = model.Sum(exp5, Var2[0]);
            foreach (IALPResource re in aff.RS)
            {
                exp5 = model.Sum(exp5, model.Prod((aff.InitialState as IALPState)[re], Var1[0][aff.RS.IndexOf(re)]));
            }
            IObjective cost = model.AddMinimize(exp5);
            #endregion

            return(model);
        }
Пример #31
0
        //F2 version with constant and slack variables
        ////Formlation F2 for the GED problem. Very efficient.
        // https://hal.archives-ouvertes.fr/hal-01619313

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

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

            Graphs.Label nodeepslabel;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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



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


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

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

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

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

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



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


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

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

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

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

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

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

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

                // add the objective function
                objCoef = objList.ToArray();
                cplex.AddMinimize(cplex.Sum(cplex.Constant(constante), cplex.ScalProd(x, objCoef)));
            }
            catch (ILOG.Concert.Exception e)
            {
                System.Console.WriteLine("Concert exception '" + e + "' caught");
            }
        }
Пример #32
0
   public static void Main(string[] args) {
      try {
         int ncols = 12;

         Cplex cplex = new Cplex();
         ILPMatrix lp = cplex.AddLPMatrix();

         // add empty corresponding to new variables columns to lp
         INumVar[] x = cplex.NumVarArray(cplex.ColumnArray(lp, ncols), 0, 50);

         // add rows to lp
         double[]   d = {-1.0, 4.0, 1.0, 1.0, -2.0, -2.0, -1.0};
         double[][] valH = {new double[] {-1.0, -1.0, -1.0},
                            new double[] { 1.0,  1.0,  1.0},
                            new double[] { 1.0,  1.0,  1.0,  1.0},
                            new double[] { 1.0,  1.0,  1.0},
                            new double[] {-1.0, -1.0, -1.0,  1.0},
                            new double[] {-1.0, -1.0,  1.0},
                            new double[] {-1.0, -1.0, -1.0, -1.0}};
         int[][]    indH = {new int[] {7, 8, 9},
                            new int[] {0, 5, 7},
                            new int[] {1, 3, 6, 8},
                            new int[] {2, 4, 9},
                            new int[] {5, 6, 10, 11},
                            new int[] {3, 4, 10},
                            new int[] {0, 1, 2, 11}};

         lp.AddRows(d, d, indH, valH);

         // add the objective function
         double[] objvals = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
                             1.0, 0.0, 0.0, 0.0, 2.0, 2.0};
         cplex.AddMinimize(cplex.ScalProd(x, objvals));

         // Solve initial problem with the network optimizer
         cplex.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Network);
         cplex.Solve();
         System.Console.WriteLine("After network optimization, objective is "
                                  + cplex.ObjValue);

         // add rows from matrix A to lp
         double[]   b = {2.0, 3.0};
         double[][] valA = {new double[] {2.0, 5.0},
                            new double[] {1.0, 1.0, 1.0}};
         int[][]    indA = {new int[] {10, 11},
                            new int[] {0, 2, 5}};
         lp.AddRows(b, b, indA, valA);
   
         // Because the problem is dual feasible with the rows added, using
         // the dual simplex method is indicated.
         cplex.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Dual);
         if ( cplex.Solve() ) {
            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);

            double[] sol = cplex.GetValues(lp);
            for (int j = 0; j < ncols; ++j) {
               System.Console.WriteLine("Variable " + j + ": Value = " + sol[j]);
            }
         }
         cplex.End();
      }
      catch (ILOG.Concert.Exception e) {
          System.Console.WriteLine("Concert exception '" + e + "' caught");
      }
   }
Пример #33
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;
            }
        }
Пример #34
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);
        }
    }
Пример #35
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);
        }
Пример #36
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);
        }
Пример #37
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);
          }
    }
Пример #38
0
        // The constructor sets up the Cplex instance to solve the worker LP,
        // and creates the worker LP (i.e., the dual of flow constraints and
        // capacity constraints of the flow MILP)
        //
        // Modeling variables:
        // forall k in V0, i in V:
        //    u(k,i) = dual variable associated with flow constraint (k,i)
        //
        // forall k in V0, forall (i,j) in A:
        //    v(k,i,j) = dual variable associated with capacity constraint (k,i,j)
        //
        // Objective:
        // minimize sum(k in V0) sum((i,j) in A) x(i,j) * v(k,i,j)
        //          - sum(k in V0) u(k,0) + sum(k in V0) u(k,k)
        //
        // Constraints:
        // forall k in V0, forall (i,j) in A: u(k,i) - u(k,j) <= v(k,i,j)
        //
        // Nonnegativity on variables v(k,i,j)
        // forall k in V0, forall (i,j) in A: v(k,i,j) >= 0
        //
        internal WorkerLP(int numNodes)
        {
            this.numNodes = numNodes;
            int i, j, k;

            // Set up Cplex instance to solve the worker LP

            cplex = new Cplex();
            cplex.SetOut(null);

            // Turn off the presolve reductions and set the CPLEX optimizer
            // to solve the worker LP with primal simplex method.

            cplex.SetParam(Cplex.Param.Preprocessing.Reduce, 0);
            cplex.SetParam(Cplex.Param.RootAlgorithm, Cplex.Algorithm.Primal);

            // Create variables v(k,i,j) forall k in V0, (i,j) in A
            // For simplicity, also dummy variables v(k,i,i) are created.
            // Those variables are fixed to 0 and do not partecipate to
            // the constraints.

            v = new INumVar[numNodes - 1][][];
            for (k = 1; k < numNodes; ++k)
            {
                v[k - 1] = new INumVar[numNodes][];
                for (i = 0; i < numNodes; ++i)
                {
                    v[k - 1][i] = new INumVar[numNodes];
                    for (j = 0; j < numNodes; ++j)
                    {
                        v[k - 1][i][j] = cplex.NumVar(0.0, System.Double.MaxValue, "v." + k + "." + i + "." + j);
                        cplex.Add(v[k - 1][i][j]);
                    }
                    v[k - 1][i][i].UB = 0.0;
                }
            }

            // Create variables u(k,i) forall k in V0, i in V

            u = new INumVar[numNodes - 1][];
            for (k = 1; k < numNodes; ++k)
            {
                u[k - 1] = new INumVar[numNodes];
                for (i = 0; i < numNodes; ++i)
                {
                    u[k - 1][i] = cplex.NumVar(-System.Double.MaxValue, System.Double.MaxValue, "u." + k + "." + i);
                    cplex.Add(u[k - 1][i]);
                }
            }

            // Initial objective function is empty

            cplex.AddMinimize();

            // Add constraints:
            // forall k in V0, forall (i,j) in A: u(k,i) - u(k,j) <= v(k,i,j)

            for (k = 1; k < numNodes; ++k)
            {
                for (i = 0; i < numNodes; ++i)
                {
                    for (j = 0; j < numNodes; ++j)
                    {
                        if (i != j)
                        {
                            ILinearNumExpr expr = cplex.LinearNumExpr();
                            expr.AddTerm(v[k - 1][i][j], -1.0);
                            expr.AddTerm(u[k - 1][i], 1.0);
                            expr.AddTerm(u[k - 1][j], -1.0);
                            cplex.AddLe(expr, 0.0);
                        }
                    }
                }
            }
        } // END WorkerLP
Пример #39
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
        }
Пример #40
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");
      }
   }
Пример #41
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);
        }