public void Optimize()
        {
            Data = new DataStructure();
            Data.LoadData();

            //生成乘子
            foreach (Node n in Data.NodeSet)
            {
                multiplier_p.Add(n, 0);
            }

            for (int i = 1; i <= IterationTimes; i++)
            {
                double LB = 0;
                BuildModel_SubProblem1();
                if (Solve())
                {
                    ParseSolution_SubProblem1();
                    LB += _grbModel.Get(GRB.DoubleAttr.ObjVal);
                }
                _grbModel.Dispose();
                _env.Dispose();


                BuildModel_SubProblem2();
                if (Solve())
                {
                    ParseSolution_SubProblem2();
                    LB += _grbModel.Get(GRB.DoubleAttr.ObjVal);
                }

                _grbModel.Dispose();
                _env.Dispose();
                UpdateMultiplier(i);


                BuildFeasibleSolutionModel();
                if (Solve())
                {
                    ParseSolution_SubProblem2();
                    StreamWriter sw = File.AppendText("solution.csv");
                    sw.Write("{0},{1},{2}", i, _grbModel.Get(GRB.DoubleAttr.ObjVal), LB);
                    sw.WriteLine();
                    sw.Close();
                }
                else
                {
                    StreamWriter sw = File.AppendText("solution.csv");
                    sw.Write("{0},{1},{2}", i, "infeasible", LB);
                    sw.WriteLine();
                    sw.Close();
                }
                _grbModel.Dispose();
                _env.Dispose();
            }


            ParseSolution();
        }
Ejemplo n.º 2
0
    static void Main()
    {
        try {
            GRBEnv   env   = new GRBEnv("qp.log");
            GRBModel model = new GRBModel(env);

            // Create variables

            GRBVar x = model.AddVar(0.0, 1.0, 0.0, GRB.CONTINUOUS, "x");
            GRBVar y = model.AddVar(0.0, 1.0, 0.0, GRB.CONTINUOUS, "y");
            GRBVar z = model.AddVar(0.0, 1.0, 0.0, GRB.CONTINUOUS, "z");

            // Set objective

            GRBQuadExpr obj = x * x + x * y + y * y + y * z + z * z + 2 * x;
            model.SetObjective(obj);

            // Add constraint: x + 2 y + 3 z >= 4

            model.AddConstr(x + 2 * y + 3 * z >= 4.0, "c0");

            // Add constraint: x + y >= 1

            model.AddConstr(x + y >= 1.0, "c1");

            // Optimize model

            model.Optimize();

            Console.WriteLine(x.VarName + " " + x.X);
            Console.WriteLine(y.VarName + " " + y.X);
            Console.WriteLine(z.VarName + " " + z.X);

            Console.WriteLine("Obj: " + model.ObjVal + " " + obj.Value);


            // Change variable types to integer

            x.VType = GRB.INTEGER;
            y.VType = GRB.INTEGER;
            z.VType = GRB.INTEGER;

            // Optimize model

            model.Optimize();

            Console.WriteLine(x.VarName + " " + x.X);
            Console.WriteLine(y.VarName + " " + y.X);
            Console.WriteLine(z.VarName + " " + z.X);

            Console.WriteLine("Obj: " + model.ObjVal + " " + obj.Value);

            // Dispose of model and env

            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 3
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();
        }
Ejemplo n.º 4
0
        static void SolveDual3(GRBEnv env, HashSet <string> nodes_set, List <Arc> arcs)
        {
            GRBModel dual = new GRBModel(env);
            Dictionary <string, GRBConstr> flow_balance  = new Dictionary <string, GRBConstr>();
            Dictionary <Arc, GRBVar>       arc_traversed = new Dictionary <Arc, GRBVar>();

            GRBConstr[] constrs = dual.AddConstrs(nodes_set.Count);
            dual.Update();

            int i = 0;

            foreach (string s in nodes_set)
            {
                GRBConstr con = constrs[i];
                con.Set(GRB.StringAttr.ConstrName, "flow_balance." + s);
                con.Set(GRB.CharAttr.Sense, GRB.EQUAL);
                flow_balance[s] = con;
                ++i;
            }
            flow_balance[ORIGIN].Set(GRB.DoubleAttr.RHS, -1);
            flow_balance[DESTINATION].Set(GRB.DoubleAttr.RHS, 1);

            foreach (Arc a in arcs)
            {
                GRBColumn col = new GRBColumn();
                col.AddTerm(1, flow_balance[a.dest]);
                col.AddTerm(-1, flow_balance[a.source]);
                arc_traversed[a] = dual.AddVar(0, 1, a.length, GRB.CONTINUOUS, col, "arc_traversed." + a.source + "." + a.dest);
            }
            dual.Optimize();
            dual.Write("dual3.lp");
            dual.Write("dual3.sol");
            dual.Dispose();
        }
Ejemplo n.º 5
0
        public WordsSolver2(Crossword cwd)
        {
            var wordsArray = File.ReadLines(@"C:\Users\Roman Bolzern\Documents\GitHub\Crossword\docs\useful\wordlist.txt").ToArray();
            var wordsList  = wordsArray.GroupBy(f => f.Length).ToDictionary(f => f.Key, f => f.ToList());

            int sizeY = cwd.Grid.GetLength(0);
            int sizeX = cwd.Grid.GetLength(1);

            GRBEnv   env = new GRBEnv();
            GRBModel m   = new GRBModel(env);

            // letters - (0), A-Z (1-27)


            for (int y = 0; y < cwd.Grid.GetLength(0); y++)
            {
                for (int x = 0; x < cwd.Grid.GetLength(1); x++)
                {
                    if (cwd.Grid[y, x] is Question)
                    {
                    }
                }
            }

            //m.SetObjective(deadFieldPenalty + clusterPenalty, GRB.MINIMIZE);

            m.Optimize();
            //m.ComputeIIS();
            //m.Write("model.ilp");

            m.Dispose();
            env.Dispose();
        }
Ejemplo n.º 6
0
        static void SolveDual2(GRBEnv env, HashSet <string> nodes_set, List <Arc> arcs)
        {
            GRBModel dual = new GRBModel(env);
            Dictionary <string, GRBLinExpr> lhs           = new Dictionary <string, GRBLinExpr>();
            Dictionary <string, GRBConstr>  flow_balance  = new Dictionary <string, GRBConstr>();
            Dictionary <Arc, GRBVar>        arc_traversed = new Dictionary <Arc, GRBVar>();

            foreach (string node in nodes_set)
            {
                lhs[node] = new GRBLinExpr();
            }

            foreach (Arc a in arcs)
            {
                GRBVar var = dual.AddVar(0, 1, a.length, GRB.CONTINUOUS, "arc_traversed." + a.source + "_" + a.dest);
                lhs[a.source].AddTerm(-1, var);
                lhs[a.dest].AddTerm(1, var);
            }
            dual.Update();
            foreach (string node in nodes_set)
            {
                flow_balance[node] = dual.AddConstr(lhs[node], 'E', 0, "flow_balance." + node);
            }
            dual.Update();
            flow_balance[ORIGIN].Set(GRB.DoubleAttr.RHS, -1);
            flow_balance[DESTINATION].Set(GRB.DoubleAttr.RHS, 1);
            dual.Optimize();
            dual.Dispose();
        }
Ejemplo n.º 7
0
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: feasopt_cs filename");
            return;
        }

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

            // Create a copy to use FeasRelax feature later */
            GRBModel feasmodel1 = new GRBModel(feasmodel);

            // Clear objective
            feasmodel.SetObjective(new GRBLinExpr());

            // Add slack variables
            GRBConstr[] c = feasmodel.GetConstrs();
            for (int i = 0; i < c.Length; ++i)
            {
                char sense = c[i].Get(GRB.CharAttr.Sense);
                if (sense != '>')
                {
                    GRBConstr[] constrs = new GRBConstr[] { c[i] };
                    double[]    coeffs  = new double[] { -1 };
                    feasmodel.AddVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, constrs,
                                     coeffs, "ArtN_" + c[i].Get(GRB.StringAttr.ConstrName));
                }
                if (sense != '<')
                {
                    GRBConstr[] constrs = new GRBConstr[] { c[i] };
                    double[]    coeffs  = new double[] { 1 };
                    feasmodel.AddVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, constrs,
                                     coeffs, "ArtP_" +
                                     c[i].Get(GRB.StringAttr.ConstrName));
                }
            }
            feasmodel.Update();

            // Optimize modified model
            feasmodel.Write("feasopt.lp");
            feasmodel.Optimize();

            // Use FeasRelax feature */
            feasmodel1.FeasRelax(GRB.FEASRELAX_LINEAR, true, false, true);
            feasmodel1.Write("feasopt1.lp");
            feasmodel1.Optimize();

            // Dispose of model and env
            feasmodel1.Dispose();
            feasmodel.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
        /// <summary>
        ///     Creates a cancellable task that runs Gurobi on the given instance.
        /// </summary>
        /// <param name="instance">Instance to run on.</param>
        /// <param name="cancellationToken">
        ///     Token that is regurlarly checked for cancellation.
        ///     If cancellation is detected, the task will be stopped.
        /// </param>
        /// <returns>
        ///     A task that returns the run's runtime, gap, feasibility and completion status onto return.
        /// </returns>
        public Task <GurobiResult> Run(InstanceSeedFile instance, CancellationToken cancellationToken)
        {
            // Check if the runner has already been disposed.
            if (this._hasAlreadyBeenDisposed)
            {
                throw new ObjectDisposedException("GurobiRunner", "Called Run on a disposed GurobiRunner.");
            }

            // Continue if it hasn't.
            var solveTask = Task.Run(
                () =>
            {
                // Prepare Gurobi model: Use configured _environment and the given instance,
                // then add a callback for cancellation.
                var instanceFile = new FileInfo(instance.Path);
                if (!File.Exists(instanceFile.FullName))
                {
                    throw new Exception(string.Format("Instance {0} not found!", instance.Path));
                }

                LoggingHelper.WriteLine(VerbosityLevel.Debug, $"Setting MIPGap to {this._runnerConfiguration.TerminationMipGap}");
                this._environment.MIPGap = this._runnerConfiguration.TerminationMipGap;
                LoggingHelper.WriteLine(VerbosityLevel.Debug, $"Current Seed: {instance.Seed}");
                this._environment.Seed      = instance.Seed;
                this._environment.TimeLimit = this._runnerConfiguration.CpuTimeout.TotalSeconds;

                var fileName = Path.GetFileNameWithoutExtension(instance.Path);
                if (!Directory.Exists("GurobiLog"))
                {
                    Directory.CreateDirectory("GurobiLog");
                }

                this._environment.LogFile = $"GurobiLog/GurobiRunner_{DateTime.Now:yy-MM-dd_HH-mm-ss-ffff}_" + fileName + ".log";

                var model = new GRBModel(this._environment, instance.Path)
                {
                    ModelName = instanceFile.Name
                };
                var mstfileName = instance.Path.Substring(0, instance.Path.Length - instanceFile.Extension.Length) + ".mst";
                if (File.Exists(mstfileName))
                {
                    model.Read(mstfileName);
                }

                model.SetCallback(new GurobiCallback(cancellationToken));

                // Optimize. This step may be aborted in the callback.
                model.Optimize();
                var result = this.CreateGurobiResult(model);
                // Before returning, dispose of Gurobi model.
                model.Dispose();
                return(result);
            },
                cancellationToken);

            return(solveTask);
        }
