Пример #1
0
 private void MinRouteSmallerThanMaxRoute(GRBModel model, GRBVar[] minRoutes, GRBVar[] maxRoutes)
 {
     for (int s = 0; s < minRoutes.Length; s++)
     {
         model.AddConstr(minRoutes[s] <= maxRoutes[s], GurobiVarName($"minRoutesSmallerThanMaxRoutesForSanta{s}"));
     }
 }
Пример #2
0
 public MasterProblem(GRBEnv env, List <Vehicle> vehicles, List <Customer> vertices)
 {
     _vehicles = vehicles;
     _vertices = vertices;
     _model    = new GRBModel(env);
     Generate();
 }
Пример #3
0
 public static void Remove(this GRBModel model, IEnumerable <GRBSOS> constraints)
 {
     foreach (var constraint in constraints)
     {
         model.Remove(constraint);
     }
 }
Пример #4
0
        private void BuildMIPModel()
        {
            _env   = new GRBEnv();
            _model = new GRBModel(_env);


            //room used.
            varR = new Dictionary <Room, GRBVar>();
            foreach (var room in Data.Rooms)
            {
                varR[room] = _model.AddVar(0, GRB.INFINITY, room.Cost, GRB.INTEGER,
                                           $"r_{room}");
            }

            _model.Update();



            _model.AddConstr(Data.TimeSlots.Count * varR.Values.Sumx(), GRB.GREATER_EQUAL, Data.Courses.Sum(c => c.Lectures), "");

            foreach (var roomCapacity in Data.RoomCapacities)
            {
                var overCap = OverCapacity * ((double)Data.Courses.Where(c => c.NumberOfStudents > roomCapacity.Value).Sum(c => c.Lectures) / Data.TimeSlots.Count);
                _model.AddConstr(varR.Where(r => r.Key.Capacity > roomCapacity.Value).Sumx(r => r.Value) * Data.TimeSlots.Count, GRB.GREATER_EQUAL,
                                 Data.Courses.Where(c => c.NumberOfStudents > roomCapacity.Value).Sum(c => c.Lectures) + overCap,
                                 $"roomcapcut_{roomCapacity.Value}");
            }

            _model.SetCallback(new OutputCallback());
        }
Пример #5
0
 public static void SetTimeLimit(this GRBModel model, TimeSpan?timeLimit)
 {
     if (timeLimit.HasValue)
     {
         model.Parameters.TimeLimit = timeLimit.Value.TotalSeconds;
     }
 }
Пример #6
0
        private void IncomingOutgoingWaysConstraints(GRBModel model, int numberOfRoutes, GRBVar[][] w, GRBVar[][] v)
        {
            for (int i = 1; i < distances.GetLength(0); i++)
            {
                if (input.Visits[i - 1].IsBreak)
                {
                    continue;
                }

                var wki = new GRBLinExpr(0);
                var wik = new GRBLinExpr(0);

                for (int s = 0; s < numberOfRoutes; s++)
                {
                    for (int k = 0; k < distances.GetLength(1); k++)
                    {
                        var swki = AccessW(w[s], k, i);
                        var swik = AccessW(w[s], i, k);

                        wki += swki;
                        wik += swik;
                    }
                }

                model.AddConstr(wki == 1, $"v{i} incoming ways == 1");
                model.AddConstr(wik == 1, $"v{i} outgoing ways == 1");
            }
        }
Пример #7
0
        private void BreakHandling(GRBModel model, int numberOfRoutes, GRBVar[][] v)
        {
            for (int i = 1; i < visitDurations.Length; i++)
            {
                if (!input.Visits[i - 1].IsBreak)
                {
                    continue;
                }

                var visit       = input.Visits[i - 1];
                var breakRoutes = new List <int>();
                for (var day = 0; day < input.Days.Length; day++)
                {
                    var s = visit.SantaId + day * input.Santas.Length;
                    model.AddGenConstrOr(v[s][i], v[s].Take(i - 1).Skip(1).ToArray(), null); // assignment if used
                    breakRoutes.Add(s);
                }

                // break cannot be visited by another santa
                foreach (var nonBreakRoute in Enumerable.Range(0, numberOfRoutes).Except(breakRoutes))
                {
                    model.AddConstr(v[nonBreakRoute][i] == 0, null);
                }
            }
        }
        public GurobiSolver()
        {
            var grbEnv = new GRBEnv();

            _grbModel = new GRBModel(grbEnv);
            _varArray = new Dictionary <string, GRBVar>();
        }
