public override int AddSos(object solver, string name, int sostype, int priority, int count, int[] sosvars, double[] weights)
        {
            GRBModel grbSolver = solver as GRBModel;

            if (grbSolver == null)
            {
                return(0);
            }
            if ((sostype != 2) & (sostype != 1))
            {
                return(0);
            }
            GRBVar[] sosGrbVars = new GRBVar[count];
            GRBVar[] allgrbVars = grbSolver.GetVars();
            for (int i = 0; i < count; i++)
            {
                sosGrbVars[i] = allgrbVars[sosvars[i]];
            }
            if (sostype == 2)
            {
                grbSolver.AddSOS(sosGrbVars, weights, GRB.SOS_TYPE2);
            }
            if (sostype == 1)
            {
                grbSolver.AddSOS(sosGrbVars, weights, GRB.SOS_TYPE1);
            }

            return(1);
        }
Example #2
0
        private void StoreAllSolutions(GRBModel model)
        {
            _model.Solutions.Clear();

            for (var i = 0; i < model.SolCount; i++)
            {
                model.Parameters.SolutionNumber = i;

                var vars = model.GetVars();

                var solution = new SolutionModel();
                var currentSolutionObjective = 0.0;

                for (var j = 0; j < model.NumVars; ++j)
                {
                    var sv = vars[j];

                    var name       = sv.VarName;
                    var splitName  = name.Split('_');
                    var id         = int.Parse(splitName[1]);
                    var lod        = int.Parse(splitName[3]);
                    var visibility = sv.Xn;

                    solution.AddEntry(id, lod, visibility);

                    var objective = sv.Obj * sv.Xn;
                    currentSolutionObjective += objective;
                }

                solution.Objective = currentSolutionObjective;
                _model.Solutions.Add(solution);
            }
        }
 static void PrintSolution(GRBModel m)
 {
     foreach (GRBVar var in m.GetVars())
     {
         Console.WriteLine("{0} = {1}", var.Get(GRB.StringAttr.VarName), var.Get(GRB.DoubleAttr.X));
     }
 }
Example #4
0
        static void Main(string[] args)
        {
            GRBEnv   env = new GRBEnv();
            GRBModel m   = new GRBModel(env);
            GRBVar   x1  = m.AddVar(0, GRB.INFINITY, 20, GRB.CONTINUOUS, "food.1");
            GRBVar   x2  = m.AddVar(0, GRB.INFINITY, 10, GRB.CONTINUOUS, "food.2");
            GRBVar   x3  = m.AddVar(0, GRB.INFINITY, 31, GRB.CONTINUOUS, "food.3");
            GRBVar   x4  = m.AddVar(0, GRB.INFINITY, 11, GRB.CONTINUOUS, "food.4");
            GRBVar   x5  = m.AddVar(0, GRB.INFINITY, 12, GRB.CONTINUOUS, "food.5");

            m.Update();
            GRBConstr con1 = m.AddConstr(2 * x1 + 3 * x3 + 1 * x4 + 2 * x5 >= 21, "nutrient.iron");
            GRBConstr con2 = m.AddConstr(1 * x2 + 2 * x3 + 2 * x4 + 1 * x5 >= 12, "nutrient.calcium");

            m.Optimize();
            m.Write("diet.lp");
            foreach (GRBVar var in m.GetVars())
            {
                Console.WriteLine("{0} = {1}, reduced cost = {2}", var.Get(GRB.StringAttr.VarName), var.Get(GRB.DoubleAttr.X), var.Get(GRB.DoubleAttr.RC));
            }
            foreach (GRBConstr constr in m.GetConstrs())
            {
                Console.WriteLine("{0}, slack = {1}, pi = {2}", constr.Get(GRB.StringAttr.ConstrName), constr.Get(GRB.DoubleAttr.Slack), constr.Get(GRB.DoubleAttr.Pi));
            }
            m.Dispose();
            env.Dispose();
        }
Example #5
0
 private void OutputSolution_SchemeSub()
 {
     Console.WriteLine("SchemeSub----");
     GRBVar[] varArray = _grbModel_SchemeGenerateSub.GetVars();
     foreach (GRBVar v in varArray)
     {
         Console.WriteLine("{0}:{1}", v.VarName, v.X);
     }
 }
Example #6
0
 private void OutputValue()
 {
     Console.WriteLine("FASub----");
     GRBVar[] varArray = _grbModel_FlowAssignmentSub.GetVars();
     foreach (GRBVar v in varArray)
     {
         Console.WriteLine("{0}:{1}", v.VarName, v.X);
     }
 }
        public override bool DelColumn(object solver, int column)
        {
            GRBModel model = solver as GRBModel;

            if (model == null)
            {
                return(false);
            }
            model.Remove(model.GetVars()[column]);
            model.Update();
            return(true);
        }