Ejemplo n.º 9
0
 public void DisposeModels()
 {
     _grbModelMaster.Dispose();
     _envMaster.Dispose();
     _grbModel_SchemeGenerateSub.Dispose();
     _env_SchemeGenerateSub.Dispose();
     _grbModel_FlowAssignmentSub.Dispose();
     _env_FlowAssignmentSub.Dispose();
     DualSolution.Clear();
 }
Ejemplo n.º 10
0
    static void Main(string[] args)
    {
        if (args.Length < 1) {
          Console.Out.WriteLine("Usage: feasopt_cs filename");
          return;
        }

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

          // Create a copy to use FeasRelax feature later */
          GRBModel feasmodel1 = new GRBModel(feasmodel);

          // Clear objective
          feasmodel.SetObjective(new GRBLinExpr());

          // Add slack variables
          GRBConstr[] c = feasmodel.GetConstrs();
          for (int i = 0; i < c.Length; ++i) {
        char sense = c[i].Get(GRB.CharAttr.Sense);
        if (sense != '>') {
          GRBConstr[] constrs = new GRBConstr[] { c[i] };
          double[] coeffs = new double[] { -1 };
          feasmodel.AddVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, constrs,
                           coeffs, "ArtN_" + c[i].Get(GRB.StringAttr.ConstrName));
        }
        if (sense != '<') {
          GRBConstr[] constrs = new GRBConstr[] { c[i] };
          double[] coeffs = new double[] { 1 };
          feasmodel.AddVar(0.0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, constrs,
                           coeffs, "ArtP_" +
                               c[i].Get(GRB.StringAttr.ConstrName));
        }
          }
          feasmodel.Update();

          // Optimize modified model
          feasmodel.Write("feasopt.lp");
          feasmodel.Optimize();

          // Use FeasRelax feature */
          feasmodel1.FeasRelax(GRB.FEASRELAX_LINEAR, true, false, true);
          feasmodel1.Write("feasopt1.lp");
          feasmodel1.Optimize();

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

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 11
0
    static void Main()
    {
        try {
            GRBEnv   env   = new GRBEnv("qcp.log");
            GRBModel model = new GRBModel(env);

            // Create variables

            GRBVar x = model.AddVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "x");
            GRBVar y = model.AddVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "y");
            GRBVar z = model.AddVar(0.0, GRB.INFINITY, 0.0, GRB.CONTINUOUS, "z");

            // Integrate new variables

            model.Update();

            // Set objective

            GRBLinExpr obj = x;
            model.SetObjective(obj, GRB.MAXIMIZE);

            // Add linear constraint: x + y + z = 1

            model.AddConstr(x + y + z == 1.0, "c0");

            // Add second-order cone: x^2 + y^2 <= z^2

            model.AddQConstr(x * x + y * y <= z * z, "qc0");

            // Add rotated cone: x^2 <= yz

            model.AddQConstr(x * x <= y * z, "qc1");

            // Optimize model

            model.Optimize();

            Console.WriteLine(x.Get(GRB.StringAttr.VarName)
                              + " " + x.Get(GRB.DoubleAttr.X));
            Console.WriteLine(y.Get(GRB.StringAttr.VarName)
                              + " " + y.Get(GRB.DoubleAttr.X));
            Console.WriteLine(z.Get(GRB.StringAttr.VarName)
                              + " " + z.Get(GRB.DoubleAttr.X));

            Console.WriteLine("Obj: " + model.Get(GRB.DoubleAttr.ObjVal) + " " +
                              obj.Value);

            // Dispose of model and env

            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 12
0
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: lp_cs filename");
            return;
        }

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

            model.Optimize();

            int optimstatus = model.Status;

            if (optimstatus == GRB.Status.INF_OR_UNBD)
            {
                model.Parameters.Presolve = 0;
                model.Optimize();
                optimstatus = model.Status;
            }

            if (optimstatus == GRB.Status.OPTIMAL)
            {
                double objval = model.ObjVal;
                Console.WriteLine("Optimal objective: " + objval);
            }
            else if (optimstatus == GRB.Status.INFEASIBLE)
            {
                Console.WriteLine("Model is infeasible");

                // compute and write out IIS

                model.ComputeIIS();
                model.Write("model.ilp");
            }
            else if (optimstatus == GRB.Status.UNBOUNDED)
            {
                Console.WriteLine("Model is unbounded");
            }
            else
            {
                Console.WriteLine("Optimization was stopped with status = "
                                  + optimstatus);
            }

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

        try {
            // Read model and verify that it is a MIP
            GRBEnv   env = new GRBEnv();
            GRBModel m   = new GRBModel(env, args[0]);
            if (m.IsMIP == 0)
            {
                Console.WriteLine("The model is not an integer program");
                Environment.Exit(1);
            }

            // Set a 2 second time limit
            m.Parameters.TimeLimit = 2.0;

            // Now solve the model with different values of MIPFocus
            GRBModel bestModel = new GRBModel(m);
            bestModel.Optimize();
            for (int i = 1; i <= 3; ++i)
            {
                m.Reset();
                m.Parameters.MIPFocus = i;
                m.Optimize();
                if (bestModel.MIPGap > m.MIPGap)
                {
                    GRBModel swap = bestModel;
                    bestModel = m;
                    m         = swap;
                }
            }

            // Finally, delete the extra model, reset the time limit and
            // continue to solve the best model to optimality
            m.Dispose();
            bestModel.Parameters.TimeLimit = GRB.INFINITY;
            bestModel.Optimize();
            Console.WriteLine("Solved with MIPFocus: " +
                              bestModel.Parameters.MIPFocus);

            // Clean up bestModel and environment
            bestModel.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " +
                              e.Message);
        }
    }
Ejemplo n.º 14
0
 public void Optimize()
 {
     Data = new DataStructure();
     Data.LoadData();
     BuildGRBModel();
     if (Solve())
     {
         ParseSolution();
     }
     _grbModel.Dispose();
     _env.Dispose();
 }