Пример #9
0
 static void PrintSolution(GRBModel m)
 {
     foreach (GRBVar var in m.GetVars())
     {
         Console.WriteLine("{0} = {1}", var.Get(GRB.StringAttr.VarName), var.Get(GRB.DoubleAttr.X));
     }
 }
Пример #10
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();
        }
Пример #11
0
        private void UpdateModels(GRBModel model, List <List <GRBVar> > varsFromElements)
        {
            if (Constants.ENABLE_DEBUG_OUTPUT)
            {
                OutputDebugVars(model);
            }

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

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

                if (lod > -1)
                {
                    currentElement.Visibility           = 1.0;
                    currentElement.CurrentLevelOfDetail = lod;
                }
                else
                {
                    currentElement.Visibility = 0.0;
                }
            }
        }
Пример #12
0
 private static void PrintSolution(GRBModel model, GRBVar[] buy,
                                   GRBVar[] nutrition)
 {
     if (model.Status == GRB.Status.OPTIMAL)
     {
         Console.WriteLine("\nCost: " + model.ObjVal);
         Console.WriteLine("\nBuy:");
         for (int j = 0; j < buy.Length; ++j)
         {
             if (buy[j].X > 0.0001)
             {
                 Console.WriteLine(buy[j].VarName + " " + buy[j].X);
             }
         }
         Console.WriteLine("\nNutrition:");
         for (int i = 0; i < nutrition.Length; ++i)
         {
             Console.WriteLine(nutrition[i].VarName + " " + nutrition[i].X);
         }
     }
     else
     {
         Console.WriteLine("No solution");
     }
 }
Пример #13
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();
        }
Пример #14
0
        // This method will work irrespective of the size of the solution space
        public ProductionTarget GetTargets(double claySupply, double glazeSupply)
        {
            GRBEnv   env   = new GRBEnv();
            GRBModel model = new GRBModel(env);
            GRBVar   xS    = CreateSmallVasesVariable(claySupply, model);
            GRBVar   xL    = CreateLargeVasesVariable(glazeSupply, model);

            model.Update();

            // Create Constraints
            CreateConstraints(model, xS, xL, claySupply, glazeSupply);

            // Define Objective
            model.SetObjective(3 * xS + 9 * xL, GRB.MAXIMIZE);

            // Find the optimum
            model.Optimize();

            // Load the results
            var results = model.Get(GRB.DoubleAttr.X, new GRBVar[] { xS, xL });

            return(new Entities.ProductionTarget()
            {
                Small = Convert.ToInt32(results[0]), Large = Convert.ToInt32(results[1])
            });
        }
Пример #15
0
 private void SetupGurobiEnvironmentAndModel()
 {
     // Model
     env   = new GRBEnv();
     model = new GRBModel(env);
     model.Set(GRB.StringAttr.ModelName, "diet");
 }
Пример #16
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();
        }