Example #8
0
 private void OutputSolution()
 {
     GRBVar[]    varArray   = _grbModelMaster.GetVars();
     GRBConstr[] constArray = _grbModelMaster.GetConstrs();
     foreach (GRBVar v in varArray)
     {
         Console.WriteLine("{0}:{1}", v.VarName, v.X);
     }
     foreach (GRBConstr ct in constArray)
     {
         Console.WriteLine("{0}:{1}", ct.ConstrName, ct.Pi);
     }
 }
        public override bool SetObjFn(object solver, double[] row)
        {
            GRBModel grbSolver = solver as GRBModel;

            if (grbSolver == null)
            {
                return(false);
            }
            GRBLinExpr obj = new GRBLinExpr();

            obj.AddTerms(row, grbSolver.GetVars());
            grbSolver.SetObjective(obj, GRB.MINIMIZE);
            return(true);
        }
        public override bool AddConstraint(object solver, double[] row, SolverAdapterConstraintTypes constr_type, double rh)
        {
            GRBModel grbSolver = solver as GRBModel;

            if (grbSolver == null)
            {
                return(false);
            }
            GRBLinExpr expr = 0.0;

            ind++;
            expr.AddTerms(row, grbSolver.GetVars());
            grbSolver.AddConstr(expr, (char)GetAdaptedConstraintType(constr_type), rh, "R" + ind);
            return(true);
        }
        public override bool GetVariables(object solver, double[] var)
        {
            GRBModel grbSolver = solver as GRBModel;

            if (grbSolver == null)
            {
                return(false);
            }
            GRBVar[] vars = grbSolver.GetVars();
            for (int i = 0; i < var.Length; i++)
            {
                var[i] = vars[i].X;
            }
            return(true);
        }
Example #12
0
        private static void OutputDebugVars(GRBModel model)
        {
            for (var s = 0; s < model.SolCount; s++)
            {
                model.Parameters.SolutionNumber = s;

                GRBVar[] vars = model.GetVars();
                for (var i = 0; i < model.NumVars; ++i)
                {
                    GRBVar sv = vars[i];
                    if (sv.Xn > 1e-6)
                    {
                        Console.WriteLine(@"s_" + s + @"  " + sv.VarName + @" = " + sv.Xn);
                    }
                }
            }
        }
 /// <summary>
 ///     Checks whether the given Gurobi model has found a feasible solution.
 /// </summary>
 /// <param name="model">Model to check.</param>
 /// <returns>Whether the model has found a feasible solution.</returns>
 private bool HasFoundSolution(GRBModel model)
 {
     // Handling model.status is an overkill here, so we use the following hack:
     try
     {
         // Check if the first variable is set.
         var firstVariable = model.GetVars()[0];
         firstVariable.Get(GRB.DoubleAttr.X);
         // If it is, we have a solution.
         return(true);
     }
     catch (GRBException)
     {
         // But if it throws an exception, we don't.
         return(false);
     }
 }
Example #14
0
        //private void UpdateModels(GRBModel model, List<List<GRBVar>> varsFromElements)
        //{
        //    if (Constants.ENABLE_DEBUG_OUTPUT)
        //        OutputDebugVars(model);

        //    for (var i = 0; i < varsFromElements.Count; i++)
        //    {
        //        var currentElement = _model.Elements[i];
        //        var currentElementVars = varsFromElements[i];
        //        var lod = -1;

        //        for (var j = 0; j < currentElementVars.Count; j++)
        //        {
        //            if (currentElementVars[j].Xn > 1e-6)
        //            {
        //                lod = j + 1;
        //            }
        //        }

        //        if (lod > -1)
        //        {
        //            currentElement.Visibility = 1.0f;
        //            currentElement.CurrentLevelOfDetail = lod;
        //        }
        //        else
        //        {
        //            currentElement.Visibility = 0.0f;
        //        }
        //    }
        //}

        private static void OutputDebugVars(GRBModel model)
        {
            var debugString = Environment.NewLine;

            for (var s = 0; s < model.SolCount; s++)
            {
                model.Parameters.SolutionNumber = s;

                GRBVar[] vars = model.GetVars();
                for (var i = 0; i < model.NumVars; ++i)
                {
                    GRBVar sv = vars[i];
                    if (sv.Xn > 1e-6)
                    {
                        debugString += @"s_" + s + @"  " + sv.VarName + @" = " + sv.Xn + Environment.NewLine;
                    }
                }
                Debug.Log(debugString);
                debugString = Environment.NewLine;
            }
        }
Example #15
0
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: callback_cs filename");
            return;
        }

        try {
            GRBEnv   env   = new GRBEnv();
            GRBModel model = new GRBModel(env, args[0]);

            GRBVar[] vars = model.GetVars();

            // Create a callback object and associate it with the model
            model.SetCallback(new callback_cs(vars));
            model.Optimize();

            double[] x      = model.Get(GRB.DoubleAttr.X, vars);
            string[] vnames = model.Get(GRB.StringAttr.VarName, vars);

            for (int j = 0; j < vars.Length; j++)
            {
                if (x[j] != 0.0)
                {
                    Console.WriteLine(vnames[j] + " " + x[j]);
                }
            }

            // Dispose of model and env
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
            Console.WriteLine(e.StackTrace);
        }
    }
Example #16
0
    ///<summary>Create a batch request for given problem file</summary>
    static string newbatchrequest(string filename)
    {
        string batchID = "";
        // Start environment, create Model object from file
        GRBEnv env = setupbatchenv();

        env.Start();
        GRBModel model = new GRBModel(env, filename);

        try {
            // Set some parameters
            model.Set(GRB.DoubleParam.MIPGap, 0.01);
            model.Set(GRB.IntParam.JSONSolDetail, 1);

            // Define tags for some variables to access their values later
            int count = 0;
            foreach (GRBVar v in model.GetVars())
            {
                v.VTag = "Variable" + count;
                count += 1;
                if (count >= 10)
                {
                    break;
                }
            }

            // Submit batch request
            batchID = model.OptimizeBatch();

            // Dispose of model and env
        } finally {
            model.Dispose();
            env.Dispose();
        }
        return(batchID);
    }