Ejemplo n.º 15
0
    static void Main()
    {
        try {
            GRBEnv env = new GRBEnv();

            GRBModel model = new GRBModel(env);

            // Create variables

            double[] ub    = { 1, 1, 2 };
            double[] obj   = { -2, -1, -1 };
            string[] names = { "x0", "x1", "x2" };

            GRBVar[] x = model.AddVars(null, ub, obj, null, names);

            // Integrate new variables

            model.Update();

            // Add first SOS1: x0=0 or x1=0

            GRBVar[] sosv1  = { x[0], x[1] };
            double[] soswt1 = { 1, 2 };

            model.AddSOS(sosv1, soswt1, GRB.SOS_TYPE1);

            // Add second SOS1: x0=0 or x2=0

            GRBVar[] sosv2  = { x[0], x[2] };
            double[] soswt2 = { 1, 2 };

            model.AddSOS(sosv2, soswt2, GRB.SOS_TYPE1);

            // Optimize model

            model.Optimize();

            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine(x[i].Get(GRB.StringAttr.VarName) + " "
                                  + x[i].Get(GRB.DoubleAttr.X));
            }

            // Dispose of model and env
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 16
0
        static void SolveDual(GRBEnv env, HashSet <string> nodes_set, List <Arc> arcs)
        {
            GRBModel dual          = new GRBModel(env);
            Star     forward_stars = new Star();
            Star     reverse_stars = new Star();

            GetStars(nodes_set, arcs, forward_stars, reverse_stars);
            Dictionary <Arc, GRBVar> arc_traversed = new Dictionary <Arc, GRBVar>();

            foreach (Arc a in arcs)
            {
                arc_traversed[a] = dual.AddVar(0, 1, a.length, GRB.CONTINUOUS, "arc_traversed." + a.source + "." + a.dest);
            }
            dual.Update();

            Dictionary <string, GRBConstr> flow_balance = new Dictionary <string, GRBConstr>();

            foreach (string node in nodes_set)
            {
                GRBLinExpr lhs          = new GRBLinExpr();
                List <Arc> forward_star = forward_stars[node];
                List <Arc> reverse_star = reverse_stars[node];
                Console.WriteLine("node " + node);
                Console.Write("Forward star: ");
                foreach (Arc a in forward_star)
                {
                    Console.Write(a.dest + ' ');
                    //                    lhs -= arc_traversed[a];
                    lhs.AddTerm(-1, arc_traversed[a]);
                }
                Console.Write("\nReverse star: ");
                foreach (Arc a in reverse_star)
                {
                    Console.Write(a.source + ' ');
                    lhs.AddTerm(1, arc_traversed[a]);
                }
                Console.WriteLine("");
                flow_balance[node] = dual.AddConstr(lhs, 'E', 0, "flow_balance." + node);
            }
            dual.Update();
            flow_balance[ORIGIN].Set(GRB.DoubleAttr.RHS, -1);
            flow_balance[DESTINATION].Set(GRB.DoubleAttr.RHS, 1);
            dual.Optimize();
            foreach (var pair in arc_traversed)
            {
                Console.WriteLine("Arc {0}:{1} traversed = {2}", pair.Key.source, pair.Key.dest, pair.Value.Get(GRB.DoubleAttr.X));
            }
            Console.WriteLine("length of shortest path = " + dual.Get(GRB.DoubleAttr.ObjVal));
            dual.Dispose();
        }
Ejemplo n.º 17
0
    static void Main()
    {
        try {
          GRBEnv    env   = new GRBEnv("mip1.log");
          GRBModel  model = new GRBModel(env);

          // Create variables

          GRBVar x = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "x");
          GRBVar y = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "y");
          GRBVar z = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "z");

          // Integrate new variables

          model.Update();

          // Set objective: maximize x + y + 2 z

          model.SetObjective(x + y + 2 * z, GRB.MAXIMIZE);

          // Add constraint: x + 2 y + 3 z <= 4

          model.AddConstr(x + 2 * y + 3 * z <= 4.0, "c0");

          // Add constraint: x + y >= 1

          model.AddConstr(x + y >= 1.0, "c1");

          // Optimize model

          model.Optimize();

          Console.WriteLine(x.Get(GRB.StringAttr.VarName)
                         + " " + x.Get(GRB.DoubleAttr.X));
          Console.WriteLine(y.Get(GRB.StringAttr.VarName)
                         + " " + y.Get(GRB.DoubleAttr.X));
          Console.WriteLine(z.Get(GRB.StringAttr.VarName)
                         + " " + z.Get(GRB.DoubleAttr.X));

          Console.WriteLine("Obj: " + model.Get(GRB.DoubleAttr.ObjVal));

          // Dispose of model and env

          model.Dispose();
          env.Dispose();

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 18
0
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: lpmethod_cs filename");
            return;
        }

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

            // Solve the model with different values of Method
            int    bestMethod = -1;
            double bestTime   = menv.Get(GRB.DoubleParam.TimeLimit);
            for (int i = 0; i <= 2; ++i)
            {
                model.Reset();
                menv.Set(GRB.IntParam.Method, i);
                model.Optimize();
                if (model.Get(GRB.IntAttr.Status) == GRB.Status.OPTIMAL)
                {
                    bestTime   = model.Get(GRB.DoubleAttr.Runtime);
                    bestMethod = i;
                    // Reduce the TimeLimit parameter to save time
                    // with other methods
                    menv.Set(GRB.DoubleParam.TimeLimit, bestTime);
                }
            }

            // Report which method was fastest
            if (bestMethod == -1)
            {
                Console.WriteLine("Unable to solve this model");
            }
            else
            {
                Console.WriteLine("Solved in " + bestTime
                                  + " seconds with Method: " + bestMethod);
            }

            // Dispose of model and env
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 19
0
    static void Main()
    {
        try {
          GRBEnv env = new GRBEnv();

          GRBModel model = new GRBModel(env);

          // Create variables

          double[] ub    = {1, 1, 2};
          double[] obj   = {-2, -1, -1};
          string[] names = {"x0", "x1", "x2"};

          GRBVar[] x = model.AddVars(null, ub, obj, null, names);

          // Integrate new variables

          model.Update();

          // Add first SOS1: x0=0 or x1=0

          GRBVar[] sosv1  = {x[0], x[1]};
          double[] soswt1 = {1, 2};

          model.AddSOS(sosv1, soswt1, GRB.SOS_TYPE1);

          // Add second SOS1: x0=0 or x2=0

          GRBVar[] sosv2  = {x[0], x[2]};
          double[] soswt2 = {1, 2};

          model.AddSOS(sosv2, soswt2, GRB.SOS_TYPE1);

          // Optimize model

          model.Optimize();

          for (int i = 0; i < 3; i++)
        Console.WriteLine(x[i].Get(GRB.StringAttr.VarName) + " "
                           + x[i].Get(GRB.DoubleAttr.X));

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

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 20
0
    static void Main()
    {
        try {
            GRBEnv   env   = new GRBEnv("mip1.log");
            GRBModel model = new GRBModel(env);

            // Create variables

            GRBVar x = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "x");
            GRBVar y = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "y");
            GRBVar z = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "z");

            // Integrate new variables

            model.Update();

            // Set objective: maximize x + y + 2 z

            model.SetObjective(x + y + 2 * z, GRB.MAXIMIZE);

            // Add constraint: x + 2 y + 3 z <= 4

            model.AddConstr(x + 2 * y + 3 * z <= 4.0, "c0");

            // Add constraint: x + y >= 1

            model.AddConstr(x + y >= 1.0, "c1");

            // Optimize model

            model.Optimize();

            Console.WriteLine(x.Get(GRB.StringAttr.VarName)
                              + " " + x.Get(GRB.DoubleAttr.X));
            Console.WriteLine(y.Get(GRB.StringAttr.VarName)
                              + " " + y.Get(GRB.DoubleAttr.X));
            Console.WriteLine(z.Get(GRB.StringAttr.VarName)
                              + " " + z.Get(GRB.DoubleAttr.X));

            Console.WriteLine("Obj: " + model.Get(GRB.DoubleAttr.ObjVal));

            // Dispose of model and env

            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 21
0
        public string Example()
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                //GRBEnv env = new GRBEnv("mip1.log");
                GRBEnv   env   = new GRBEnv();
                GRBModel model = new GRBModel(env);

                GRBVar x = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "x");
                GRBVar y = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "y");
                GRBVar z = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "z");

                // Set objective: maximize x + y + 2 z

                model.SetObjective(x + y + 2 * z, GRB.MAXIMIZE);

                // Add constraint: x + 2 y + 3 z <= 4

                model.AddConstr(x + 2 * y + 3 * z <= 4.0, "c0");

                // Add constraint: x + y >= 1

                model.AddConstr(x + y >= 1.0, "c1");

                // Optimize model

                model.Optimize();


                sb.AppendLine(x.VarName + " " + x.X);
                sb.AppendLine(y.VarName + " " + y.X);
                sb.AppendLine(z.VarName + " " + z.X);

                sb.AppendLine("Obj: " + model.ObjVal);

                // Dispose of model and env

                model.Dispose();
                env.Dispose();
            }
            catch (GRBException e)
            {
                //pokemon
            }
            return(sb.ToString());
        }
Ejemplo n.º 22
0
    static void Main(string[] args)
    {
        if (args.Length < 1) {
          Console.Out.WriteLine("Usage: lpmethod_cs filename");
          return;
        }

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

          // Solve the model with different values of Method
          int bestMethod = -1;
          double bestTime = menv.Get(GRB.DoubleParam.TimeLimit);
          for (int i = 0; i <= 2; ++i)
          {
        model.Reset();
        menv.Set(GRB.IntParam.Method, i);
        model.Optimize();
        if (model.Get(GRB.IntAttr.Status) == GRB.Status.OPTIMAL)
        {
          bestTime = model.Get(GRB.DoubleAttr.Runtime);
          bestMethod = i;
          // Reduce the TimeLimit parameter to save time
          // with other methods
          menv.Set(GRB.DoubleParam.TimeLimit, bestTime);
        }
          }

          // Report which method was fastest
          if (bestMethod == -1) {
        Console.WriteLine("Unable to solve this model");
          } else {
        Console.WriteLine("Solved in " + bestTime
          + " seconds with Method: " + bestMethod);
          }

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

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 23
0
        public void mip1_cs()
        {
            try
            {
                // Create an empty environment, set options and start
                GRBEnv env = new GRBEnv(true);
                env.Set("LogFile", "mip1.log");
                env.Start();

                // Create empty model
                GRBModel model = new GRBModel(env);

                // Create variables
                GRBVar x = model.AddVar(0.0, 1.0, 1.0, GRB.BINARY, "x");
                GRBVar y = model.AddVar(0.0, 1.0, 1.0, GRB.BINARY, "y");
                GRBVar z = model.AddVar(0.0, 1.0, 1.0, GRB.BINARY, "z");

                // Set objective: maximize x + y + 2 z
                model.SetObjective(x + y + 2 * z, GRB.MAXIMIZE);

                // Add constraint: x + 2 y + 3 z <= 4
                model.AddConstr(x + 2 * y + 3 * z <= 4.0, "c0");

                // Add constraint: x + y >= 1
                model.AddConstr(x + y >= 1.0, "c1");

                // Optimize model
                model.Optimize();

                Console.WriteLine(x.VarName + " " + x.X);
                Console.WriteLine(y.VarName + " " + y.X);
                Console.WriteLine(z.VarName + " " + z.X);

                Console.WriteLine("Obj: " + model.ObjVal);

                // Dispose of model and env
                model.Dispose();
                env.Dispose();
            }
            catch (GRBException e)
            {
                Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
            }
        }
Ejemplo n.º 24
0
        static void SolvePrimal(GRBEnv env, HashSet <string> nodes_set, List <Arc> arcs)
        {
            GRBModel m = new GRBModel(env);

            Dictionary <string, GRBVar> distances = new Dictionary <string, GRBVar>(); // pi

            foreach (string node in nodes_set)
            {
                distances[node] = m.AddVar(0, GRB.INFINITY, 0, GRB.CONTINUOUS, "distance." + node);
            }
            m.Update();
            distances[ORIGIN].Set(GRB.DoubleAttr.Obj, -1);
            distances[DESTINATION].Set(GRB.DoubleAttr.Obj, 1);
            m.Set(GRB.IntAttr.ModelSense, -1);

            Dictionary <Arc, GRBConstr> constrs = new Dictionary <Arc, GRBConstr>();

            foreach (Arc a in arcs)
            {
                constrs[a] = m.AddConstr(distances[a.dest] <= distances[a.source] + a.length, "distance_con." + a.source + "." + a.dest);
            }

            m.Update();
            m.Write("shortest_path.lp");
            m.Optimize();

            foreach (var pair in distances)
            {
                Console.WriteLine("distance to {0} is {1}", pair.Key, pair.Value.Get(GRB.DoubleAttr.X));
            }

            foreach (var pair in constrs)
            {
                GRBConstr con = pair.Value;
                if (con.Get(GRB.DoubleAttr.Pi) > 0.5)
                {
                    Console.WriteLine("Arc {0}, {1} is in shortest path", pair.Key.source, pair.Key.dest);
                }
            }
            Console.WriteLine("Length of shortest path is {0}", m.Get(GRB.DoubleAttr.ObjVal));
            m.Dispose();
        }
Ejemplo n.º 25
0
    static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.Out.WriteLine("Usage: tune_cs filename");
            return;
        }

        try {
            GRBEnv env = new GRBEnv();

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

            // Set the TuneResults parameter to 1
            model.GetEnv().Set(GRB.IntParam.TuneResults, 1);

            // Tune the model
            model.Tune();

            // Get the number of tuning results
            int resultcount = model.Get(GRB.IntAttr.TuneResultCount);

            if (resultcount > 0)
            {
                // Load the tuned parameters into the model's environment
                model.GetTuneResult(0);

                // Write the tuned parameters to a file
                model.Write("tune.prm");

                // Solve the model using the tuned parameters
                model.Optimize();
            }

            // Dispose of model and environment
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 26
0
        public void Optimize()
        {
            Data.LoadData();

            GenerateInitialFeasibleSolution();

            while (true)
            {
                _envMaster      = new GRBEnv("CG_Model.log");
                _grbModelMaster = new GRBModel(_envMaster);


                BuildVar();
                GenerateConst();

                _grbModelMaster.Write("CG_Model.lp");
                _grbModelMaster.Optimize();

                GetDual();

                OutputSolution();

                OptimizeSchemeSub();
                OptimizeFASub();

                bool IsActive = AddColumn();

                _grbModelMaster.Dispose();
                _envMaster.Dispose();
                _grbModel_SchemeGenerateSub.Dispose();
                _env_SchemeGenerateSub.Dispose();
                _grbModel_FlowAssignmentSub.Dispose();
                _env_FlowAssignmentSub.Dispose();

                if (!IsActive)
                {
                    break;
                }
            }
        }
Ejemplo n.º 27
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);
        }
    }
