示例#1
0
    public static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            System.Console.WriteLine("Usage: Goalex1 filename");
            System.Console.WriteLine("   where filename is a file with extension ");
            System.Console.WriteLine("      MPS, SAV, or LP (lower case is allowed)");
            System.Console.WriteLine(" Exiting...");
            return;
        }

        try {
            Cplex cplex = new Cplex();

            cplex.ImportModel(args[0]);

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

            ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

            cplex.SetParam(Cplex.Param.MIP.Strategy.Search, Cplex.MIPSearch.Traditional);
            if (cplex.Solve(new MyBranchGoal(lp.NumVars)))
            {
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine("Solution value  = " + cplex.ObjValue);
            }

            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
示例#2
0
    internal static ILPMatrix PopulateByRow(IMPModeler model)
    {
        ILPMatrix lp = model.AddLPMatrix();

        double[]  lb = { 0.0, 0.0, 0.0 };
        double[]  ub = { 40.0, System.Double.MaxValue, System.Double.MaxValue };
        INumVar[] x  = model.NumVarArray(model.ColumnArray(lp, 3), lb, ub);

        // - x0 +   x1 + x2 <= 20
        //   x0 - 3*x1 + x2 <= 30
        double[]   lhs = { -System.Double.MaxValue, -System.Double.MaxValue };
        double[]   rhs = { 20.0, 30.0 };
        double[][] val = { new double[] { -1.0,  1.0, 1.0 },
                           new double[] {  1.0, -3.0, 1.0 } };
        int[][]    ind = { new int[] { 0, 1, 2 },
                           new int[] { 0, 1, 2 } };
        lp.AddRows(lhs, rhs, ind, val);

        // Q = 0.5 ( 33*x0*x0 + 22*x1*x1 + 11*x2*x2 - 12*x0*x1 - 23*x1*x2 )
        INumExpr x00 = model.Prod(33.0, model.Square(x[0]));
        INumExpr x11 = model.Prod(22.0, model.Square(x[1]));
        INumExpr x22 = model.Prod(11.0, model.Square(x[2]));
        INumExpr x01 = model.Prod(-12.0, model.Prod(x[0], x[1]));
        INumExpr x12 = model.Prod(-23.0, model.Prod(x[1], x[2]));
        INumExpr Q   = model.Prod(0.5, model.Sum(x00, x11, x22, x01, x12));

        // maximize x0 + 2*x1 + 3*x2 + Q
        double[] objvals = { 1.0, 2.0, 3.0 };
        model.Add(model.Maximize(model.Diff(model.ScalProd(x, objvals), Q)));

        return(lp);
    }
示例#3
0
    internal static void SolveAndDisplay(Cplex cplex, ILPMatrix lp)
    {
        if (cplex.Solve())
        {
            double[] x     = cplex.GetValues(lp);
            double[] dj    = cplex.GetReducedCosts(lp);
            double[] pi    = cplex.GetDuals(lp);
            double[] slack = cplex.GetSlacks(lp);

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

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

            int ncons = slack.Length;
            for (int i = 0; i < ncons; ++i)
            {
                System.Console.WriteLine("Constraint " + i + ": Slack = " + slack[i] + " Pi = " + pi[i]);
            }
        }
    }
示例#4
0
    // To populate by row, we first create the variables, and then use them to
    // create the range constraints and objective.  The model we create is:
    //
    // Minimize
    //  obj:   - 0.5 (-3 * xˆ2 - 3 * yˆ2 - 1 * x * y)
    // Subject To
    //  c1: -x + y >= 0
    //  c2:  x + y >= 0
    // Bounds
    //  -1 <= x <= 1
    //   0 <= y <= 1
    // End

    internal static ILPMatrix PopulateByRow(IMPModeler model)
    {
        ILPMatrix lp = model.AddLPMatrix();

        double[]  lb = { -1.0, 0.0 };
        double[]  ub = { 1.0, 1.0 };
        INumVar[] x  = model.NumVarArray(model.ColumnArray(lp, 2), lb, ub);

        double[]   lhs = { 0.0, 0.0 };
        double[]   rhs = { System.Double.MaxValue, System.Double.MaxValue };
        double[][] val = { new double[] { -1.0, 1.0 },
                           new double[] {  1.0, 1.0 } };
        int[][]    ind = { new int[] { 0, 1 },
                           new int[] { 0, 1 } };
        lp.AddRows(lhs, rhs, ind, val);

        INumExpr x00 = model.Prod(-3.0, x[0], x[0]);
        INumExpr x11 = model.Prod(-3.0, x[1], x[1]);
        INumExpr x01 = model.Prod(-1.0, x[0], x[1]);
        INumExpr Q   = model.Prod(0.5, model.Sum(x00, x11, x01));

        model.Add(model.Minimize(Q));

        return(lp);
    }
示例#5
0
    public static void Main(string[] args)
    {
        try {
            Cplex     cplex = new Cplex();
            ILPMatrix lp    = PopulateByRow(cplex);

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

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

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

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

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

            cplex.ExportModel("indefqpex1.lp");
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception '" + e + "' caught");
        }
    }
示例#6
0
    // Modifying all quadratic terms x[i]*x[j]
    // in the objective function.
    internal static void ModifyQuadObjective(CplexModeler model)
    {
        IEnumerator matrixEnum = model.GetLPMatrixEnumerator();

        matrixEnum.MoveNext();
        ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

        INumVar[]  x     = lp.NumVars;
        int        ncols = x.Length;
        IObjective obj   = model.GetObjective();

        // Note that the quadratic expression in the objective
        // is normalized: i.e., for all i != j, terms
        // c(i,j)*x[i]*x[j] + c(j,i)*x[j]*x[i] are normalized as
        // (c(i,j) + c(j,i)) * x[i]*x[j], or
        // (c(i,j) + c(j,i)) * x[j]*x[i].
        // Therefore you can only modify one of the terms
        // x[i]*x[j] or x[j]*x[i].
        // If you modify both x[i]*x[j] and x[j]*x[i], then
        // the second modification will overwrite the first one.
        for (int i = 0; i < ncols; ++i)
        {
            model.SetQuadCoef(obj, x[i], x[i], i * i);
            for (int j = 0; j < i; ++j)
            {
                model.SetQuadCoef(obj, x[i], x[j], -2.0 * (i * j));
            }
        }

        // Print out the objective function
        PrintObjective(obj);
    }
示例#7
0
    public static void Main(string[] args)
    {
        // Check length of command line
        if (args.Length != 2)
        {
            Usage();
            System.Environment.Exit(-1);
        }

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

        // Solve the model.
        Cplex cplex = null;

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

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

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

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

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

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

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

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

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

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

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

                int ncons = slack.Length;
                for (int i = 0; i < ncons; ++i)
                {
                    System.Console.WriteLine("Constraint " + i +
                                             ": Slack = " + slack[i] +
                                             " Pi = " + pi[i]);
                }
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception '" + e + "' caught");
        }
    }
 public void setProb(Problem prob)
 {
     if (prob is ProblemCPLEX)
     {
         this.cplex     = ((ProblemCPLEX)prob).cplex;
         this.ilpMatrix = ((ProblemCPLEX)prob).ilpMatrix;
         this.objCoef   = ((ProblemCPLEX)prob).objCoef;
     }
     else
     {
         this.cplex     = ((ProblemCPLEXUndirected)prob).cplex;
         this.ilpMatrix = ((ProblemCPLEXUndirected)prob).ilpMatrix;
         this.objCoef   = ((ProblemCPLEXUndirected)prob).objCoef;
     }
 }