Example #17
0
    static void Main(string[] args)
    {
        if (args.Length < 1) {
          Console.Out.WriteLine("Usage: callback_cs filename");
          return;
        }

        try {
          GRBEnv    env   = new GRBEnv();
          GRBModel  model = new GRBModel(env, args[0]);

          GRBVar[] vars   = model.GetVars();

          model.SetCallback(new callback_cs(vars));
          model.Optimize();

          double[] x      = model.Get(GRB.DoubleAttr.X, vars);
          string[] vnames = model.Get(GRB.StringAttr.VarName, vars);

          for (int j = 0; j < vars.Length; j++) {
        if (x[j] != 0.0) Console.WriteLine(vnames[j] + " " + x[j]);
          }

          for (int j = 0; j < vars.Length; j++) {
        if (x[j] != 0.0) Console.WriteLine(vnames[j] + " " + x[j]);
          }

          // Dispose of model and env
          model.Dispose();
          env.Dispose();

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
          Console.WriteLine(e.StackTrace);
        }
    }
Example #18
0
    static void Main(string[] args)
    {
        const int maxscenarios = sensitivity_cs.MAXSCENARIOS;

        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: sensitivity_cs filename");
            return;
        }

        try {
            // Create environment
            GRBEnv env = new GRBEnv();

            // Read model
            GRBModel model = new GRBModel(env, args[0]);

            int scenarios;

            if (model.IsMIP == 0)
            {
                Console.WriteLine("Model is not a MIP");
                return;
            }

            // Solve model
            model.Optimize();

            if (model.Status != GRB.Status.OPTIMAL)
            {
                Console.WriteLine("Optimization ended with status " + model.Status);
                return;
            }

            // Store the optimal solution
            double   origObjVal = model.ObjVal;
            GRBVar[] vars       = model.GetVars();
            double[] origX      = model.Get(GRB.DoubleAttr.X, vars);

            scenarios = 0;

            // Count number of unfixed, binary variables in model. For each we
            // create a scenario.
            for (int i = 0; i < vars.Length; i++)
            {
                GRBVar v     = vars[i];
                char   vType = v.VType;

                if (v.LB == 0.0 && v.UB == 1.0 &&
                    (vType == GRB.BINARY || vType == GRB.INTEGER))
                {
                    scenarios++;

                    if (scenarios >= maxscenarios)
                    {
                        break;
                    }
                }
            }

            Console.WriteLine("###  construct multi-scenario model with "
                              + scenarios + " scenarios");

            // Set the number of scenarios in the model */
            model.NumScenarios = scenarios;

            scenarios = 0;

            // Create a (single) scenario model by iterating through unfixed
            // binary variables in the model and create for each of these
            // variables a scenario by fixing the variable to 1-X, where X is its
            // value in the computed optimal solution
            for (int i = 0; i < vars.Length; i++)
            {
                GRBVar v     = vars[i];
                char   vType = v.VType;

                if (v.LB == 0.0 && v.UB == 1.0 &&
                    (vType == GRB.BINARY || vType == GRB.INTEGER) &&
                    scenarios < maxscenarios)
                {
                    // Set ScenarioNumber parameter to select the corresponding
                    // scenario for adjustments
                    model.Parameters.ScenarioNumber = scenarios;

                    // Set variable to 1-X, where X is its value in the optimal solution */
                    if (origX[i] < 0.5)
                    {
                        v.ScenNLB = 1.0;
                    }
                    else
                    {
                        v.ScenNUB = 0.0;
                    }

                    scenarios++;
                }
                else
                {
                    // Add MIP start for all other variables using the optimal solution
                    // of the base model
                    v.Start = origX[i];
                }
            }

            // Solve multi-scenario model
            model.Optimize();

            // In case we solved the scenario model to optimality capture the
            // sensitivity information
            if (model.Status == GRB.Status.OPTIMAL)
            {
                // get the model sense (minimization or maximization)
                int modelSense = model.ModelSense;

                scenarios = 0;

                for (int i = 0; i < vars.Length; i++)
                {
                    GRBVar v     = vars[i];
                    char   vType = v.VType;

                    if (v.LB == 0.0 && v.UB == 1.0 &&
                        (vType == GRB.BINARY || vType == GRB.INTEGER))
                    {
                        // Set scenario parameter to collect the objective value of the
                        // corresponding scenario
                        model.Parameters.ScenarioNumber = scenarios;

                        double scenarioObjVal   = model.ScenNObjVal;
                        double scenarioObjBound = model.ScenNObjBound;

                        Console.Write("Objective sensitivity for variable "
                                      + v.VarName + " is ");

                        // Check if we found a feasible solution for this scenario
                        if (scenarioObjVal >= modelSense * GRB.INFINITY)
                        {
                            // Check if the scenario is infeasible
                            if (scenarioObjBound >= modelSense * GRB.INFINITY)
                            {
                                Console.WriteLine("infeasible");
                            }
                            else
                            {
                                Console.WriteLine("unknown (no solution available)");
                            }
                        }
                        else
                        {
                            // Scenario is feasible and a solution is available
                            Console.WriteLine(modelSense * (scenarioObjVal - origObjVal));
                        }

                        scenarios++;

                        if (scenarios >= maxscenarios)
                        {
                            break;
                        }
                    }
                }
            }

            // Dispose of model and environment
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode);
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        }
    }