Ejemplo n.º 28
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);
    }
Ejemplo n.º 29
0
    static void Main(string[] args)
    {
        int n = 9;
        int s = 3;

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

        try {
          GRBEnv env = new GRBEnv();
          GRBModel model = new GRBModel(env);

          // Create 3-D array of model variables

          GRBVar[,,] vars = new GRBVar[n,n,n];

          for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
          for (int v = 0; v < n; v++) {
            string st = "G_" + i.ToString() + "_" + j.ToString()
                             + "_" + v.ToString();
            vars[i,j,v] = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, st);
          }
        }
          }

          // Integrate variables into model

          model.Update();

          // Add constraints

          GRBLinExpr expr;

          // Each cell must take one value

          for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
          expr = 0.0;
          for (int v = 0; v < n; v++)
            expr += vars[i,j,v];
          string st = "V_" + i.ToString() + "_" + j.ToString();
          model.AddConstr(expr == 1.0, st);
        }
          }

          // Each value appears once per row

          for (int i = 0; i < n; i++) {
        for (int v = 0; v < n; v++) {
          expr = 0.0;
          for (int j = 0; j < n; j++)
            expr += vars[i,j,v];
          string st = "R_" + i.ToString() + "_" + v.ToString();
          model.AddConstr(expr == 1.0, st);
        }
          }

          // Each value appears once per column

          for (int j = 0; j < n; j++) {
        for (int v = 0; v < n; v++) {
          expr = 0.0;
          for (int i = 0; i < n; i++)
            expr += vars[i,j,v];
          string st = "C_" + j.ToString() + "_" + v.ToString();
          model.AddConstr(expr == 1.0, st);
        }
          }

          // Each value appears once per sub-grid

          for (int v = 0; v < n; v++) {
        for (int i0 = 0; i0 < s; i0++) {
          for (int j0 = 0; j0 < s; j0++) {
            expr = 0.0;
            for (int i1 = 0; i1 < s; i1++) {
              for (int j1 = 0; j1 < s; j1++) {
                expr += vars[i0*s+i1,j0*s+j1,v];
              }
            }
            string st = "Sub_" + v.ToString() + "_" + i0.ToString()
                               + "_" + j0.ToString();
            model.AddConstr(expr == 1.0, st);
          }
        }
          }

          // Update model

          model.Update();

          // Fix variables associated with pre-specified cells

          StreamReader sr = File.OpenText(args[0]);

          for (int i = 0; i < n; i++) {
        string input = sr.ReadLine();
        for (int j = 0; j < n; j++) {
          int val = (int) input[j] - 48 - 1; // 0-based

          if (val >= 0)
            vars[i,j,val].Set(GRB.DoubleAttr.LB, 1.0);
        }
          }

          // Optimize model

          model.Optimize();

          // Write model to file
          model.Write("sudoku.lp");

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

          Console.WriteLine();
          for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
          for (int v = 0; v < n; v++) {
            if (x[i,j,v] > 0.5) {
              Console.Write(v+1);
            }
          }
        }
        Console.WriteLine();
          }

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

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 30
0
    protected static bool dense_optimize(GRBEnv    env,
                   int       rows,
                   int       cols,
                   double[]  c,      // linear portion of objective function
                   double[,] Q,      // quadratic portion of objective function
                   double[,] A,      // constraint matrix
                   char[]    sense,  // constraint senses
                   double[]  rhs,    // RHS vector
                   double[]  lb,     // variable lower bounds
                   double[]  ub,     // variable upper bounds
                   char[]    vtype,  // variable types (continuous, binary, etc.)
                   double[]  solution)
    {
        bool success = false;

        try {
          GRBModel model = new GRBModel(env);

          // Add variables to the model

          GRBVar[] vars = model.AddVars(lb, ub, null, vtype, null);
          model.Update();

          // Populate A matrix

          for (int i = 0; i < rows; i++) {
        GRBLinExpr expr = new GRBLinExpr();
        for (int j = 0; j < cols; j++)
          if (A[i,j] != 0)
            expr.AddTerm(A[i,j], vars[j]); // Note: '+=' would be much slower
        model.AddConstr(expr, sense[i], rhs[i], "");
          }

          // Populate objective

          GRBQuadExpr obj = new GRBQuadExpr();
          if (Q != null) {
        for (int i = 0; i < cols; i++)
          for (int j = 0; j < cols; j++)
            if (Q[i,j] != 0)
              obj.AddTerm(Q[i,j], vars[i], vars[j]); // Note: '+=' would be much slower
        for (int j = 0; j < cols; j++)
          if (c[j] != 0)
            obj.AddTerm(c[j], vars[j]); // Note: '+=' would be much slower
        model.SetObjective(obj);
          }

          // Solve model

          model.Optimize();

          // Extract solution

          if (model.Get(GRB.IntAttr.Status) == GRB.Status.OPTIMAL) {
        success = true;

        for (int j = 0; j < cols; j++)
          solution[j] = vars[j].Get(GRB.DoubleAttr.X);
          }

          model.Dispose();

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }

        return success;
    }
Ejemplo n.º 31
0
    static void Main()
    {
        try {

          // Warehouse demand in thousands of units
          double[] Demand = new double[] { 15, 18, 14, 20 };

          // Plant capacity in thousands of units
          double[] Capacity = new double[] { 20, 22, 17, 19, 18 };

          // Fixed costs for each plant
          double[] FixedCosts =
          new double[] { 12000, 15000, 17000, 13000, 16000 };

          // Transportation costs per thousand units
          double[,] TransCosts =
          new double[,] { { 4000, 2000, 3000, 2500, 4500 },
              { 2500, 2600, 3400, 3000, 4000 },
              { 1200, 1800, 2600, 4100, 3000 },
              { 2200, 2600, 3100, 3700, 3200 } };

          // Number of plants and warehouses
          int nPlants = Capacity.Length;
          int nWarehouses = Demand.Length;

          // Model
          GRBEnv env = new GRBEnv();
          GRBModel model = new GRBModel(env);
          model.Set(GRB.StringAttr.ModelName, "facility");

          // Plant open decision variables: open[p] == 1 if plant p is open.
          GRBVar[] open = new GRBVar[nPlants];
          for (int p = 0; p < nPlants; ++p) {
        open[p] = model.AddVar(0, 1, FixedCosts[p], GRB.BINARY, "Open" + p);
          }

          // Transportation decision variables: how much to transport from
          // a plant p to a warehouse w
          GRBVar[,] transport = new GRBVar[nWarehouses,nPlants];
          for (int w = 0; w < nWarehouses; ++w) {
        for (int p = 0; p < nPlants; ++p) {
          transport[w,p] =
              model.AddVar(0, GRB.INFINITY, TransCosts[w,p], GRB.CONTINUOUS,
                           "Trans" + p + "." + w);
        }
          }

          // The objective is to minimize the total fixed and variable costs
          model.Set(GRB.IntAttr.ModelSense, 1);

          // Update model to integrate new variables
          model.Update();

          // Production constraints
          // Note that the right-hand limit sets the production to zero if
          // the plant is closed
          for (int p = 0; p < nPlants; ++p) {
        GRBLinExpr ptot = 0.0;
        for (int w = 0; w < nWarehouses; ++w)
          ptot += transport[w,p];
        model.AddConstr(ptot <= Capacity[p] * open[p], "Capacity" + p);
          }

          // Demand constraints
          for (int w = 0; w < nWarehouses; ++w) {
        GRBLinExpr dtot = 0.0;
        for (int p = 0; p < nPlants; ++p)
          dtot += transport[w,p];
        model.AddConstr(dtot == Demand[w], "Demand" + w);
          }

          // Guess at the starting point: close the plant with the highest
          // fixed costs; open all others

          // First, open all plants
          for (int p = 0; p < nPlants; ++p) {
        open[p].Set(GRB.DoubleAttr.Start, 1.0);
          }

          // Now close the plant with the highest fixed cost
          Console.WriteLine("Initial guess:");
          double maxFixed = -GRB.INFINITY;
          for (int p = 0; p < nPlants; ++p) {
        if (FixedCosts[p] > maxFixed) {
          maxFixed = FixedCosts[p];
        }
          }
          for (int p = 0; p < nPlants; ++p) {
        if (FixedCosts[p] == maxFixed) {
          open[p].Set(GRB.DoubleAttr.Start, 0.0);
          Console.WriteLine("Closing plant " + p + "\n");
          break;
        }
          }

          // Use barrier to solve root relaxation
          model.GetEnv().Set(GRB.IntParam.Method, GRB.METHOD_BARRIER);

          // Solve
          model.Optimize();

          // Print solution
          Console.WriteLine("\nTOTAL COSTS: " + model.Get(GRB.DoubleAttr.ObjVal));
          Console.WriteLine("SOLUTION:");
          for (int p = 0; p < nPlants; ++p) {
        if (open[p].Get(GRB.DoubleAttr.X) == 1.0) {
          Console.WriteLine("Plant " + p + " open:");
          for (int w = 0; w < nWarehouses; ++w) {
            if (transport[w,p].Get(GRB.DoubleAttr.X) > 0.0001) {
              Console.WriteLine("  Transport " +
                  transport[w,p].Get(GRB.DoubleAttr.X) +
                  " units to warehouse " + w);
            }
          }
        } else {
          Console.WriteLine("Plant " + p + " closed!");
        }
          }

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

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 32
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);
        }
    }