Пример #17
0
        private void AddDistanceConstraints(GRBModel model, GRBVar[,,] seated)
        {
            for (int g1 = 0; g1 < Cinema.TotalNumberOfGroups; g1++)
            {
                for (int g2 = 0; g2 < Cinema.TotalNumberOfGroups; g2++)
                {
                    if (g1 < g2)
                    {
                        var size1 = Cinema.GroupSizes[g1];
                        var size2 = Cinema.GroupSizes[g2];
                        // Loop over all legal start positions for group 1
                        foreach (var pos1 in Cinema.LegalStartPositions[size1 - 1])
                        {
                            var x1 = pos1.Item1;
                            var y1 = pos1.Item2;

                            // Collect invalid seats
                            var invalidSeats = Cinema.GetInvalidSeats(x1, y1, size1, size2);
                            foreach (var pos2 in invalidSeats)
                            {
                                if (Cinema.LegalStartPositions[size2 - 1].Any(m => m == pos2))
                                {
                                    var x2 = pos2.Item1;
                                    var y2 = pos2.Item2;

                                    model.AddConstr(seated[x1, y1, g1] + seated[x2, y2, g2], GRB.LESS_EQUAL, 1, "Distance constaint");
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #18
0
 public static void Remove(this GRBModel model, IEnumerable <GRBVar> variables)
 {
     foreach (var variable in variables)
     {
         model.Remove(variable);
     }
 }
Пример #19
0
        private void StoreAllSolutions(GRBModel model)
        {
            _model.Solutions.Clear();

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

                var vars = model.GetVars();

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

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

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

                    solution.AddEntry(id, lod, visibility);

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

                solution.Objective = currentSolutionObjective;
                _model.Solutions.Add(solution);
            }
        }
Пример #20
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);
        }
    }
Пример #21
0
        /// <summary>
        /// Gets the final <see cref="GurobiRuntimeFeatures"/>.
        /// </summary>
        /// <param name="model">The <see cref="GRBModel"/>.</param>
        /// <param name="result">The <see cref="GurobiResult"/>.</param>
        /// <returns>The final <see cref="GurobiRuntimeFeatures"/>.</returns>
        private GurobiRuntimeFeatures GetFinalGurobiRuntimeFeatures(GRBModel model, GurobiResult result)
        {
            // Get current runtime features.
            var runtimeFeatures = this.GetCurrentGurobiRuntimeFeatures();

            // Update all feature values, provided by GurobiResult.
            runtimeFeatures.MipGap = result.Gap;

            // Update all feature values, provided by GRBModel.
            runtimeFeatures.BarrierIterationsCount = this.GetValueWithTryCatch(
                () => model.BarIterCount,
                runtimeFeatures.BarrierIterationsCount);
            runtimeFeatures.BestObjective          = this.GetValueWithTryCatch(() => model.ObjVal, runtimeFeatures.BestObjective);
            runtimeFeatures.BestObjectiveBound     = this.GetValueWithTryCatch(() => model.ObjBound, runtimeFeatures.BestObjectiveBound);
            runtimeFeatures.ExploredNodeCount      = this.GetValueWithTryCatch(() => model.NodeCount, runtimeFeatures.ExploredNodeCount);
            runtimeFeatures.SimplexIterationsCount = this.GetValueWithTryCatch(() => model.IterCount, runtimeFeatures.SimplexIterationsCount);

            // Since GRBModel does not provide the number of unexplored nodes, use last entry or 0, depending on the run status.
            runtimeFeatures.UnexploredNodeCount =
                result.TargetAlgorithmStatus != TargetAlgorithmStatus.Finished ? runtimeFeatures.UnexploredNodeCount : 0;

            // Since GRBModel.SolCount just reports the number of stored solutions, use maximum between last entry and GRBModel.SolCount.
            var feasibleSolutionsCountFromModel = this.GetValueWithTryCatch(() => model.SolCount, runtimeFeatures.FeasibleSolutionsCount);

            runtimeFeatures.FeasibleSolutionsCount = Math.Max(feasibleSolutionsCountFromModel, runtimeFeatures.FeasibleSolutionsCount);

            return(runtimeFeatures);
        }
Пример #22
0
        /// <summary>
        /// I used this Gurobi model to calculate the fixed point baseline.
        /// </summary>
        public mae_sdo()
        {
            string path = @"C:\Users\Roman Bolzern\Desktop\D4\neu\meta_data_training.csv";

            var lines = File.ReadLines(path).ToArray();

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

            var scale = 1e9;

            var y = m.AddVar(1e-9 * scale, 1e-2 * scale, 0d, GRB.CONTINUOUS, "y");

            var obj = new GRBLinExpr();

            for (int i = 1; i < lines.Length; i++)
            {
                var diff      = double.Parse(lines[i].Split(',')[3]) * scale - y;
                var diffinput = m.AddVar(-1e-2 * scale, 1e-2 * scale, 0d, GRB.CONTINUOUS, "diffinput");
                m.AddConstr(diffinput == diff);
                var diffres = m.AddVar(0, 1e-2 * scale, 0d, GRB.CONTINUOUS, "diffres");
                m.AddGenConstrAbs(diffres, diffinput, "diffAbs");
                obj += diffres;
            }

            m.SetObjective(obj, GRB.MINIMIZE);
            m.Optimize();

            Console.WriteLine($"Objective: {((GRBLinExpr)m.GetObjective()).Value / scale}");
            Console.WriteLine($"fixed point: {y.X / scale}");
        }
Пример #23
0
        public override int AddSos(object solver, string name, int sostype, int priority, int count, int[] sosvars, double[] weights)
        {
            GRBModel grbSolver = solver as GRBModel;

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

            return(1);
        }
Пример #24
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();
        }
Пример #25
0
    private static int solveAndPrint(GRBModel model, GRBVar totSlack,
                                     int nWorkers, String[] Workers,
                                     GRBVar[] totShifts)
    {
        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");
            return(status);
        }
        if (status != GRB.Status.OPTIMAL)
        {
            Console.WriteLine("Optimization was stopped with status " + status);
            return(status);
        }

        // Print total slack and the number of shifts worked for each worker
        Console.WriteLine("\nTotal slack required: " + totSlack.X);
        for (int w = 0; w < nWorkers; ++w)
        {
            Console.WriteLine(Workers[w] + " worked " +
                              totShifts[w].X + " shifts");
        }
        Console.WriteLine("\n");
        return(status);
    }
Пример #26
0
            /// <summary>
            /// 求解主问题
            /// </summary>
            /// <returns></returns>
            public bool Solve()
            {
                _env              = new GRBEnv();
                _env.OutputFlag   = 0;
                _env.LogToConsole = 0;

                _model = new GRBModel(_env);

                BuildVar();
                BuildConst();

                _model.Write("Benders_Master.lp");
                _model.Optimize();
                if (_model.Status == GRB.Status.OPTIMAL)
                {
                    Frmk.SlaveObj = new SlaveObjCoef();
                    foreach (Node n in Frmk.Data.NodeSet)
                    {
                        double x = _model.GetVarByName("x_" + n.ID).X;
                        Frmk.SlaveObj.x.Add(n, Convert.ToInt32(x));
                    }
                    Output();
                    return(true);
                }
                else
                {
                    throw new ApplicationException("没可行解!");
                    return(false);
                }
            }
Пример #27
0
 public Cplex()
 {
     this._env = new GRBEnv("gurobi.log");
     this._model = new GRBModel(_env);
     _model.GetEnv().Set(GRB.IntParam.UpdateMode, 1);
     this._status = 0;
 }
Пример #28
0
        private void AddDoNotSeatOutOfBoundsConstraint(GRBModel model, GRBVar[,,] seated)
        {
            for (int x = 0; x < Cinema.Width; x++)
            {
                for (int y = 0; y < Cinema.Height; y++)
                {
                    for (int g = 0; g < Cinema.TotalNumberOfGroups; g++)
                    {
                        var anyZeroes = false;

                        for (int i = 0; i < Cinema.GroupSizes[g]; i++)
                        {
                            if (x + i >= Cinema.Width || Cinema.Seats[x + i, y] == 0)
                            {
                                anyZeroes = true;
                                break;
                            }
                        }

                        if (anyZeroes)
                        {
                            model.AddConstr(seated[x, y, g], GRB.LESS_EQUAL, 0, "Out of bounds constraint");
                        }
                    }
                }
            }
        }
Пример #29
0
 public void SetupDecisionVariables(GRBModel model)
 {
     // Create decision variables for the nutrition information,
     // which we limit via bounds
     SetupNutritionDecisionVariables(model);
     // Create decision variables for the foodTypes to buy
     SetupBuyDecisionVariables(model);
 }
Пример #30
0
        private void AddContraints(GRBModel model, GRBVar[,,] seated)
        {
            AddOnlyOnePositionPerGroupConstraint(model, seated);

            AddDoNotSeatOutOfBoundsConstraint(model, seated);

            AddDistanceConstraintsParallel(model, seated);
        }
 /// <summary>
 /// Checks, if the run is interrupted.
 /// </summary>
 /// <param name="model">The model.</param>
 /// <returns>True, if run is interrupted.</returns>
 private bool GetIsRunInterrupted(GRBModel model)
 {
     return(model.Status == GRB.Status.INTERRUPTED ||
            model.Status == GRB.Status.TIME_LIMIT ||
            model.Status == GRB.Status.NUMERIC ||
            model.Status == GRB.Status.INPROGRESS ||
            model.Status == GRB.Status.LOADED);
 }
Пример #32
0
 public void ImportModel(string file)
 {
     if (_model != null)
     {
         _model.Dispose();
         _model = null;
     }
     this._model = new GRBModel(_env, file);
 }
Пример #33
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);
        }
    }