示例#10
0
    public static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            System.Console.WriteLine("Usage: AdMIPex1 filename");
            System.Console.WriteLine("   where filename is a file with extension ");
            System.Console.WriteLine("      MPS, SAV, or LP (lower case is allowed)");
            System.Console.WriteLine(" Exiting...");
            System.Environment.Exit(-1);
        }

        try {
            Cplex cplex = new Cplex();

            cplex.ImportModel(args[0]);

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

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

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

                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine("Solution value  = " + cplex.ObjValue);
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception exc) {
            System.Console.WriteLine("Concert exception caught: " + exc);
        }
    }
示例#11
0
    // Creating a simple QP problem
    internal static ILPMatrix CreateQPModel(IMPModeler model)
    {
        ILPMatrix lp = model.AddLPMatrix();

        double[]  lb    = { 0.0, 0.0, 0.0 };
        double[]  ub    = { 40.0, System.Double.MaxValue, System.Double.MaxValue };
        INumVar[] x     = model.NumVarArray(model.ColumnArray(lp, 3), lb, ub);
        int       nvars = x.Length;

        for (int j = 0; j < nvars; ++j)
        {
            x[j].Name = "x" + j;
        }

        // - x0 +   x1 + x2 <= 20
        //   x0 - 3*x1 + x2 <= 30
        double[]   lhs = { -System.Double.MaxValue, -System.Double.MaxValue };
        double[]   rhs = { 20.0, 30.0 };
        double[][] val = { new double[] { -1.0,  1.0, 1.0 },
                           new double[] {  1.0, -3.0, 1.0 } };
        int[][]    ind = { new int[] { 0, 1, 2 },
                           new int[]    { 0, 1, 2 } };
        lp.AddRows(lhs, rhs, ind, val);

        // minimize - x0 - x1 - x2 + x0*x0 + x1*x1 + x0*x1 + x1*x0
        ILQNumExpr objExpr = model.LqNumExpr();

        for (int i = 0; i < nvars; ++i)
        {
            objExpr.AddTerm(-1.0, x[i]);
            for (int j = 0; j < nvars; ++j)
            {
                objExpr.AddTerm(1.0, x[i], x[j]);
            }
        }
        IObjective obj = model.Minimize(objExpr);

        model.Add(obj);

        // Print out the objective function
        PrintObjective(obj);

        return(lp);
    }