Ejemplo n.º 33
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);
        }
    }
Ejemplo n.º 34
0
    static void Main()
    {
        try {
            // Create environment

            GRBEnv env = new GRBEnv();

            // Create a new m

            GRBModel m = new GRBModel(env);

            double lb = 0.0, ub = GRB.INFINITY;

            GRBVar x = m.AddVar(lb, ub, 0.0, GRB.CONTINUOUS, "x");
            GRBVar y = m.AddVar(lb, ub, 0.0, GRB.CONTINUOUS, "y");
            GRBVar u = m.AddVar(lb, ub, 0.0, GRB.CONTINUOUS, "u");
            GRBVar v = m.AddVar(lb, ub, 0.0, GRB.CONTINUOUS, "v");

            // Set objective

            m.SetObjective(2 * x + y, GRB.MAXIMIZE);

            // Add linear constraint

            m.AddConstr(u + 4 * v <= 9, "l1");

            // Approach 1) PWL constraint approach

            double   intv = 1e-3;
            double   xmax = Math.Log(9.0);
            int      len  = (int)Math.Ceiling(xmax / intv) + 1;
            double[] xpts = new double[len];
            double[] upts = new double[len];
            for (int i = 0; i < len; i++)
            {
                xpts[i] = i * intv;
                upts[i] = f(i * intv);
            }
            GRBGenConstr gc1 = m.AddGenConstrPWL(x, u, xpts, upts, "gc1");

            double ymax = (9.0 / 4.0) * (9.0 / 4.0);
            len = (int)Math.Ceiling(ymax / intv) + 1;
            double[] ypts = new double[len];
            double[] vpts = new double[len];
            for (int i = 0; i < len; i++)
            {
                ypts[i] = i * intv;
                vpts[i] = g(i * intv);
            }
            GRBGenConstr gc2 = m.AddGenConstrPWL(y, v, ypts, vpts, "gc2");

            // Optimize the model and print solution

            m.Optimize();
            printsol(m, x, y, u, v);

            // Approach 2) General function constraint approach with auto PWL
            //             translation by Gurobi

            // restore unsolved state and get rid of PWL constraints
            m.Reset();
            m.Remove(gc1);
            m.Remove(gc2);
            m.Update();

            GRBGenConstr gcf1 = m.AddGenConstrExp(x, u, "gcf1", "");
            GRBGenConstr gcf2 = m.AddGenConstrPow(y, v, 0.5, "gcf2", "");

            m.Parameters.FuncPieceLength = 1e-3;

            // Optimize the model and print solution

            m.Optimize();
            printsol(m, x, y, u, v);

            // Zoom in, use optimal solution to reduce the ranges and use a smaller
            // pclen=1e-5 to solve it

            x.LB = Math.Max(x.LB, x.X - 0.01);
            x.UB = Math.Min(x.UB, x.X + 0.01);
            y.LB = Math.Max(y.LB, y.X - 0.01);
            y.UB = Math.Min(y.UB, y.X + 0.01);
            m.Update();
            m.Reset();

            m.Parameters.FuncPieceLength = 1e-5;

            // Optimize the model and print solution

            m.Optimize();
            printsol(m, x, y, u, v);

            // Dispose of model and environment

            m.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 35
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);
        }
    }
Ejemplo n.º 36
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.Set(GRB.StringAttr.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.Set(GRB.IntAttr.ModelSense, 1);

          // Update model to integrate new variables
          model.Update();

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

          // Optimize
          model.Optimize();
          int status = model.Get(GRB.IntAttr.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.Get(GRB.DoubleAttr.ObjVal));
        return;
          }
          if ((status != GRB.Status.INF_OR_UNBD) &&
          (status != GRB.Status.INFEASIBLE)) {
        Console.WriteLine("Optimization was stopped with status " + status);
        return;
          }

          // Add slack variables to make the model feasible
          Console.WriteLine("The model is infeasible; adding slack variables");

          // Set original objective coefficients to zero
          model.SetObjective(new GRBLinExpr());

          // Add a new slack variable to each shift constraint so that the shifts
          // can be satisfied
          LinkedList<GRBVar> slacks = new LinkedList<GRBVar>();
          foreach (GRBConstr c in reqCts) {
        GRBColumn col = new GRBColumn();
        col.AddTerm(1.0, c);
        GRBVar newvar =
            model.AddVar(0, GRB.INFINITY, 1.0, GRB.CONTINUOUS, col,
                         c.Get(GRB.StringAttr.ConstrName) + "Slack");
        slacks.AddFirst(newvar);
          }

          // Solve the model with slacks
          model.Optimize();
          status = model.Get(GRB.IntAttr.Status);
          if ((status == GRB.Status.INF_OR_UNBD) ||
          (status == GRB.Status.INFEASIBLE) ||
          (status == GRB.Status.UNBOUNDED)) {
        Console.WriteLine("The model with slacks 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:");
          foreach (GRBVar sv in slacks) {
        if (sv.Get(GRB.DoubleAttr.X) > 1e-6) {
          Console.WriteLine(sv.Get(GRB.StringAttr.VarName) + " = " +
              sv.Get(GRB.DoubleAttr.X));
        }
          }

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

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " +
          e.Message);
        }
    }
    static void Main(string[] args)
    {
        int n = 9;
        int s = 3;

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

        try {
            GRBEnv   env   = new GRBEnv();
            GRBModel model = new GRBModel(env);

            // Create 3-D array of model variables

            GRBVar[,,] vars = new GRBVar[n, n, n];

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    for (int v = 0; v < n; v++)
                    {
                        string st = "G_" + i.ToString() + "_" + j.ToString()
                                    + "_" + v.ToString();
                        vars[i, j, v] = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, st);
                    }
                }
            }

            // Add constraints

            GRBLinExpr expr;

            // Each cell must take one value

            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    expr = 0.0;
                    for (int v = 0; v < n; v++)
                    {
                        expr.AddTerm(1.0, vars[i, j, v]);
                    }
                    string st = "V_" + i.ToString() + "_" + j.ToString();
                    model.AddConstr(expr == 1.0, st);
                }
            }

            // Each value appears once per row

            for (int i = 0; i < n; i++)
            {
                for (int v = 0; v < n; v++)
                {
                    expr = 0.0;
                    for (int j = 0; j < n; j++)
                    {
                        expr.AddTerm(1.0, vars[i, j, v]);
                    }
                    string st = "R_" + i.ToString() + "_" + v.ToString();
                    model.AddConstr(expr == 1.0, st);
                }
            }

            // Each value appears once per column

            for (int j = 0; j < n; j++)
            {
                for (int v = 0; v < n; v++)
                {
                    expr = 0.0;
                    for (int i = 0; i < n; i++)
                    {
                        expr.AddTerm(1.0, vars[i, j, v]);
                    }
                    string st = "C_" + j.ToString() + "_" + v.ToString();
                    model.AddConstr(expr == 1.0, st);
                }
            }

            // Each value appears once per sub-grid

            for (int v = 0; v < n; v++)
            {
                for (int i0 = 0; i0 < s; i0++)
                {
                    for (int j0 = 0; j0 < s; j0++)
                    {
                        expr = 0.0;
                        for (int i1 = 0; i1 < s; i1++)
                        {
                            for (int j1 = 0; j1 < s; j1++)
                            {
                                expr.AddTerm(1.0, vars[i0 * s + i1, j0 * s + j1, v]);
                            }
                        }
                        string st = "Sub_" + v.ToString() + "_" + i0.ToString()
                                    + "_" + j0.ToString();
                        model.AddConstr(expr == 1.0, st);
                    }
                }
            }

            // Fix variables associated with pre-specified cells

            StreamReader sr = File.OpenText(args[0]);

            for (int i = 0; i < n; i++)
            {
                string input = sr.ReadLine();
                for (int j = 0; j < n; j++)
                {
                    int val = (int)input[j] - 48 - 1; // 0-based

                    if (val >= 0)
                    {
                        vars[i, j, val].LB = 1.0;
                    }
                }
            }

            // Optimize model

            model.Optimize();

            // Write model to file
            model.Write("sudoku.lp");

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

            Console.WriteLine();
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    for (int v = 0; v < n; v++)
                    {
                        if (x[i, j, v] > 0.5)
                        {
                            Console.Write(v + 1);
                        }
                    }
                }
                Console.WriteLine();
            }

            // Dispose of model and env
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 38
0
    static void Main()
    {
        try {
          GRBEnv    env   = new GRBEnv("qp.log");
          GRBModel  model = new GRBModel(env);

          // Create variables

          GRBVar x = model.AddVar(0.0, 1.0, 0.0, GRB.CONTINUOUS, "x");
          GRBVar y = model.AddVar(0.0, 1.0, 0.0, GRB.CONTINUOUS, "y");
          GRBVar z = model.AddVar(0.0, 1.0, 0.0, GRB.CONTINUOUS, "z");

          // Integrate new variables

          model.Update();

          // Set objective

          GRBQuadExpr obj = x*x + x*y + y*y + y*z + z*z;
          model.SetObjective(obj);

          // Add constraint: x + 2 y + 3 z >= 4

          model.AddConstr(x + 2 * y + 3 * z >= 4.0, "c0");

          // Add constraint: x + y >= 1

          model.AddConstr(x + y >= 1.0, "c1");

          // Optimize model

          model.Optimize();

          Console.WriteLine(x.Get(GRB.StringAttr.VarName)
                         + " " + x.Get(GRB.DoubleAttr.X));
          Console.WriteLine(y.Get(GRB.StringAttr.VarName)
                         + " " + y.Get(GRB.DoubleAttr.X));
          Console.WriteLine(z.Get(GRB.StringAttr.VarName)
                         + " " + z.Get(GRB.DoubleAttr.X));

          Console.WriteLine("Obj: " + model.Get(GRB.DoubleAttr.ObjVal) + " " +
                        obj.Value);

          // Change variable types to integer

          x.Set(GRB.CharAttr.VType, GRB.INTEGER);
          y.Set(GRB.CharAttr.VType, GRB.INTEGER);
          z.Set(GRB.CharAttr.VType, GRB.INTEGER);

          // Optimize model

          model.Optimize();

          Console.WriteLine(x.Get(GRB.StringAttr.VarName)
                         + " " + x.Get(GRB.DoubleAttr.X));
          Console.WriteLine(y.Get(GRB.StringAttr.VarName)
                         + " " + y.Get(GRB.DoubleAttr.X));
          Console.WriteLine(z.Get(GRB.StringAttr.VarName)
                         + " " + z.Get(GRB.DoubleAttr.X));

          Console.WriteLine("Obj: " + model.Get(GRB.DoubleAttr.ObjVal) + " " +
                        obj.Value);

          // Dispose of model and env

          model.Dispose();
          env.Dispose();

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 39
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.Set(GRB.StringAttr.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.Set(GRB.IntAttr.ModelSense, 1);

          // Update model to integrate new variables
          model.Update();

          // 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 += x[w, s];
        model.AddConstr(lhs == shiftRequirements[s], Shifts[s]);
          }

          // Optimize
          model.Optimize();
          int status = model.Get(GRB.IntAttr.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.Get(GRB.DoubleAttr.ObjVal));
        return;
          }
          if ((status != GRB.Status.INF_OR_UNBD) &&
          (status != GRB.Status.INFEASIBLE)) {
        Console.WriteLine("Optimization was stopped with status " + status);
        return;
          }

          // Do IIS
          Console.WriteLine("The model is infeasible; computing IIS");
          LinkedList<string> removed = new LinkedList<string>();

          // Loop until we reduce to a model that can be solved
          while (true) {
        model.ComputeIIS();
        Console.WriteLine("\nThe following constraint cannot be satisfied:");
        foreach (GRBConstr c in model.GetConstrs()) {
          if (c.Get(GRB.IntAttr.IISConstr) == 1) {
            Console.WriteLine(c.Get(GRB.StringAttr.ConstrName));
            // Remove a single constraint from the model
            removed.AddFirst(c.Get(GRB.StringAttr.ConstrName));
            model.Remove(c);
            break;
          }
        }

        Console.WriteLine();
        model.Optimize();
        status = model.Get(GRB.IntAttr.Status);

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

          Console.WriteLine("\nThe following constraints were removed "
          + "to get a feasible LP:");
          foreach (string s in removed) {
        Console.Write(s + " ");
          }
          Console.WriteLine();

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

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " +
          e.Message);
        }
    }