Example #19
0
    static void Main()
    {
        try {
            // Sample data
            // Sets of days and workers
            string[] Shifts =
                new string[] { "Mon1", "Tue2", "Wed3", "Thu4", "Fri5", "Sat6",
                               "Sun7", "Mon8", "Tue9", "Wed10", "Thu11", "Fri12", "Sat13",
                               "Sun14" };
            string[] Workers =
                new string[] { "Amy", "Bob", "Cathy", "Dan", "Ed", "Fred", "Gu" };

            int nShifts  = Shifts.Length;
            int nWorkers = Workers.Length;

            // Number of workers required for each shift
            double[] shiftRequirements =
                new double[] { 3, 2, 4, 4, 5, 6, 5, 2, 2, 3, 4, 6, 7, 5 };

            // Amount each worker is paid to work one shift
            double[] pay = new double[] { 10, 12, 10, 8, 8, 9, 11 };

            // Worker availability: 0 if the worker is unavailable for a shift
            double[,] availability =
                new double[, ] {
                { 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1 },
                { 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0 },
                { 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },
                { 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1 },
                { 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1 },
                { 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1 },
                { 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
            };

            // Model
            GRBEnv   env   = new GRBEnv();
            GRBModel model = new GRBModel(env);

            model.ModelName = "assignment";

            // Assignment variables: x[w][s] == 1 if worker w is assigned
            // to shift s. Since an assignment model always produces integer
            // solutions, we use continuous variables and solve as an LP.
            GRBVar[,] x = new GRBVar[nWorkers, nShifts];
            for (int w = 0; w < nWorkers; ++w)
            {
                for (int s = 0; s < nShifts; ++s)
                {
                    x[w, s] =
                        model.AddVar(0, availability[w, s], pay[w], GRB.CONTINUOUS,
                                     Workers[w] + "." + Shifts[s]);
                }
            }

            // The objective is to minimize the total pay costs
            model.ModelSense = GRB.MINIMIZE;

            // Constraint: assign exactly shiftRequirements[s] workers
            // to each shift s
            for (int s = 0; s < nShifts; ++s)
            {
                GRBLinExpr lhs = 0.0;
                for (int w = 0; w < nWorkers; ++w)
                {
                    lhs.AddTerm(1.0, x[w, s]);
                }
                model.AddConstr(lhs == shiftRequirements[s], Shifts[s]);
            }

            // Optimize
            model.Optimize();
            int status = model.Status;
            if (status == GRB.Status.UNBOUNDED)
            {
                Console.WriteLine("The model cannot be solved "
                                  + "because it is unbounded");
                return;
            }
            if (status == GRB.Status.OPTIMAL)
            {
                Console.WriteLine("The optimal objective is " + model.ObjVal);
                return;
            }
            if ((status != GRB.Status.INF_OR_UNBD) &&
                (status != GRB.Status.INFEASIBLE))
            {
                Console.WriteLine("Optimization was stopped with status " + status);
                return;
            }

            // Relax the constraints to make the model feasible
            Console.WriteLine("The model is infeasible; relaxing the constraints");
            int orignumvars = model.NumVars;
            model.FeasRelax(0, false, false, true);
            model.Optimize();
            status = model.Status;
            if ((status == GRB.Status.INF_OR_UNBD) ||
                (status == GRB.Status.INFEASIBLE) ||
                (status == GRB.Status.UNBOUNDED))
            {
                Console.WriteLine("The relaxed model cannot be solved "
                                  + "because it is infeasible or unbounded");
                return;
            }
            if (status != GRB.Status.OPTIMAL)
            {
                Console.WriteLine("Optimization was stopped with status " + status);
                return;
            }

            Console.WriteLine("\nSlack values:");
            GRBVar[] vars = model.GetVars();
            for (int i = orignumvars; i < model.NumVars; ++i)
            {
                GRBVar sv = vars[i];
                if (sv.X > 1e-6)
                {
                    Console.WriteLine(sv.VarName + " = " + sv.X);
                }
            }

            // Dispose of model and environment
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " +
                              e.Message);
        }
    }