Пример #34
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);
        }
    }
Пример #35
0
 public DecisionVariableSet(GRBModel model, IEnumerable<DecisionVariableData> decisionVariableData, string label)
 {
     // Create decision variables for the nutrition information,
     // which we limit via bounds
     NumberOfDecisonVariables = decisionVariableData.Count();
     decisionVariables = new GRBVar[NumberOfDecisonVariables];
     int i = 0;
     foreach (var dv in decisionVariableData)
     {
         decisionVariables[i] = dv.AddToModel(model);
         i++;
     }
     _label = label;
 }
Пример #36
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);
        }
    }
Пример #37
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);
        }
    }
Пример #38
0
 public void getOldList(GRBModel model, GRBConstr constr)
 {
     model.Update();
     GRBLinExpr linExpr = model.GetRow(constr);
     oldDict = new Dictionary<GRBVar, double>();
     for (int i = 0; i < linExpr.Size; i++)
     {
         GRBVar var = linExpr.GetVar(i);
         double val = linExpr.GetCoeff(i);
         if (oldDict.ContainsKey(var))
         {
             oldDict[var] += val;
         }
         else
         {
             oldDict[var] = val;
         }
     }
     constrs = new GRBConstr[1];
     constrs[0] = constr;
 }
Пример #39
0
        private GRBVar[,] _x; // starting time of job j on machine a

        #endregion Fields

        #region Constructors

        public GurobiJspModel(ProblemInstance prob, string name, int tmlim_min)
        {
            _n = prob.NumJobs;
            _m = prob.NumMachines;
            Info = "Starting gurobi optimisation";
            _fileName = String.Format("jssp.{0}.log", name);

            // Model
            try
            {
                _env = new GRBEnv(_fileName);
                if (tmlim_min > 0)
                    _env.Set(GRB.DoubleParam.TimeLimit, tmlim_min*60); // time limit is set to seconds!
                _env.Set(GRB.IntParam.LogToConsole, 0);

                _model = new GRBModel(_env);
                _model.Set(GRB.StringAttr.ModelName, "jsp");
            }
            catch (GRBException e)
            {
                Console.WriteLine("Error code: " + e.ErrorCode + ". " + e.Message);
            }

            DecisionVariables();
            ProcessingOrder(prob.Procs, prob.Sigma);
            DisjunctiveCondition(prob.Procs);
            Objective(prob.Procs, prob.Sigma);

            //TrueOptimumDecVars = Optimise(out TrueOptimum);
            //if (TrueOptimum > 0) // Objective cutoff
            //    _model.GetEnv().Set(GRB.DoubleParam.Cutoff, TrueOptimum + 0.5);
            /* Indicates that you aren't interested in solutions whose objective values
                 * are worse than the specified value. If the objective value for the optimal
                 * solution is better than the specified cutoff, the solver will return the
                 * optimal solution. Otherwise, it will terminate with a CUTOFF status.
                 */
            // seems to be only for LP relaxation, not MIP objective
        }