Ejemplo n.º 40
0
    public static void Main(String[] args)
    {
        if (args.Length < 1) {
          Console.WriteLine("Usage: tsp_cs nnodes");
          return;
        }

        int n = Convert.ToInt32(args[0]);

        try {
          GRBEnv   env   = new GRBEnv();
          GRBModel model = new GRBModel(env);

          // Must disable dual reductions when using lazy constraints

          model.GetEnv().Set(GRB.IntParam.DualReductions, 0);

          double[] x = new double[n];
          double[] y = new double[n];

          Random r = new Random();
          for (int i = 0; i < n; i++) {
        x[i] = r.NextDouble();
        y[i] = r.NextDouble();
          }

          // Create variables

          GRBVar[,] vars = new GRBVar[n, n];

          for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
          vars[i, j] = model.AddVar(0.0, 1.0, distance(x, y, i, j),
                                    GRB.BINARY, "x"+i+"_"+j);

          // Integrate variables

          model.Update();

          // Degree-2 constraints

          for (int i = 0; i < n; i++) {
        GRBLinExpr expr = 0;
        for (int j = 0; j < n; j++)
          expr += vars[i, j];
        model.AddConstr(expr == 2.0, "deg2_"+i);
          }

          // Forbid edge from node back to itself

          for (int i = 0; i < n; i++)
        vars[i, i].Set(GRB.DoubleAttr.UB, 0.0);

          // Symmetric TSP

          for (int i = 0; i < n; i++)
        for (int j = 0; j < i; j++)
          model.AddConstr(vars[i, j]== vars[j, i], "");

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

          if (model.Get(GRB.IntAttr.SolCount) > 0) {
        int[] tour = findsubtour(model.Get(GRB.DoubleAttr.X, vars));

        Console.Write("Tour: ");
        for (int i = 0; i < tour.Length; i++)
          Console.Write(tour[i] + " ");
        Console.WriteLine();
          }

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

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
          Console.WriteLine(e.StackTrace);
        }
    }
    static void Main()
    {
        try {
            // Warehouse demand in thousands of units
            double[] Demand = new double[] { 15, 18, 14, 20 };

            // Plant capacity in thousands of units
            double[] Capacity = new double[] { 20, 22, 17, 19, 18 };

            // Fixed costs for each plant
            double[] FixedCosts =
                new double[] { 12000, 15000, 17000, 13000, 16000 };

            // Transportation costs per thousand units
            double[,] TransCosts =
                new double[, ] {
                { 4000, 2000, 3000, 2500, 4500 },
                { 2500, 2600, 3400, 3000, 4000 },
                { 1200, 1800, 2600, 4100, 3000 },
                { 2200, 2600, 3100, 3700, 3200 }
            };

            // Number of plants and warehouses
            int nPlants     = Capacity.Length;
            int nWarehouses = Demand.Length;

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

            model.ModelName = "facility";

            // Plant open decision variables: open[p] == 1 if plant p is open.
            GRBVar[] open = new GRBVar[nPlants];
            for (int p = 0; p < nPlants; ++p)
            {
                open[p] = model.AddVar(0, 1, FixedCosts[p], GRB.BINARY, "Open" + p);
            }

            // Transportation decision variables: how much to transport from
            // a plant p to a warehouse w
            GRBVar[,] transport = new GRBVar[nWarehouses, nPlants];
            for (int w = 0; w < nWarehouses; ++w)
            {
                for (int p = 0; p < nPlants; ++p)
                {
                    transport[w, p] =
                        model.AddVar(0, GRB.INFINITY, TransCosts[w, p], GRB.CONTINUOUS,
                                     "Trans" + p + "." + w);
                }
            }

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

            // Production constraints
            // Note that the right-hand limit sets the production to zero if
            // the plant is closed
            for (int p = 0; p < nPlants; ++p)
            {
                GRBLinExpr ptot = 0.0;
                for (int w = 0; w < nWarehouses; ++w)
                {
                    ptot.AddTerm(1.0, transport[w, p]);
                }
                model.AddConstr(ptot <= Capacity[p] * open[p], "Capacity" + p);
            }

            // Demand constraints
            for (int w = 0; w < nWarehouses; ++w)
            {
                GRBLinExpr dtot = 0.0;
                for (int p = 0; p < nPlants; ++p)
                {
                    dtot.AddTerm(1.0, transport[w, p]);
                }
                model.AddConstr(dtot == Demand[w], "Demand" + w);
            }

            // Guess at the starting point: close the plant with the highest
            // fixed costs; open all others

            // First, open all plants
            for (int p = 0; p < nPlants; ++p)
            {
                open[p].Start = 1.0;
            }

            // Now close the plant with the highest fixed cost
            Console.WriteLine("Initial guess:");
            double maxFixed = -GRB.INFINITY;
            for (int p = 0; p < nPlants; ++p)
            {
                if (FixedCosts[p] > maxFixed)
                {
                    maxFixed = FixedCosts[p];
                }
            }
            for (int p = 0; p < nPlants; ++p)
            {
                if (FixedCosts[p] == maxFixed)
                {
                    open[p].Start = 0.0;
                    Console.WriteLine("Closing plant " + p + "\n");
                    break;
                }
            }

            // Use barrier to solve root relaxation
            model.Parameters.Method = GRB.METHOD_BARRIER;

            // Solve
            model.Optimize();

            // Print solution
            Console.WriteLine("\nTOTAL COSTS: " + model.ObjVal);
            Console.WriteLine("SOLUTION:");
            for (int p = 0; p < nPlants; ++p)
            {
                if (open[p].X > 0.99)
                {
                    Console.WriteLine("Plant " + p + " open:");
                    for (int w = 0; w < nWarehouses; ++w)
                    {
                        if (transport[w, p].X > 0.0001)
                        {
                            Console.WriteLine("  Transport " +
                                              transport[w, p].X + " units to warehouse " + w);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Plant " + p + " closed!");
                }
            }

            // Dispose of model and env
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
        }
    }
Ejemplo n.º 42
0
    static void Main()
    {
        try {

          // Nutrition guidelines, based on
          // USDA Dietary Guidelines for Americans, 2005
          // http://www.health.gov/DietaryGuidelines/dga2005/
          string[] Categories =
          new string[] { "calories", "protein", "fat", "sodium" };
          int nCategories = Categories.Length;
          double[] minNutrition = new double[] { 1800, 91, 0, 0 };
          double[] maxNutrition = new double[] { 2200, GRB.INFINITY, 65, 1779 };

          // Set of foods
          string[] Foods =
          new string[] { "hamburger", "chicken", "hot dog", "fries",
              "macaroni", "pizza", "salad", "milk", "ice cream" };
          int nFoods = Foods.Length;
          double[] cost =
          new double[] { 2.49, 2.89, 1.50, 1.89, 2.09, 1.99, 2.49, 0.89,
              1.59 };

          // Nutrition values for the foods
          double[,] nutritionValues = new double[,] {
          { 410, 24, 26, 730 },   // hamburger
          { 420, 32, 10, 1190 },  // chicken
          { 560, 20, 32, 1800 },  // hot dog
          { 380, 4, 19, 270 },    // fries
          { 320, 12, 10, 930 },   // macaroni
          { 320, 15, 12, 820 },   // pizza
          { 320, 31, 12, 1230 },  // salad
          { 100, 8, 2.5, 125 },   // milk
          { 330, 8, 10, 180 }     // ice cream
          };

          // Model
          GRBEnv env = new GRBEnv();
          GRBModel model = new GRBModel(env);
          model.Set(GRB.StringAttr.ModelName, "diet");

          // Create decision variables for the nutrition information,
          // which we limit via bounds
          GRBVar[] nutrition = new GRBVar[nCategories];
          for (int i = 0; i < nCategories; ++i) {
        nutrition[i] =
            model.AddVar(minNutrition[i], maxNutrition[i], 0, GRB.CONTINUOUS,
                         Categories[i]);
          }

          // Create decision variables for the foods to buy
          GRBVar[] buy = new GRBVar[nFoods];
          for (int j = 0; j < nFoods; ++j) {
        buy[j] =
            model.AddVar(0, GRB.INFINITY, cost[j], GRB.CONTINUOUS, Foods[j]);
          }

          // The objective is to minimize the costs
          model.Set(GRB.IntAttr.ModelSense, 1);

          // Update model to integrate new variables
          model.Update();

          // Nutrition constraints
          for (int i = 0; i < nCategories; ++i) {
        GRBLinExpr ntot = 0.0;
        for (int j = 0; j < nFoods; ++j)
          ntot += nutritionValues[j,i] * buy[j];
        model.AddConstr(ntot == nutrition[i], Categories[i]);
          }

          // Solve
          model.Optimize();
          PrintSolution(model, buy, nutrition);

          Console.WriteLine("\nAdding constraint: at most 6 servings of dairy");
          model.AddConstr(buy[7] + buy[8] <= 6.0, "limit_dairy");

          // Solve
          model.Optimize();
          PrintSolution(model, buy, nutrition);

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

        } catch (GRBException e) {
          Console.WriteLine("Error code: " + e.ErrorCode + ". " +
          e.Message);
        }
    }
    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;
            }

            // Do IIS
            Console.WriteLine("The model is infeasible; computing IIS");
            model.ComputeIIS();
            Console.WriteLine("\nThe following constraint(s) "
                              + "cannot be satisfied:");
            foreach (GRBConstr c in model.GetConstrs())
            {
                if (c.IISConstr == 1)
                {
                    Console.WriteLine(c.ConstrName);
                }
            }

            // Dispose of model and env
            model.Dispose();
            env.Dispose();
        } catch (GRBException e) {
            Console.WriteLine("Error code: " + e.ErrorCode + ". " +
                              e.Message);
        }
    }