Example #20
0
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: callback_cs filename");
            return;
        }

        StreamWriter logfile = null;

        try {
            // Create environment
            GRBEnv env = new GRBEnv();

            // Read model from file
            GRBModel model = new GRBModel(env, args[0]);

            // Turn off display and heuristics
            model.Parameters.OutputFlag = 0;
            model.Parameters.Heuristics = 0.0;

            // Open log file
            logfile = new StreamWriter("cb.log");

            // Create a callback object and associate it with the model
            GRBVar[]    vars = model.GetVars();
            callback_cs cb   = new callback_cs(vars, logfile);

            model.SetCallback(cb);

            // Solve model and capture solution information
            model.Optimize();

            Console.WriteLine("");
            Console.WriteLine("Optimization complete");
            if (model.SolCount == 0)
            {
                Console.WriteLine("No solution found, optimization status = "
                                  + model.Status);
            }
            else
            {
                Console.WriteLine("Solution found, objective = " + model.ObjVal);

                string[] vnames = model.Get(GRB.StringAttr.VarName, vars);
                double[] x      = model.Get(GRB.DoubleAttr.X, vars);

                for (int j = 0; j < vars.Length; j++)
                {
                    if (x[j] != 0.0)
                    {
                        Console.WriteLine(vnames[j] + " " + x[j]);
                    }
                }
            }

            // Dispose of model and environment
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode);
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        } catch (Exception e) {
            Console.WriteLine("Error during optimization");
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        } finally {
            // Close log file
            if (logfile != null)
            {
                logfile.Close();
            }
        }
    }
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: sensitivity_cs filename");
            return;
        }

        try {
            // Create environment

            GRBEnv env = new GRBEnv();

            // Read and solve model

            GRBModel model = new GRBModel(env, args[0]);

            if (model.IsMIP == 0)
            {
                Console.WriteLine("Model is not a MIP");
                return;
            }

            model.Optimize();

            if (model.Status != GRB.Status.OPTIMAL)
            {
                Console.WriteLine("Optimization ended with status " + model.Status);
                return;
            }

            // Store the optimal solution

            double   origObjVal = model.ObjVal;
            GRBVar[] vars       = model.GetVars();
            double[] origX      = model.Get(GRB.DoubleAttr.X, vars);

            // Disable solver output for subsequent solves

            model.Parameters.OutputFlag = 0;

            // Iterate through unfixed, binary variables in model

            for (int i = 0; i < vars.Length; i++)
            {
                GRBVar v     = vars[i];
                char   vType = v.VType;

                if (v.LB == 0 && v.UB == 1 &&
                    (vType == GRB.BINARY || vType == GRB.INTEGER))
                {
                    // Set variable to 1-X, where X is its value in optimal solution

                    if (origX[i] < 0.5)
                    {
                        v.LB    = 1.0;
                        v.Start = 1.0;
                    }
                    else
                    {
                        v.UB    = 0.0;
                        v.Start = 0.0;
                    }

                    // Update MIP start for the other variables

                    for (int j = 0; j < vars.Length; j++)
                    {
                        if (j != i)
                        {
                            vars[j].Start = origX[j];
                        }
                    }

                    // Solve for new value and capture sensitivity information

                    model.Optimize();

                    if (model.Status == GRB.Status.OPTIMAL)
                    {
                        Console.WriteLine("Objective sensitivity for variable "
                                          + v.VarName + " is " + (model.ObjVal - origObjVal));
                    }
                    else
                    {
                        Console.WriteLine("Objective sensitivity for variable "
                                          + v.VarName + " is infinite");
                    }

                    // Restore the original variable bounds

                    v.LB = 0.0;
                    v.UB = 1.0;
                }
            }

            // Dispose of model and environment

            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode);
            Console.WriteLine(e.Message);
            Console.WriteLine(e.StackTrace);
        }
    }
Example #22
0
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: sensitivity_cs filename");
            return;
        }

        try {
            // Read model
            GRBEnv   env = new GRBEnv();
            GRBModel a   = new GRBModel(env, args[0]);
            a.Optimize();
            a.GetEnv().Set(GRB.IntParam.OutputFlag, 0);

            // Extract variables from model
            GRBVar[] avars = a.GetVars();

            for (int i = 0; i < avars.Length; ++i)
            {
                GRBVar v = avars[i];
                if (v.Get(GRB.CharAttr.VType) == GRB.BINARY)
                {
                    // Create clone and fix variable
                    GRBModel b  = new GRBModel(a);
                    GRBVar   bv = b.GetVars()[i];
                    if (v.Get(GRB.DoubleAttr.X) - v.Get(GRB.DoubleAttr.LB) < 0.5)
                    {
                        bv.Set(GRB.DoubleAttr.LB, bv.Get(GRB.DoubleAttr.UB));
                    }
                    else
                    {
                        bv.Set(GRB.DoubleAttr.UB, bv.Get(GRB.DoubleAttr.LB));
                    }

                    b.Optimize();

                    if (b.Get(GRB.IntAttr.Status) == GRB.Status.OPTIMAL)
                    {
                        double objchg =
                            b.Get(GRB.DoubleAttr.ObjVal) - a.Get(GRB.DoubleAttr.ObjVal);
                        if (objchg < 0)
                        {
                            objchg = 0;
                        }
                        Console.WriteLine("Objective sensitivity for variable " +
                                          v.Get(GRB.StringAttr.VarName) + " is " + objchg);
                    }
                    else
                    {
                        Console.WriteLine("Objective sensitivity for variable " +
                                          v.Get(GRB.StringAttr.VarName) + " is infinite");
                    }

                    // Dispose of model
                    b.Dispose();
                }
            }

            // Dispose of model and env
            a.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " +
                              e.Message);
        }
    }