示例#12
0
    public static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            System.Console.WriteLine("Usage: AdMIPex2 filename");
            System.Console.WriteLine("   where filename is a file with extension ");
            System.Console.WriteLine("      MPS, SAV, or LP (lower case is allowed)");
            System.Console.WriteLine(" Exiting...");
            System.Environment.Exit(-1);
        }

        try {
            Cplex cplex = new Cplex();

            cplex.ImportModel(args[0]);

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


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

            ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

            cplex.Use(new RoundDown(lp.NumVars));

            cplex.SetParam(Cplex.Param.MIP.Strategy.Search, Cplex.MIPSearch.Traditional);
            if (cplex.Solve())
            {
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine("Solution value  = " + cplex.ObjValue);
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
示例#13
0
    public static void Main(string[] args)
    {
        try {
            Cplex     cplex = new Cplex();
            ILPMatrix lp    = PopulateByRow(cplex);


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

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

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

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

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

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

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

            ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

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

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

            cplex.SetParam(Cplex.Param.MIP.Interval, 1000);
            if (cplex.Solve())
            {
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine("Solution value  = " + cplex.ObjValue);
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
示例#15
0
    internal static ILPMatrix PopulateByRow(IMPModeler model)
    {
        ILPMatrix lp = model.AddLPMatrix();

        double[]  lb = { 0.0, 0.0, 0.0 };
        double[]  ub = { 40.0, System.Double.MaxValue, System.Double.MaxValue };
        INumVar[] x  = model.NumVarArray(model.ColumnArray(lp, 3), lb, ub);

        double[]   lhs = { -System.Double.MaxValue, -System.Double.MaxValue };
        double[]   rhs = { 20.0, 30.0 };
        double[][] val = { new double[] { -1.0,  1.0, 1.0 },
                           new double[] {  1.0, -3.0, 1.0 } };
        int[][]    ind = { new int[] { 0, 1, 2 },
                           new int[] { 0, 1, 2 } };
        lp.AddRows(lhs, rhs, ind, val);

        double[] objvals = { 1.0, 2.0, 3.0 };
        model.AddMaximize(model.ScalProd(x, objvals));

        return(lp);
    }
示例#16
0
    // Solve the current model and print results
    internal static void SolveAndPrint(Cplex cplex, string msg)
    {
        System.Console.WriteLine(msg);
        if (cplex.Solve())
        {
            System.Console.WriteLine();
            System.Console.WriteLine("Solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Solution value  = " + cplex.ObjValue);

            IEnumerator matrixEnum = cplex.GetLPMatrixEnumerator();
            matrixEnum.MoveNext();
            ILPMatrix lp    = (ILPMatrix)matrixEnum.Current;
            double[]  x     = cplex.GetValues(lp);
            int       nvars = x.Length;
            for (int j = 0; j < nvars; ++j)
            {
                System.Console.WriteLine("Variable " + j + ": Value = " + x[j]);
            }
        }
        System.Console.WriteLine();
    }
示例#17
0
    public static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            Usage();
            return;
        }
        try {
            Cplex cplex = new Cplex();

            cplex.ImportModel(args[0]);

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

                // access ILPMatrix object that has been read from file in order to
                // access variables which are the columns of the lp.  Method
                // importModel guarantees to the model into exactly on ILPMatrix
                // object which is why there are no test or iterations needed in the
                // following line of code.

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

                ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

                double[] x = cplex.GetValues(lp);
                for (int j = 0; j < x.Length; ++j)
                {
                    System.Console.WriteLine("Variable " + j + ": Value = " + x[j]);
                }
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
示例#18
0
    public static void Main(string[] args)
    {
        try {
            Cplex cplex = new Cplex();

            cplex.ImportModel(args[0]);

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

            ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

            IConversion relax = cplex.Conversion(lp.NumVars,
                                                 NumVarType.Float);
            cplex.Add(relax);

            cplex.Solve();
            System.Console.WriteLine("Relaxed solution status = " + cplex.GetStatus());
            System.Console.WriteLine("Relaxed solution value  = " + cplex.ObjValue);

            double[] vals = cplex.GetValues(lp.NumVars);
            cplex.Use(new Solve(lp.NumVars, vals));

            cplex.Delete(relax);

            cplex.SetParam(Cplex.Param.MIP.Strategy.Search, Cplex.MIPSearch.Traditional);
            if (cplex.Solve())
            {
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine("Solution value  = " + cplex.ObjValue);
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
示例#19
0
    public static void Main(string[] args)
    {
        try {
            Cplex cplex = new Cplex();

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

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

            ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

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

            cplex.SetParam(Cplex.Param.MIP.Interval, 1000);
            cplex.SetParam(Cplex.Param.MIP.Strategy.Search, Cplex.MIPSearch.Traditional);
            if (cplex.Solve())
            {
                System.Console.WriteLine("Solution status = " + cplex.GetStatus());
                System.Console.WriteLine("Solution value  = " + cplex.ObjValue);
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
示例#20
0
    internal static IRange[] MakeCuts(IModeler m, ILPMatrix lp)
    {
        INumVar x11 = null, x12 = null, x13 = null, x14 = null, x15 = null;
        INumVar x21 = null, x22 = null, x23 = null, x24 = null, x25 = null;
        INumVar x31 = null, x32 = null, x33 = null, x34 = null, x35 = null;
        INumVar x41 = null, x42 = null, x43 = null, x44 = null, x45 = null;
        INumVar x51 = null, x52 = null, x53 = null, x54 = null, x55 = null;
        INumVar w11 = null, w12 = null, w13 = null, w14 = null, w15 = null;
        INumVar w21 = null, w22 = null, w23 = null, w24 = null, w25 = null;
        INumVar w31 = null, w32 = null, w33 = null, w34 = null, w35 = null;
        INumVar w41 = null, w42 = null, w43 = null, w44 = null, w45 = null;
        INumVar w51 = null, w52 = null, w53 = null, w54 = null, w55 = null;

        INumVar[] vars = lp.NumVars;
        int       num  = vars.Length;

        for (int i = 0; i < num; ++i)
        {
            if (vars[i].Name.Equals("X11"))
            {
                x11 = vars[i];
            }
            else if (vars[i].Name.Equals("X12"))
            {
                x12 = vars[i];
            }
            else if (vars[i].Name.Equals("X13"))
            {
                x13 = vars[i];
            }
            else if (vars[i].Name.Equals("X14"))
            {
                x14 = vars[i];
            }
            else if (vars[i].Name.Equals("X15"))
            {
                x15 = vars[i];
            }
            else if (vars[i].Name.Equals("X21"))
            {
                x21 = vars[i];
            }
            else if (vars[i].Name.Equals("X22"))
            {
                x22 = vars[i];
            }
            else if (vars[i].Name.Equals("X23"))
            {
                x23 = vars[i];
            }
            else if (vars[i].Name.Equals("X24"))
            {
                x24 = vars[i];
            }
            else if (vars[i].Name.Equals("X25"))
            {
                x25 = vars[i];
            }
            else if (vars[i].Name.Equals("X31"))
            {
                x31 = vars[i];
            }
            else if (vars[i].Name.Equals("X32"))
            {
                x32 = vars[i];
            }
            else if (vars[i].Name.Equals("X33"))
            {
                x33 = vars[i];
            }
            else if (vars[i].Name.Equals("X34"))
            {
                x34 = vars[i];
            }
            else if (vars[i].Name.Equals("X35"))
            {
                x35 = vars[i];
            }
            else if (vars[i].Name.Equals("X41"))
            {
                x41 = vars[i];
            }
            else if (vars[i].Name.Equals("X42"))
            {
                x42 = vars[i];
            }
            else if (vars[i].Name.Equals("X43"))
            {
                x43 = vars[i];
            }
            else if (vars[i].Name.Equals("X44"))
            {
                x44 = vars[i];
            }
            else if (vars[i].Name.Equals("X45"))
            {
                x45 = vars[i];
            }
            else if (vars[i].Name.Equals("X51"))
            {
                x51 = vars[i];
            }
            else if (vars[i].Name.Equals("X52"))
            {
                x52 = vars[i];
            }
            else if (vars[i].Name.Equals("X53"))
            {
                x53 = vars[i];
            }
            else if (vars[i].Name.Equals("X54"))
            {
                x54 = vars[i];
            }
            else if (vars[i].Name.Equals("X55"))
            {
                x55 = vars[i];
            }
            else if (vars[i].Name.Equals("W11"))
            {
                w11 = vars[i];
            }
            else if (vars[i].Name.Equals("W12"))
            {
                w12 = vars[i];
            }
            else if (vars[i].Name.Equals("W13"))
            {
                w13 = vars[i];
            }
            else if (vars[i].Name.Equals("W14"))
            {
                w14 = vars[i];
            }
            else if (vars[i].Name.Equals("W15"))
            {
                w15 = vars[i];
            }
            else if (vars[i].Name.Equals("W21"))
            {
                w21 = vars[i];
            }
            else if (vars[i].Name.Equals("W22"))
            {
                w22 = vars[i];
            }
            else if (vars[i].Name.Equals("W23"))
            {
                w23 = vars[i];
            }
            else if (vars[i].Name.Equals("W24"))
            {
                w24 = vars[i];
            }
            else if (vars[i].Name.Equals("W25"))
            {
                w25 = vars[i];
            }
            else if (vars[i].Name.Equals("W31"))
            {
                w31 = vars[i];
            }
            else if (vars[i].Name.Equals("W32"))
            {
                w32 = vars[i];
            }
            else if (vars[i].Name.Equals("W33"))
            {
                w33 = vars[i];
            }
            else if (vars[i].Name.Equals("W34"))
            {
                w34 = vars[i];
            }
            else if (vars[i].Name.Equals("W35"))
            {
                w35 = vars[i];
            }
            else if (vars[i].Name.Equals("W41"))
            {
                w41 = vars[i];
            }
            else if (vars[i].Name.Equals("W42"))
            {
                w42 = vars[i];
            }
            else if (vars[i].Name.Equals("W43"))
            {
                w43 = vars[i];
            }
            else if (vars[i].Name.Equals("W44"))
            {
                w44 = vars[i];
            }
            else if (vars[i].Name.Equals("W45"))
            {
                w45 = vars[i];
            }
            else if (vars[i].Name.Equals("W51"))
            {
                w51 = vars[i];
            }
            else if (vars[i].Name.Equals("W52"))
            {
                w52 = vars[i];
            }
            else if (vars[i].Name.Equals("W53"))
            {
                w53 = vars[i];
            }
            else if (vars[i].Name.Equals("W54"))
            {
                w54 = vars[i];
            }
            else if (vars[i].Name.Equals("W55"))
            {
                w55 = vars[i];
            }
        }

        IRange[] cut = new IRange[8];

        cut[0] = m.Le(m.Diff(x21, x22), 0.0);
        cut[1] = m.Le(m.Diff(x22, x23), 0.0);
        cut[2] = m.Le(m.Diff(x23, x24), 0.0);
        cut[3] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x11),
                                  m.Prod(2.98, x21),
                                  m.Prod(3.47, x31),
                                  m.Prod(2.24, x41),
                                  m.Prod(2.08, x51)),
                            m.Sum(m.Prod(0.25, w11),
                                  m.Prod(0.25, w21),
                                  m.Prod(0.25, w31),
                                  m.Prod(0.25, w41),
                                  m.Prod(0.25, w51))), 20.25);
        cut[4] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x12),
                                  m.Prod(2.98, x22),
                                  m.Prod(3.47, x32),
                                  m.Prod(2.24, x42),
                                  m.Prod(2.08, x52)),
                            m.Sum(m.Prod(0.25, w12),
                                  m.Prod(0.25, w22),
                                  m.Prod(0.25, w32),
                                  m.Prod(0.25, w42),
                                  m.Prod(0.25, w52))), 20.25);
        cut[5] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x13),
                                  m.Prod(2.98, x23),
                                  m.Prod(3.47, x33),
                                  m.Prod(2.24, x43),
                                  m.Prod(2.08, x53)),
                            m.Sum(m.Prod(0.25, w13),
                                  m.Prod(0.25, w23),
                                  m.Prod(0.25, w33),
                                  m.Prod(0.25, w43),
                                  m.Prod(0.25, w53))), 20.25);
        cut[6] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x14),
                                  m.Prod(2.98, x24),
                                  m.Prod(3.47, x34),
                                  m.Prod(2.24, x44),
                                  m.Prod(2.08, x54)),
                            m.Sum(m.Prod(0.25, w14),
                                  m.Prod(0.25, w24),
                                  m.Prod(0.25, w34),
                                  m.Prod(0.25, w44),
                                  m.Prod(0.25, w54))), 20.25);
        cut[7] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x15),
                                  m.Prod(2.98, x25),
                                  m.Prod(3.47, x35),
                                  m.Prod(2.24, x45),
                                  m.Prod(2.08, x55)),
                            m.Sum(m.Prod(0.25, w15),
                                  m.Prod(0.25, w25),
                                  m.Prod(0.25, w35),
                                  m.Prod(0.25, w45),
                                  m.Prod(0.25, w55))), 16.25);

        return(cut);
    }