Ejemplo n.º 44
0
        public Instance Match(Instance instance, string path, bool print)
        {
            try
            {
                LP = "";
                if (!System.IO.Directory.Exists(path) && print)
                    System.IO.Directory.CreateDirectory(path);

                GRBEnv env = new GRBEnv("mip1.log");
                GRBModel model = new GRBModel(env);

                List<LPEdge> LPEdges = new List<LPEdge>();


                if (print)
                {
                    instance.Draw().Save(path + "/0Start.bmp");
                }

                int EdgeCounter = 0;
                foreach (Instance.Applicant a in instance.Applicants)
                {
                    EdgeCounter += a.Priorities.Count;
                    foreach (Instance.Priority Prio in a.Priorities)
                    {
                        {
                            LPEdges.Add(new LPEdge(a, instance.Posts[Prio.Target], Prio.Rank));
                            if (Prio.Rank == 0)
                                instance.Posts[Prio.Target].IsF = 1;
                        }
                    }

                }
                // Create variables

                GRBVar[] Edges = new GRBVar[EdgeCounter];

                for (int i = 0; i < Edges.Length; i++)
                {
                    Edges[i] = model.AddVar(0.0, 1.0, 0.0, GRB.BINARY, "ve" + i.ToString());
                }

                // Integrate new variables

                model.Update();

                if (print)
                    LP += "Applicant Matching Conditions:" + Environment.NewLine;

                foreach (Instance.Applicant a in instance.Applicants)
                {
                    GRBLinExpr Temp = new GRBLinExpr();
                    for (int i = 0; i < LPEdges.Count; i++)
                    {
                        if (LPEdges[i].Applicant == a)
                        {
                            Temp += Edges[i];
                            if (print)
                                LP += "(a" + LPEdges[i].Applicant.ID + ", p" + LPEdges[i].Post.ID + ") + ";
                        }
                    }
                    model.AddConstr(Temp == 1.0, "a" + a.ID.ToString());
                    if (print)
                        LP += " = 1;" + Environment.NewLine;
                }

                if (print)
                    LP += Environment.NewLine + "Post Matching Conditions:" + Environment.NewLine;
                
                foreach (Instance.Post p in instance.Posts)
                {
                    GRBLinExpr Temp = new GRBLinExpr();
                    for (int i = 0; i < LPEdges.Count; i++)
                    {
                        if (LPEdges[i].Post == p)
                        {
                            Temp += Edges[i];
                            if (print)
                                LP += "(a" + LPEdges[i].Applicant.ID + ", p" + LPEdges[i].Post.ID + ") + ";
                        }
                    }
                    model.AddConstr(Temp <= 1.0, "p" + p.ID.ToString());
                    if (print)
                        LP += " <= 1;" + Environment.NewLine;
                }

                if (print)
                    LP += Environment.NewLine + "First Choice Conditions:" + Environment.NewLine;

                for (int i = 0; i < LPEdges.Count; i++)
                {
                    LPEdge le1 = LPEdges[i];

                    if (le1.Post.IsF == 1 && le1.Rank != 0)
                    {
                        model.AddConstr(Edges[i] <= 0, "s" + i.ToString());
                        if (print)
                            LP += "(a" + LPEdges[i].Applicant.ID + ", p" + LPEdges[i].Post.ID + ") <= 0;" + Environment.NewLine;

                        for (int j = 0; j < LPEdges[i].Applicant.Priorities.Count; j++)
                        {
                            if (LPEdges[i].Applicant.Priorities[j].Target == LPEdges[i].Post.ID && LPEdges[i].Rank == LPEdges[i].Applicant.Priorities[j].Rank)
                            {
                                LPEdges[i].Applicant.Priorities.RemoveAt(j);
                            }
                        }
                    }
                }

                if (print)
                    LP += Environment.NewLine + "Second Choice Conditions:" + Environment.NewLine;

                for (int i = 0; i < LPEdges.Count; i++)
                {
                    LPEdge le1 = LPEdges[i];

                    foreach (LPEdge le2 in LPEdges)
                    {
                        if (le2 != le1 && le2.Post.IsF == 0 && le1.Applicant == le2.Applicant && le2.Rank != 0 && le2.Rank < le1.Rank)
                        {
                            model.AddConstr(Edges[i] <= 0, "s" + i.ToString());
                            if (print)
                                LP += "(a" + LPEdges[i].Applicant.ID + ", p" + LPEdges[i].Post.ID + ") <= 0;" + Environment.NewLine;
                            for (int j = 0; j < LPEdges[i].Applicant.Priorities.Count; j++)
                            {
                                if (LPEdges[i].Applicant.Priorities[j].Target == LPEdges[i].Post.ID && LPEdges[i].Rank == LPEdges[i].Applicant.Priorities[j].Rank)
                                {
                                    LPEdges[i].Applicant.Priorities.RemoveAt(j);
                                }
                            }
                            break;
                        }
                    }
                }

                if (print)
                    LP += Environment.NewLine + "First Post Conditions:" + Environment.NewLine;

                foreach (Instance.Post p in instance.Posts)
                {
                    if (p.IsF == 1)
                    {
                        GRBLinExpr Temp = new GRBLinExpr();
                        for (int i = 0; i < LPEdges.Count; i++)
                        {
                            if (LPEdges[i].Post == p)
                            {
                                Temp += Edges[i];
                                if (print)
                                    LP += "(a" + LPEdges[i].Applicant.ID + ", p" + LPEdges[i].Post.ID + ") + ";
                            }
                        }
                        model.AddConstr(Temp >= 1.0, "f" + p.ID.ToString());
                        if (print)
                            LP += ">= 1;" + Environment.NewLine;
                    }
                }


                // Optimize model

                model.Optimize();

                if (print)
                {
                    instance.Draw().Save(path + "/1Reduced.bmp");
                }

                for (int i = 0; i < Edges.Length; i++)
                {
                    if (Edges[i].Get(GRB.DoubleAttr.X) == 1)
                    {
                        instance.AddMatch(LPEdges[i].Post.ID, LPEdges[i].Applicant.ID);
                    }
                }

                if (print)
                {
                    instance.Draw().Save(path + "/2Matched.bmp");
                }

                // Dispose of model and env

                model.Dispose();
                env.Dispose();

                return instance;

            }
            catch (GRBException e)
            {
                Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
                return null;
            }
        }