Example #23
0
    static void Main(string[] args)
    {
        if (args.Length < 1) {
          Console.Out.WriteLine("Usage: mip2_cs filename");
          return;
        }

        try {
          GRBEnv    env   = new GRBEnv();
          GRBModel  model = new GRBModel(env, args[0]);
          if (model.Get(GRB.IntAttr.IsMIP) == 0) {
        Console.WriteLine("Model is not a MIP");
        return;
          }

          model.Optimize();

          int optimstatus = model.Get(GRB.IntAttr.Status);
          double objval = 0;
          if (optimstatus == GRB.Status.OPTIMAL) {
        objval = model.Get(GRB.DoubleAttr.ObjVal);
        Console.WriteLine("Optimal objective: " + objval);
          } else if (optimstatus == GRB.Status.INF_OR_UNBD) {
        Console.WriteLine("Model is infeasible or unbounded");
        return;
          } else if (optimstatus == GRB.Status.INFEASIBLE) {
        Console.WriteLine("Model is infeasible");
        return;
          } else if (optimstatus == GRB.Status.UNBOUNDED) {
        Console.WriteLine("Model is unbounded");
        return;
          } else {
        Console.WriteLine("Optimization was stopped with status = "
                           + optimstatus);
        return;
          }

          /* Iterate over the solutions and compute the objectives */

          GRBVar[] vars = model.GetVars();
          model.GetEnv().Set(GRB.IntParam.OutputFlag, 0);

          Console.WriteLine();
          for (int k = 0; k < model.Get(GRB.IntAttr.SolCount); ++k) {
        model.GetEnv().Set(GRB.IntParam.SolutionNumber, k);
        double objn = 0.0;

        for (int j = 0; j < vars.Length; j++) {
          objn += vars[j].Get(GRB.DoubleAttr.Obj)
            * vars[j].Get(GRB.DoubleAttr.Xn);
        }

        Console.WriteLine("Solution " + k + " has objective: " + objn);
          }
          Console.WriteLine();
          model.GetEnv().Set(GRB.IntParam.OutputFlag, 1);

          /* Create a fixed model, turn off presolve and solve */

          GRBModel fixedmodel = model.FixedModel();

          fixedmodel.GetEnv().Set(GRB.IntParam.Presolve, 0);

          fixedmodel.Optimize();

          int foptimstatus = fixedmodel.Get(GRB.IntAttr.Status);

          if (foptimstatus != GRB.Status.OPTIMAL) {
        Console.WriteLine("Error: fixed model isn't optimal");
        return;
          }

          double fobjval = fixedmodel.Get(GRB.DoubleAttr.ObjVal);

          if (Math.Abs(fobjval - objval) > 1.0e-6 * (1.0 + Math.Abs(objval))) {
        Console.WriteLine("Error: objective values are different");
        return;
          }

          GRBVar[] fvars  = fixedmodel.GetVars();
          double[] x      = fixedmodel.Get(GRB.DoubleAttr.X, fvars);
          string[] vnames = fixedmodel.Get(GRB.StringAttr.VarName, fvars);

          for (int j = 0; j < fvars.Length; j++) {
        if (x[j] != 0.0) Console.WriteLine(vnames[j] + " " + x[j]);
          }

          // Dispose of models and env
          fixedmodel.Dispose();
          model.Dispose();
          env.Dispose();

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Example #24
0
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: fixanddive_cs filename");
            return;
        }

        try {
            // Read model
            GRBEnv   env   = new GRBEnv();
            GRBModel model = new GRBModel(env, args[0]);

            // Collect integer variables and relax them
            List <GRBVar> intvars = new List <GRBVar>();
            foreach (GRBVar v in model.GetVars())
            {
                if (v.VType != GRB.CONTINUOUS)
                {
                    intvars.Add(v);
                    v.VType = GRB.CONTINUOUS;
                }
            }

            model.Parameters.OutputFlag = 0;
            model.Optimize();

            // Perform multiple iterations. In each iteration, identify the first
            // quartile of integer variables that are closest to an integer value
            // in the relaxation, fix them to the nearest integer, and repeat.

            for (int iter = 0; iter < 1000; ++iter)
            {
                // create a list of fractional variables, sorted in order of
                // increasing distance from the relaxation solution to the nearest
                // integer value

                List <GRBVar> fractional = new List <GRBVar>();
                foreach (GRBVar v in intvars)
                {
                    double sol = Math.Abs(v.X);
                    if (Math.Abs(sol - Math.Floor(sol + 0.5)) > 1e-5)
                    {
                        fractional.Add(v);
                    }
                }

                Console.WriteLine("Iteration " + iter + ", obj " +
                                  model.ObjVal + ", fractional " + fractional.Count);

                if (fractional.Count == 0)
                {
                    Console.WriteLine("Found feasible solution - objective " +
                                      model.ObjVal);
                    break;
                }

                // Fix the first quartile to the nearest integer value

                fractional.Sort(new FractionalCompare());
                int nfix = Math.Max(fractional.Count / 4, 1);
                for (int i = 0; i < nfix; ++i)
                {
                    GRBVar v      = fractional[i];
                    double fixval = Math.Floor(v.X + 0.5);
                    v.LB = fixval;
                    v.UB = fixval;
                    Console.WriteLine("  Fix " + v.VarName +
                                      " to " + fixval + " ( rel " + v.X + " )");
                }

                model.Optimize();

                // Check optimization result

                if (model.Status != GRB.Status.OPTIMAL)
                {
                    Console.WriteLine("Relaxation is infeasible");
                    break;
                }
            }

            // Dispose of model and env
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " +
                              e.Message);
        }
    }