示例#21
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");
        }
    }
示例#22
0
    public static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            Usage();
            return;
        }
        try {
            // Create the modeler/solver object
            Cplex cplex = new Cplex();

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

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

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

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

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

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

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

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

            default:  Usage();
                return;
            }

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


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

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

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

                ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

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

                try { // basis may not exist
                    Cplex.BasisStatus[] cstat =
                        cplex.GetBasisStatuses(lp.NumVars);
                    for (int j = 0; j < x.Length; ++j)
                    {
                        System.Console.WriteLine("Variable " + j + ": Basis Status = " + cstat[j]);
                    }
                }
                catch (System.Exception) {
                }

                System.Console.WriteLine("Maximum bound violation = " +
                                         cplex.GetQuality(Cplex.QualityType.MaxPrimalInfeas));
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
示例#23
0
    public static void Main(string[] args)
    {
        if (args.Length != 1)
        {
            Usage();
            return;
        }
        try {
            Cplex cplex = new Cplex();

            cplex.ImportModel(args[0]);

            /* Set the solution pool relative gap parameter to obtain solutions
             * of objective value within 10% of the optimal */

            cplex.SetParam(Cplex.Param.MIP.Pool.RelGap, 0.1);

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

                // access ILPMatrix object that has been read from file in order to
                // access variables which are the columns of the lp.  Method
                // importModel guarantees to the model into exactly on ILPMatrix
                // object which is why there are no test or iterations needed in the
                // following line of code.

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

                ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

                double[] incx = cplex.GetValues(lp);
                for (int j = 0; j < incx.Length; j++)
                {
                    System.Console.WriteLine("Variable " + j + ": Value = " + incx[j]);
                }
                System.Console.WriteLine();

                /* Get the number of solutions in the solution pool */

                int numsol = cplex.SolnPoolNsolns;
                System.Console.WriteLine("The solution pool contains " + numsol +
                                         " solutions.");

                /* Some solutions are deleted from the pool because of the
                 * solution pool relative gap parameter */

                int numsolreplaced = cplex.SolnPoolNreplaced;
                System.Console.WriteLine(numsolreplaced +
                                         " solutions were removed due to the " +
                                         "solution pool relative gap parameter.");

                System.Console.WriteLine("In total, " + (numsol + numsolreplaced) +
                                         " solutions were generated.");

                /* Get the average objective value of solutions in the
                 * solution pool */

                System.Console.WriteLine(
                    "The average objective value of the solutions is " +
                    cplex.SolnPoolMeanObjValue + ".");

                System.Console.WriteLine();

                /* Write out the objective value of each solution and its
                 * difference to the incumbent */

                for (int i = 0; i < numsol; i++)
                {
                    double[] x = cplex.GetValues(lp, i);

                    /* Compute the number of variables that differ in the
                     * solution and in the incumbent */

                    int numdiff = 0;
                    for (int j = 0; j < x.Length; ++j)
                    {
                        if (System.Math.Abs(x[j] - incx[j]) > EPSZERO)
                        {
                            numdiff++;
                        }
                    }
                    System.Console.WriteLine("Solution " + i +
                                             " with objective " +
                                             cplex.GetObjValue(i) +
                                             " differs in " +
                                             numdiff + " of " + x.Length +
                                             " variables.");
                }
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
示例#24
0
    public static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            Usage();
            return;
        }
        try {
            // Create the modeler/solver object
            Cplex cplex = new Cplex();

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

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

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

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

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

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

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

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

            default:  Usage();
                return;
            }

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


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

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

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

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

                // Basis information is not available for barrier without crossover.
                // Thus we include the query in a try statement and print the solution
                // without barrier information in case we get an exception.
                try {
                    Cplex.BasisStatus[] bStat = cplex.GetBasisStatuses(vars);
                    for (int i = 0; i < vals.Length; i++)
                    {
                        System.Console.WriteLine("Variable " + vars[i].Name +
                                                 " has vals " + vals[i] +
                                                 " and status " + bStat[i]);
                    }
                }
                catch (ILOG.Concert.Exception) {
                    for (int i = 0; i < vals.Length; i++)
                    {
                        System.Console.WriteLine("Variable " + vars[i].Name +
                                                 " has vals " + vals[i]);
                    }
                }
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception exc) {
            System.Console.WriteLine("Concert exception '" + exc + "' caught");
        }
    }