Ejemplo n.º 45
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);
        }
    }
        public HttpResponseMessage Optimize(string RunName)
        {
            using (var dbConn = new ApplicationDbContext())
            {
                //Variables for students, semesters, courses, and course/semester offerings
                students = dbConn.StudentPreferences.Where(m => m.IsActive == true).Include(m => m.Courses).Include(m => m.Student.CompletedCourses).OrderByDescending(m => m.Student.CompletedCourses.Count()).ToArray();
                crssems = dbConn.CourseSemesters.Where(m => m.IsActive == true).Include(m => m.Course).Include(m => m.Semester).ToArray();
                courses = crssems.Select(m => m.Course).Distinct().ToArray();
                sems = crssems.Select(m => m.Semester).Distinct().OrderBy(m => m.Type).OrderBy(m => m.Year).ToArray();

                var completed = dbConn.CompletedCourses.ToList();
                try
                {
                    GRBEnv env = new GRBEnv("mip1.log");
                    GRBModel model = new GRBModel(env);
                    model.Set(GRB.StringAttr.ModelName, "Course Optimizer");
                    GRBVar[,] slacks = new GRBVar[courses.Length, sems.Length];

                    //Assignment of student, course, and semester.  Student must have a desire to take the coure, has not taken the course, and the course is offered to be included
                    GRBVar[,,] CourseAllocation = new GRBVar[students.Length, courses.Length, sems.Length];
                    for (int i = 0; i < students.Length; i++)
                    {
                        for (int j = 0; j < courses.Length; j++)
                        {
                            for (int k = 0; k < sems.Length; k++)
                            {
                                if (students[i].Courses.Contains(courses[j]) && !completed.Any(m => m.GaTechId == students[i].GaTechId && courses[j].ID == m.Course_ID) && crssems.Contains(crssems.SingleOrDefault(m => m.Course == courses[j] && m.Semester == sems[k])))
                                    CourseAllocation[i, j, k] = model.AddVar(0, 1, 1, GRB.BINARY, "students." + (i + 1).ToString() + "_Course." + (j + 1).ToString() + "_Semester." + (k + 1).ToString());
                                else
                                    CourseAllocation[i, j, k] = model.AddVar(0, 0, 1, GRB.BINARY, "students." + (i + 1).ToString() + "_Course." + (j + 1).ToString() + "_Semester." + (k + 1).ToString());
                            }
                        }
                    }
                    model.Set(GRB.IntAttr.ModelSense, 1);
                    model.Update();

                    //MUST TAKE DESIRED COURSE ONLY ONCE
                    //Constrains the students to only take courses they desire once and for when the course is offered and does not allow a repeat of a course in another semester
                    for (int i = 0; i < students.Length; i++)
                    {
                        for (int j = 0; j < courses.Length; j++)
                        {
                            if (students[i].Courses.Contains(courses[j]) && !completed.Any(m => m.GaTechId == students[i].GaTechId && courses[j].ID == m.Course_ID))
                            {
                                GRBLinExpr constStudentDesiredCourses = 0.0;
                                for (int k = 0; k < sems.Length; k++)
                                {
                                    if (crssems.Any(m => m.Course.ID == courses[j].ID && m.Semester.Type == sems[k].Type && m.Semester.Year == sems[k].Year))
                                        constStudentDesiredCourses.AddTerm(1.0, CourseAllocation[i, j, k]);
                                }
                                String sStudentDesiredCourses = "DesiredCourse." + j + 1 + "_Student." + i + 1;
                                model.AddConstr(constStudentDesiredCourses == 1, sStudentDesiredCourses);
                            }
                        }

                        //MAX COURSES PER SEMESTER
                        //Constrains the students to only have a maximum number of 2 courses per semester.
                        for (int k = 0; k < sems.Length; k++)
                        {
                            GRBLinExpr constMaxPerSem = 0.0;
                            for (int j = 0; j < courses.Length; j++)
                            {
                                if (!completed.Any(m => m.GaTechId == students[i].GaTechId && courses[j].ID == m.Course_ID) && (crssems.Any(m => m.Course.ID == courses[j].ID && m.Semester.Type == sems[k].Type && m.Semester.Year == sems[k].Year)))
                                    constMaxPerSem.AddTerm(1, CourseAllocation[i, j, k]);
                            }
                            String sCourseSem = "maxCourseStudent." + i + 1 + "_Semester." + k + 1;
                            model.AddConstr(constMaxPerSem <= MAX_COURSES_PER_SEMESTER, sCourseSem);
                        }

                        //PREREQUISITES
                        //Constrains the students to take prerequisite courses prior to taking a course that needs the prerequisite
                        for (int j = 0; j < courses.Length; j++)
                        {
                            if (courses[j].Prerequisites.Any() && students[i].Courses.Contains(courses[j]) && !completed.Any(m => m.GaTechId == students[i].GaTechId && courses[j].ID == m.Course_ID))
                            {

                                foreach (var prereq in courses[j].Prerequisites)
                                {
                                    int prereqIndex = Array.IndexOf(courses, prereq);
                                    GRBLinExpr coursePrereqConst1 = 0.0;
                                    GRBLinExpr coursePrereqConst2 = 0.0;
                                    if (!completed.Any(m => m.GaTechId == students[i].GaTechId && m.Course.ID == prereq.ID))
                                    {

                                        for (int k = 0; k < sems.Length; k++)
                                        {

                                            if (prereqIndex >= 0)
                                            {
                                                coursePrereqConst1.AddTerm(k + 1, CourseAllocation[i, prereqIndex, k]);
                                                coursePrereqConst2.AddTerm(k, CourseAllocation[i, j, k]);
                                            }
                                        }
                                    }
                                    model.AddConstr(coursePrereqConst1, GRB.LESS_EQUAL, coursePrereqConst2, "PREREQ_Student" + i + "_Course+" + j + "_Prereq" + prereqIndex);

                                }

                            }
                        }
                    }

                    //SENIORITY
                    //Students are already ordered from dB query by seniority in descending order and puts a preference to senior students over the next student that desires that
                    //same course with less seniority.
                    for (int j = 0; j < courses.Length; j++)
                    {
                        for (int i = 0; i < students.Length - 1; i++)
                        {
                            if (students[i].Courses.Contains(courses[j]) && !completed.Any(m => m.GaTechId == students[i].GaTechId && courses[j].ID == m.Course_ID))
                            {
                                int SemsRemain = (students[i].Courses.Count - students[i].Student.CompletedCourses.Count) / 2 + (students[i].Courses.Count - students[i].Student.CompletedCourses.Count) % 2;
                                for (int n = i + 1; n < students.Length; n++)
                                {
                                    if (students[n].Courses.Contains(courses[j]) && !completed.Any(m => m.GaTechId == students[n].GaTechId && courses[j].ID == m.Course_ID))
                                    {
                                        GRBLinExpr​ seniority = 0.0;
                                        for (int k = 0; k < sems.Length; k++)
                                        {
                                            if (crssems.Any(m => m.Course.ID == courses[j].ID && m.Semester.Type == sems[k].Type && m.Semester.Year == sems[k].Year))
                                            {
                                                if (k <= SemsRemain)
                                                {
                                                    seniority​.AddTerm(1.0, CourseAllocation[i, j, k]);
                                                    seniority​.AddTerm(-1.0, CourseAllocation​[n, j, k]);
                                                }
                                                else
                                                {
                                                    seniority​.AddTerm(-1.0, CourseAllocation[i, j, k]);
                                                    seniority​.AddTerm(1.0, CourseAllocation​[n, j, k]);
                                                }
                                            }
                                        }
                                        model.AddConstr(seniority, GRB.GREATER_EQUAL, 0, "Seniority for Student." + students[i] + "_Course." + courses[j]);
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    //Add the slack variable for all semester & course offerings then constrain the maximum number of students
                    //to take a couse in a semester.
                    for (int k = 0; k < sems.Length; k++)
                    {
                        for (int j = 0; j < courses.Length; j++)
                        {
                            if (crssems.Any(m => m.Course.ID == courses[j].ID && m.Semester.Type == sems[k].Type && m.Semester.Year == sems[k].Year))
                            {
                                slacks[j, k] = model.AddVar(0, GRB.INFINITY, 0, GRB.INTEGER, sems[k].Type.ToString() + "." + sems[k].Year.ToString() + "." + courses[j].Name + ".Slacks");
                                GRBLinExpr constMaxStudCrsSem = 0.0;
                                for (int i = 0; i < students.Length; i++)
                                {
                                    if (!completed.Any(m => m.GaTechId == students[i].GaTechId && courses[j].ID == m.Course_ID))
                                        constMaxStudCrsSem.AddTerm(1.0, CourseAllocation[i, j, k]);
                                }
                                model.Update();
                                constMaxStudCrsSem.AddTerm(-1.0, slacks[j, k]);
                                model.AddConstr(constMaxStudCrsSem <= crssems.Single(m => m.Course.ID == courses[j].ID && m.Semester.Type == sems[k].Type && m.Semester.Year == sems[k].Year).StudentLimit, sems[k].Type.ToString() + "." + sems[k].Year.ToString() + "." + courses[j].Name);
                            }
                        }
                    }

                    //Add total slack to the optimization model for all courses in the semesters they are offered.
                    GRBVar totSlack = model.AddVar(0, GRB.INFINITY, 0, GRB.INTEGER, "totSlack");
                    GRBLinExpr lhs = new GRBLinExpr();
                    lhs.AddTerm(-1.0, totSlack);
                    for (int j = 0; j < courses.Length; j++)
                    {
                        for (int k = 0; k < sems.Length; k++)
                        {
                            if (crssems.Any(m => m.Course.ID == courses[j].ID && m.Semester.Type == sems[k].Type && m.Semester.Year == sems[k].Year))
                                lhs.AddTerm(1.0, slacks[j, k]);
                        }
                    }
                    model.Update();
                    model.AddConstr(lhs, GRB.EQUAL, 0, "totSlack");

                    // Objective: minimize the total slack
                    GRBLinExpr obj = new GRBLinExpr();
                    obj.AddTerm(1.0, totSlack);
                    model.SetObjective(obj);

                    //Optimize the model to minimize the total slack and maximize students to course offerings based on input variables and constraints.
                    model.Optimize();

                    //Write Results optimization results to database
                    writeResults(CourseAllocation, students, courses, sems, crssems, dbConn, Convert.ToInt32(model.Get(GRB.DoubleAttr.ObjVal)), RunName);

                    //Clean-Up
                    model.Dispose();
                    env.Dispose();
            }
                catch (Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "An Error occured while running the optimization.");
            }
            }
            return Request.CreateResponse(HttpStatusCode.OK);
        }