Example #25
0
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: mip2_cs filename");
            return;
        }

        try {
            GRBEnv   env   = new GRBEnv();
            GRBModel model = new GRBModel(env, args[0]);
            if (model.IsMIP == 0)
            {
                Console.WriteLine("Model is not a MIP");
                return;
            }

            model.Optimize();

            int    optimstatus = model.Status;
            double objval      = 0;
            if (optimstatus == GRB.Status.OPTIMAL)
            {
                objval = model.ObjVal;
                Console.WriteLine("Optimal objective: " + objval);
            }
            else if (optimstatus == GRB.Status.INF_OR_UNBD)
            {
                Console.WriteLine("Model is infeasible or unbounded");
                return;
            }
            else if (optimstatus == GRB.Status.INFEASIBLE)
            {
                Console.WriteLine("Model is infeasible");
                return;
            }
            else if (optimstatus == GRB.Status.UNBOUNDED)
            {
                Console.WriteLine("Model is unbounded");
                return;
            }
            else
            {
                Console.WriteLine("Optimization was stopped with status = "
                                  + optimstatus);
                return;
            }

            /* Iterate over the solutions and compute the objectives */

            GRBVar[] vars = model.GetVars();
            model.Parameters.OutputFlag = 0;

            Console.WriteLine();
            for (int k = 0; k < model.SolCount; ++k)
            {
                model.Parameters.SolutionNumber = k;
                double objn = 0.0;

                for (int j = 0; j < vars.Length; j++)
                {
                    objn += vars[j].Obj * vars[j].Xn;
                }

                Console.WriteLine("Solution " + k + " has objective: " + objn);
            }
            Console.WriteLine();
            model.Parameters.OutputFlag = 1;

            /* Create a fixed model, turn off presolve and solve */

            GRBModel fixedmodel = model.FixedModel();

            fixedmodel.Parameters.Presolve = 0;

            fixedmodel.Optimize();

            int foptimstatus = fixedmodel.Status;

            if (foptimstatus != GRB.Status.OPTIMAL)
            {
                Console.WriteLine("Error: fixed model isn't optimal");
                return;
            }

            double fobjval = fixedmodel.ObjVal;

            if (Math.Abs(fobjval - objval) > 1.0e-6 * (1.0 + Math.Abs(objval)))
            {
                Console.WriteLine("Error: objective values are different");
                return;
            }

            GRBVar[] fvars  = fixedmodel.GetVars();
            double[] x      = fixedmodel.Get(GRB.DoubleAttr.X, fvars);
            string[] vnames = fixedmodel.Get(GRB.StringAttr.VarName, fvars);

            for (int j = 0; j < fvars.Length; j++)
            {
                if (x[j] != 0.0)
                {
                    Console.WriteLine(vnames[j] + " " + x[j]);
                }
            }

            // Dispose of models and env
            fixedmodel.Dispose();
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Example #26
0
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: lpmod_cs filename");
            return;
        }

        try {
            // Read model and determine whether it is an LP
            GRBEnv   env   = new GRBEnv();
            GRBModel model = new GRBModel(env, args[0]);
            if (model.IsMIP != 0)
            {
                Console.WriteLine("The model is not a linear program");
                Environment.Exit(1);
            }

            model.Optimize();

            int status = model.Status;

            if ((status == GRB.Status.INF_OR_UNBD) ||
                (status == GRB.Status.INFEASIBLE) ||
                (status == GRB.Status.UNBOUNDED))
            {
                Console.WriteLine("The model cannot be solved because it is "
                                  + "infeasible or unbounded");
                Environment.Exit(1);
            }

            if (status != GRB.Status.OPTIMAL)
            {
                Console.WriteLine("Optimization was stopped with status " + status);
                Environment.Exit(0);
            }

            // Find the smallest variable value
            double minVal = GRB.INFINITY;
            GRBVar minVar = null;
            foreach (GRBVar v in model.GetVars())
            {
                double sol = v.X;
                if ((sol > 0.0001) && (sol < minVal) && (v.LB == 0.0))
                {
                    minVal = sol;
                    minVar = v;
                }
            }

            Console.WriteLine("\n*** Setting " +
                              minVar.VarName + " from " + minVal +
                              " to zero ***\n");
            minVar.UB = 0.0;

            // Solve from this starting point
            model.Optimize();

            // Save iteration & time info
            double warmCount = model.IterCount;
            double warmTime  = model.Runtime;

            // Reset the model and resolve
            Console.WriteLine("\n*** Resetting and solving "
                              + "without an advanced start ***\n");
            model.Reset();
            model.Optimize();

            double coldCount = model.IterCount;
            double coldTime  = model.Runtime;

            Console.WriteLine("\n*** Warm start: " + warmCount + " iterations, " +
                              warmTime + " seconds");
            Console.WriteLine("*** Cold start: " + coldCount + " iterations, " +
                              coldTime + " seconds");

            // Dispose of model and env
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " +
                              e.Message);
        }
    }