示例#25
0
    internal static void SolveAndDisplay(Cplex cplex, ILPMatrix lp)
    {
        if ( cplex.Solve() ) {
         double[] x     = cplex.GetValues(lp);
         double[] dj    = cplex.GetReducedCosts(lp);
         double[] pi    = cplex.GetDuals(lp);
         double[] slack = cplex.GetSlacks(lp);

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

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

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

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

            Cplex.Aborter myAborter;

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

            case 'l':
                useLoggingCallback = true;
                break;

            case 'a':
                useAborter = true;
                break;

            default:
                Usage();
                return;
            }

            Cplex cplex = new Cplex();

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

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

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

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

            cplex.Solve();

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

            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
示例#27
0
   public static IRange[] MakeCuts(IModeler m, ILPMatrix lp) {
      INumVar x11 = null, x12 = null, x13 = null, x14 = null, x15 = null;
      INumVar x21 = null, x22 = null, x23 = null, x24 = null, x25 = null;
      INumVar x31 = null, x32 = null, x33 = null, x34 = null, x35 = null;
      INumVar x41 = null, x42 = null, x43 = null, x44 = null, x45 = null;
      INumVar x51 = null, x52 = null, x53 = null, x54 = null, x55 = null;
      INumVar w11 = null, w12 = null, w13 = null, w14 = null, w15 = null;
      INumVar w21 = null, w22 = null, w23 = null, w24 = null, w25 = null;
      INumVar w31 = null, w32 = null, w33 = null, w34 = null, w35 = null;
      INumVar w41 = null, w42 = null, w43 = null, w44 = null, w45 = null;
      INumVar w51 = null, w52 = null, w53 = null, w54 = null, w55 = null;

      INumVar[] vars = lp.NumVars;
      int       num  = vars.Length;

      for (int i = 0; i < num; ++i) {
         if      ( vars[i].Name.Equals("X11") ) x11 = vars[i];
         else if ( vars[i].Name.Equals("X12") ) x12 = vars[i];
         else if ( vars[i].Name.Equals("X13") ) x13 = vars[i];
         else if ( vars[i].Name.Equals("X14") ) x14 = vars[i];
         else if ( vars[i].Name.Equals("X15") ) x15 = vars[i];
         else if ( vars[i].Name.Equals("X21") ) x21 = vars[i];
         else if ( vars[i].Name.Equals("X22") ) x22 = vars[i];
         else if ( vars[i].Name.Equals("X23") ) x23 = vars[i];
         else if ( vars[i].Name.Equals("X24") ) x24 = vars[i];
         else if ( vars[i].Name.Equals("X25") ) x25 = vars[i];
         else if ( vars[i].Name.Equals("X31") ) x31 = vars[i];
         else if ( vars[i].Name.Equals("X32") ) x32 = vars[i];
         else if ( vars[i].Name.Equals("X33") ) x33 = vars[i];
         else if ( vars[i].Name.Equals("X34") ) x34 = vars[i];
         else if ( vars[i].Name.Equals("X35") ) x35 = vars[i];
         else if ( vars[i].Name.Equals("X41") ) x41 = vars[i];
         else if ( vars[i].Name.Equals("X42") ) x42 = vars[i];
         else if ( vars[i].Name.Equals("X43") ) x43 = vars[i];
         else if ( vars[i].Name.Equals("X44") ) x44 = vars[i];
         else if ( vars[i].Name.Equals("X45") ) x45 = vars[i];
         else if ( vars[i].Name.Equals("X51") ) x51 = vars[i];
         else if ( vars[i].Name.Equals("X52") ) x52 = vars[i];
         else if ( vars[i].Name.Equals("X53") ) x53 = vars[i];
         else if ( vars[i].Name.Equals("X54") ) x54 = vars[i];
         else if ( vars[i].Name.Equals("X55") ) x55 = vars[i];
         else if ( vars[i].Name.Equals("W11") ) w11 = vars[i];
         else if ( vars[i].Name.Equals("W12") ) w12 = vars[i];
         else if ( vars[i].Name.Equals("W13") ) w13 = vars[i];
         else if ( vars[i].Name.Equals("W14") ) w14 = vars[i];
         else if ( vars[i].Name.Equals("W15") ) w15 = vars[i];
         else if ( vars[i].Name.Equals("W21") ) w21 = vars[i];
         else if ( vars[i].Name.Equals("W22") ) w22 = vars[i];
         else if ( vars[i].Name.Equals("W23") ) w23 = vars[i];
         else if ( vars[i].Name.Equals("W24") ) w24 = vars[i];
         else if ( vars[i].Name.Equals("W25") ) w25 = vars[i];
         else if ( vars[i].Name.Equals("W31") ) w31 = vars[i];
         else if ( vars[i].Name.Equals("W32") ) w32 = vars[i];
         else if ( vars[i].Name.Equals("W33") ) w33 = vars[i];
         else if ( vars[i].Name.Equals("W34") ) w34 = vars[i];
         else if ( vars[i].Name.Equals("W35") ) w35 = vars[i];
         else if ( vars[i].Name.Equals("W41") ) w41 = vars[i];
         else if ( vars[i].Name.Equals("W42") ) w42 = vars[i];
         else if ( vars[i].Name.Equals("W43") ) w43 = vars[i];
         else if ( vars[i].Name.Equals("W44") ) w44 = vars[i];
         else if ( vars[i].Name.Equals("W45") ) w45 = vars[i];
         else if ( vars[i].Name.Equals("W51") ) w51 = vars[i];
         else if ( vars[i].Name.Equals("W52") ) w52 = vars[i];
         else if ( vars[i].Name.Equals("W53") ) w53 = vars[i];
         else if ( vars[i].Name.Equals("W54") ) w54 = vars[i];
         else if ( vars[i].Name.Equals("W55") ) w55 = vars[i];
      }

      IRange[] cut = new IRange[8];

      cut[0] = m.Le(m.Diff(x21, x22), 0.0);
      cut[1] = m.Le(m.Diff(x22, x23), 0.0);
      cut[2] = m.Le(m.Diff(x23, x24), 0.0);
      cut[3] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x11),
                                m.Prod(2.98, x21),
                                m.Prod(3.47, x31),
                                m.Prod(2.24, x41),
                                m.Prod(2.08, x51)),
                          m.Sum(m.Prod(0.25, w11),
                                m.Prod(0.25, w21),
                                m.Prod(0.25, w31),
                                m.Prod(0.25, w41),
                                m.Prod(0.25, w51))), 20.25);
      cut[4] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x12),
                                m.Prod(2.98, x22),
                                m.Prod(3.47, x32),
                                m.Prod(2.24, x42),
                                m.Prod(2.08, x52)),
                          m.Sum(m.Prod(0.25, w12),
                                m.Prod(0.25, w22),
                                m.Prod(0.25, w32),
                                m.Prod(0.25, w42),
                                m.Prod(0.25, w52))), 20.25);
      cut[5] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x13),
                                m.Prod(2.98, x23),
                                m.Prod(3.47, x33),
                                m.Prod(2.24, x43),
                                m.Prod(2.08, x53)),
                          m.Sum(m.Prod(0.25, w13),
                                m.Prod(0.25, w23),
                                m.Prod(0.25, w33),
                                m.Prod(0.25, w43),
                                m.Prod(0.25, w53))), 20.25);
      cut[6] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x14),
                                m.Prod(2.98, x24),
                                m.Prod(3.47, x34),
                                m.Prod(2.24, x44),
                                m.Prod(2.08, x54)),
                          m.Sum(m.Prod(0.25, w14),
                                m.Prod(0.25, w24),
                                m.Prod(0.25, w34),
                                m.Prod(0.25, w44),
                                m.Prod(0.25, w54))), 20.25);
      cut[7] = m.Le(m.Sum(m.Sum(m.Prod(2.08, x15),
                                m.Prod(2.98, x25),
                                m.Prod(3.47, x35),
                                m.Prod(2.24, x45),
                                m.Prod(2.08, x55)),
                          m.Sum(m.Prod(0.25, w15),
                                m.Prod(0.25, w25),
                                m.Prod(0.25, w35),
                                m.Prod(0.25, w45),
                                m.Prod(0.25, w55))), 16.25);

      return cut;
   }