Пример #40
0
 public IObjective(GRBModel model, int sense)
     : base()
 {
     this.model = model;
     this.sense = sense;
 }
Пример #41
0
 public IObjective(GRBModel model, INumExpr expr)
     : base(expr.expr)
 {
     this.model = model;
     this.sense = GRB.MINIMIZE;    // default
 }
Пример #42
0
 public GRBVar AddToModel(GRBModel model)
 {
     return model.AddVar(lowerBound, upperBound, ObjectiveCoefficient, variableType, name);
 }
Пример #43
0
 private void SetupGurobiEnvironmentAndModel()
 {
     // Model
     env = new GRBEnv();
     model = new GRBModel(env);
     model.Set(GRB.StringAttr.ModelName, "diet");
 }
Пример #44
0
 /// <summary>
 /// Adds the Gurobi OPF model for the provided power system, to the provided gurobi model.
 /// </summary>
 /// <param name="powerSystem"></param>
 /// <param name="env"></param>
 /// <param name="model"></param>
 public OPFModel(IPowerSystem powerSystem, GRBEnv env, GRBModel model)
     : base(env,model)
 {
     this.MyPowerSystem = powerSystem;
 }
Пример #45
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;
            }
        }
Пример #46
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);
        }
    }
Пример #47
0
 public void AddNutritionConstraints(GRBModel model)
 {
     // Nutrition constraints
     for (int i = 0; i < NumberOfCategories; ++i)
     {
         GRBLinExpr ntot = 0.0;
         for (int j = 0; j < numberOfFoodTypes; ++j)
             ntot += nutritionValues[j, i] * boughtAmount[j];
         model.AddConstr(ntot == nutritionDecisionVariables[i], categories[i]);
     }
 }