Example #27
0
        public static Graph RunSolver(Graph graph)
        {
            GRBEnv env = new GRBEnv();
            env.Set(GRB.IntParam.OutputFlag, 0);
            env.Set(GRB.IntParam.LogToConsole, 0);
            env.Set(GRB.IntParam.Presolve, 2);
            env.Set(GRB.DoubleParam.Heuristics, 0.0);
            GRBModel model = new GRBModel(env);
            GRBVar[] variables = new GRBVar[graph.NumberOfEdges];
            model.SetCallback(new LPSolverCallback());
            Dictionary<Edge, GRBVar> edgeVars = new Dictionary<Edge, GRBVar>();

            // Add variables to the LP model
            for (int i = 0; i < graph.NumberOfEdges; i++)
            {
                variables[i] = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "x_" + i);
                edgeVars.Add(graph.Edges[i], variables[i]);
            }
            model.Update();

            // Add constraints to the LP model
            Console.Write("\rRunning LP. Creating constraints...\r");
            //var nonTerminals = graph.Vertices.Except(graph.Terminals).ToList();
            ulong conNr = 0;
            //var terminalCombinations = new List<List<Vertex>>();

            // Assume, without loss of generality, that Terminals[0] is the root, and thus is always included
            int rootNr = 1;
            foreach (var rootTerminal in graph.Terminals)
            //var rootTerminal = graph.Terminals[0];
            {
                Console.Write("\rRunning LP. Creating constraints... {0}/{1}\r", rootNr, graph.Terminals.Count);
                foreach (var combination in GetBFS(graph, rootTerminal))
                {
                    var nodes = combination.ToList(); //new HashSet<Vertex>(combination);
                    if (nodes.Count == graph.NumberOfVertices || graph.Terminals.All(nodes.Contains))
                        continue;
                    //Debug.WriteLine("Combination: {0}", string.Join(" ", nodes));
                    //for (int i = 1; i <= nodes.Count; i++)
                    {
                        var edges = nodes//.Take(i)
                                         .SelectMany(graph.GetEdgesForVertex)
                                         .Distinct()
                                         .Where(x => x.WhereOne(y => !nodes.Contains(y)));
                        GRBLinExpr expression = 0;
                        foreach (var edge in edges)
                            expression.AddTerm(1, edgeVars[edge]);
                        model.AddConstr(expression >= 1.0, "subset_" + conNr);
                        conNr++;

                        if (conNr % 100000 == 0)
                        {
                            //model = model.Presolve(); //Pre-solve the model every 1000 constraints.
                            int constrBefore = model.GetConstrs().Length, varsBefore = model.GetVars().Length;
                            Debug.WriteLine("Presolve called.");
                            var presolved = model.Presolve();
                            Debug.WriteLine("Model has {0} constraints, {1} variables. Presolve has {2} constraints, {3} variables",
                                constrBefore, varsBefore, presolved.GetConstrs().Length, presolved.GetVars().Length);
                        }
                    }
                }

                //Debug.WriteLine("   ");
                //Debug.WriteLine("   ");
                rootNr++;
            }

            //terminalCombinations.Add(new List<Vertex>(new[] { graph.Terminals[0] }));
            //for (int j = 1; j < graph.Terminals.Count - 1; j++)
            //    terminalCombinations.AddRange(new Combinations<Vertex>(graph.Terminals.Skip(1), j).Select(combination => combination.Union(new[] { graph.Terminals[0] }).ToList()));

            //long nonTerminalSetsDone = 0;
            //long nonTerminalSets = 0;
            //for (int i = 0; i <= nonTerminals.Count; i++)
            //    nonTerminalSets += Combinations<Vertex>.NumberOfCombinations(nonTerminals.Count, i);

            //for (int i = 0; i <= nonTerminals.Count; i++)
            //{
            //    foreach (var nonTerminalSet in new Combinations<Vertex>(nonTerminals, i))
            //    {
            //        foreach (var nodes in (from a in terminalCombinations
            //                               select new HashSet<Vertex>(a.Union(nonTerminalSet))))
            //        {
            //            var edges = nodes.SelectMany(graph.GetEdgesForVertex)
            //                             .Distinct()
            //                             .Where(x => x.WhereOne(y => !nodes.Contains(y)));
            //            GRBLinExpr expression = 0;
            //            foreach (var edge in edges)
            //                expression.AddTerm(1, edgeVars[edge]);
            //            model.AddConstr(expression >= 1.0, "subset_" + conNr);
            //            conNr++;
            //        }
            //        nonTerminalSetsDone++;
            //        if (nonTerminalSetsDone % 100 == 0)
            //            Console.Write("\rRunning LP. Creating constraints... {0}/{1} ({2:0.000}%)\r", nonTerminalSetsDone, nonTerminalSets, nonTerminalSetsDone * 100.0 / nonTerminalSets);
            //    }
            //}

            // Solve the LP model
            Console.Write("\rRunning LP. Creating objective & updating...                                   \r");
            GRBLinExpr objective = new GRBLinExpr();
            for (int i = 0; i < graph.NumberOfEdges; i++)
                objective.AddTerm(graph.Edges[i].Cost, variables[i]);
            model.SetObjective(objective, GRB.MINIMIZE);
            Console.Write("\rRunning LP. Tuning...                                   \r");
            model.Tune();
            Debug.WriteLine("Presolve called.");
            model.Presolve();
            Console.Write("\rRunning LP. Solving...                               \r");
            Debug.WriteLine("Optimize called.");
            model.Optimize();

            Graph solution = graph.Clone();
            HashSet<Edge> includedEdges = new HashSet<Edge>();
            for (int i = 0; i < solution.NumberOfEdges; i++)
            {
                var value = variables[i].Get(GRB.DoubleAttr.X);
                if (value == 1)
                    includedEdges.Add(solution.Edges[i]);
            }

            foreach (var edge in solution.Edges.ToList())
                if (!includedEdges.Contains(edge))
                    solution.RemoveEdge(edge);

            Console.Write("\r                                                  \r");

            return solution;
        }