示例#28
0
    public static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            Usage();
            return;
        }
        try {
            Cplex cplex = new Cplex();

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

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

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

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

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

            default:  Usage();
                return;
            }

            cplex.ImportModel(args[0]);


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

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

                ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

                double[] x = cplex.GetValues(lp);
                for (int j = 0; j < x.Length; ++j)
                {
                    System.Console.WriteLine("Variable " + j + ": Value = " + x[j]);
                }
            }
            cplex.End();
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
示例#29
0
        //A quadratic interger program for graph matching,
        //When tuned with the right similarity function it can represent the GED problem.
        // See Pattern Reocgnition Paper paper On the unification of graph matching and graph edit distance paper.
        //The directed version has not been tested yet
        public override void QAPGMGED()
        {
            //some important variables
            int nbNode1       = graph1.ListNodes.Count;
            int nbNode2       = graph2.ListNodes.Count;
            int nbvar         = nbNode1 * nbNode2; // number of variables
            int nbcontraintes = nbNode1 + nbNode2; // number of constraints

            Graphs.Label nodeepslabel;

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

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

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

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

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


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

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


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

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

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

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

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

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

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


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

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

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

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


                #region création fonction objectif

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

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


                #region définition des contraintes du pb

                // We create the constraints

                // The sum of x variables by rows

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

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



                #endregion
            }
            catch (ILOG.Concert.Exception e)
            {
                System.Console.WriteLine("Concert exception `" + e + "` caught");
            }
        }