Пример #48
0
 public void AddExtraConstraint(GRBModel model)
 {
     model.AddConstr(boughtAmount[7] + boughtAmount[8] <= 6.0, "limit_dairy");
 }
Пример #49
0
 public IObjective(GRBModel model, INumExpr expr, int sense)
     : base(expr.expr)
 {
     this.model = model;
     this.sense = sense;
 }
Пример #50
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);
        }
    }
Пример #51
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;
    }
        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);
        }
Пример #53
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);
        }
    }
Пример #54
0
 public IObjective(GRBModel model)
     : base()
 {
     this.model = model;
     this.sense = GRB.MINIMIZE;    // default
 }
Пример #55
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);
        }
    }
Пример #56
0
 public void SetupBuyDecisionVariables(GRBModel model)
 {
     boughtAmount = new DecisionVariableSet(model, GetBoughtAmountDecisionVariables(), "Buy");
 }
Пример #57
0
 private static void PrintSolution(GRBModel model, GRBVar[] buy,
                                 GRBVar[] nutrition)
 {
     if (model.Get(GRB.IntAttr.Status) == GRB.Status.OPTIMAL) {
       Console.WriteLine("\nCost: " + model.Get(GRB.DoubleAttr.ObjVal));
       Console.WriteLine("\nBuy:");
       for (int j = 0; j < buy.Length; ++j) {
     if (buy[j].Get(GRB.DoubleAttr.X) > 0.0001) {
       Console.WriteLine(buy[j].Get(GRB.StringAttr.VarName) + " " +
           buy[j].Get(GRB.DoubleAttr.X));
     }
       }
       Console.WriteLine("\nNutrition:");
       for (int i = 0; i < nutrition.Length; ++i) {
     Console.WriteLine(nutrition[i].Get(GRB.StringAttr.VarName) + " " +
         nutrition[i].Get(GRB.DoubleAttr.X));
       }
     } else {
       Console.WriteLine("No solution");
     }
 }
Пример #58
0
 public void SetupDecisionVariables(GRBModel model)
 {
     // Create decision variables for the nutrition information,
     // which we limit via bounds
     SetupNutritionDecisionVariables(model);
     // Create decision variables for the foodTypes to buy
     SetupBuyDecisionVariables(model);
 }
Пример #59
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);
        }
    }
Пример #60
0
 public void SetupNutritionDecisionVariables(GRBModel model)
 {
     nutritionDecisionVariables = new DecisionVariableSet(model, GetNutritionDecisionVariables(), "Nutrition");
 }