示例#30
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");
            }
        }
示例#31
0
    public static void Main(string[] args)
    {
        if (args.Length != 2)
        {
            Usage();
            return;
        }
        bool ismip = false;

        try {
            Cplex cplex = new Cplex();

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

            case 'f': cplex.SetParam(Cplex.Param.OptimalityTarget,
                                     Cplex.OptimalityTarget.FirstOrder);
                break;

            case 'g': cplex.SetParam(Cplex.Param.OptimalityTarget,
                                     Cplex.OptimalityTarget.OptimalGlobal);
                break;

            default:  Usage();
                return;
            }

            cplex.ImportModel(args[0]);

            ismip = cplex.IsMIP();

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

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

                ILPMatrix lp = (ILPMatrix)matrixEnum.Current;

                double[] x = cplex.GetValues(lp);
                for (int j = 0; j < x.Length; ++j)
                {
                    System.Console.WriteLine("Variable " + j + ": Value = " + x[j]);
                }
            }
            cplex.End();
        }
        catch (ILOG.CPLEX.CplexModeler.Exception e) {
            if (args[1].ToCharArray()[0] == 'c' &&
                e.GetStatus() == 5002)
            {
                /* Status 5002 is CPXERR_Q_NOT_POS_DEF */
                if (ismip)
                {
                    System.Console.WriteLine("Problem is not convex. Use argument g to get global optimum.");
                }
                else
                {
                    System.Console.Write("Problem is not convex. Use argument f to get local optimum ");
                    System.Console.WriteLine("or g to get global optimum.");
                }
            }
            else if (args[1].ToCharArray()[0] == 'f' &&
                     e.GetStatus() == 1017 &&
                     ismip)
            {
                /* Status 1017 is CPXERR_NOT_FOR_MIP */
                System.Console.Write("Problem is a MIP, cannot compute local optima satifying ");
                System.Console.WriteLine("the first order KKT.");
                System.Console.WriteLine("Use argument g to get the global optimum.");
            }
            else
            {
                System.Console.WriteLine("Cplex exception '" + e + "' caught");
            }
        }
        catch (ILOG.Concert.Exception e) {
            System.Console.WriteLine("Concert exception caught: " + e);
        }
    }
示例#32
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");
            }
        }