private void InitGoogleSolver() { PrintDebugRessourcesBefore("InitGoogleSolver"); model.Reset(); PrintDebugRessourcesAfter(); }
public override int DeleteLp(object solver) { GRBModel grbSolver = solver as GRBModel; if (grbSolver == null) { return(-1); } grbSolver.Reset(); return(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); } }
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); } }
public void Reset() { Create(); _model.Reset(); _variables.Clear(); _arrivalTimes.Clear(); _value = 0; _prepS = _model.AddVar(0, double.PositiveInfinity, 0, GRB.CONTINUOUS, "prep"); _execS = _model.AddVar(0, double.PositiveInfinity, 0, GRB.CONTINUOUS, "exec"); _variables[(int)VariableTypes.PreperationTime] = _prepS; _variables[(int)VariableTypes.ExecutionTime] = _execS; }
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); } }
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); } }
public List <int[]> SolveVRP(int timeLimitMilliseconds) { using (var env = new GRBEnv($"{DateTime.Now:yy-MM-dd-HH-mm-ss}_vrp_gurobi.log")) using (var vrpModel = new GRBModel(env)) { #region initialize Variables var numberOfRoutes = input.Santas.Length * input.Days.Length; var v = new GRBVar[numberOfRoutes][]; // [santa] visits [visit] var w = new GRBVar[numberOfRoutes][]; // [santa] uses [way] for (int s = 0; s < numberOfRoutes; s++) { v[s] = new GRBVar[visitDurations.Length]; for (int i = 0; i < v[s].Length; i++) { v[s][i] = vrpModel.AddVar(0, 1, 0.0, GRB.BINARY, $"v[{s}][{i}]"); } w[s] = vrpModel.AddVars(distances.GetLength(0) * distances.GetLength(1), GRB.BINARY); } #endregion initialize Variables #region add constraints SelfieConstraint(vrpModel, numberOfRoutes, w); VisitVisitedOnce(vrpModel, numberOfRoutes, v); IncomingOutgoingWaysConstraints(vrpModel, numberOfRoutes, w, v); IncomingOutgoingSanta(vrpModel, numberOfRoutes, v, w); IncomingOutgoingSantaHome(vrpModel, numberOfRoutes, w, v); NumberOfWaysMatchForSanta(vrpModel, numberOfRoutes, v, w); BreakHandling(vrpModel, numberOfRoutes, v); #endregion add constraints var totalWayTime = new GRBLinExpr(0); var longestRoute = vrpModel.AddVar(0, input.Days.Max(d => d.to - d.from), 0, GRB.CONTINUOUS, "longestRoute"); for (int s = 0; s < numberOfRoutes; s++) { var routeTime = new GRBLinExpr(0); for (int i = 0; i < visitDurations.Length; i++) { routeTime += v[s][i] * visitDurations[i]; for (int j = 0; j < visitDurations.Length; j++) { routeTime += AccessW(w[s], i, j) * distances[i, j]; } } totalWayTime += routeTime; vrpModel.AddConstr(longestRoute >= routeTime, $"longesRouteConstr{s}"); } vrpModel.SetObjective( +(40d / 3600d) * totalWayTime + (30d / 3600d) * longestRoute , GRB.MINIMIZE); vrpModel.Parameters.LazyConstraints = 1; vrpModel.SetCallback(new VRPCallbackSolverCallback(w, AccessW, ConvertBack)); vrpModel.Parameters.TimeLimit = timeLimitMilliseconds / 1000; InitializeModel(w, v, numberOfRoutes, input.Visits, input.Santas.Length); vrpModel.Optimize(); if (vrpModel.SolCount == 0) { return(null); } var routes = new List <int[]>(); for (int s = 0; s < numberOfRoutes; s++) { var route = new List <int>(); var currVisit = 0; do { route.Add(currVisit); for (int i = 0; i < visitDurations.Length; i++) { if (AccessW(w[s], currVisit, i).X > 0.5) { currVisit = i; break; } } } while (currVisit != 0); routes.Add(route.ToArray()); } vrpModel.Reset(); return(routes); } }
// return false if not enough tick data public bool TryGetTickRecommendations() { var env = new GRBEnv(); env.LogToConsole = 0; var model = new GRBModel(env); var userTickData = new List <UserTickData>(); foreach (var history in _tickHistories) { var userNum = _tickHistories.IndexOf(history); // todo // todo time delta if (history.GetValidInbetweenCount < 5) { Logger.Warn($"Not enough inbetweens for {userNum}, has {history.GetValidInbetweenCount}"); return(false); } history.GetStatistics(out float average, out float std); var userTick = new UserTickData { LastTickSeconds = history.LastTickSeconds, // this needs to be close enough to a min tick time AvgDelta = average, StdDelta = std, TimeFrame = FindTicksInSeconds }; userTickData.Add(userTick); GRBVar avgVar = model.AddVar(0, double.PositiveInfinity, 0, GRB.CONTINUOUS, $"avg_u{userNum}"); userTick.RecommendedAvgVar = avgVar; } // variant 1: make them sync // variant 2: find a possible intersection point??? perhaps this is already handled by the prep time thing var stdOffsetFactor = .5f; var meanDeltaDistance = .1f; GRBLinExpr minimizeValue = 0; // finde kleinsten gemeinsamen nenner for (int userNum = 0; userNum < userTickData.Count; userNum++) { var userInfo = userTickData[userNum]; model.AddConstr(userInfo.RecommendedAvgVar <= userInfo.AvgDelta + userInfo.StdDelta * stdOffsetFactor, $"ubound_avg_u{userNum}"); model.AddConstr(userInfo.RecommendedAvgVar >= userInfo.AvgDelta - userInfo.StdDelta * stdOffsetFactor, $"lbound_avg_u{userNum}"); GRBVar absAvgDelta = model.AddVar(0, double.PositiveInfinity, 0, GRB.CONTINUOUS, $"abs_avg_delta_u{userNum}"); model.AddConstr(userInfo.RecommendedAvgVar - userInfo.AvgDelta <= absAvgDelta, $"abs_avg_delta_r-a_u{userNum}"); model.AddConstr(userInfo.AvgDelta - userInfo.RecommendedAvgVar <= absAvgDelta, $"abs_avg_delta_a-r_u{userNum}"); minimizeValue += absAvgDelta; for (int otherNum = userNum + 1; otherNum < userTickData.Count; otherNum++) { var otherInfo = userTickData[otherNum]; GRBVar interval = model.AddVar(0, double.PositiveInfinity, 0, GRB.CONTINUOUS, $"interval_u{userNum}_u{otherNum}"); GRBVar smaller; GRBVar larger; if (userInfo.AvgDelta <= otherInfo.AvgDelta) { smaller = userInfo.RecommendedAvgVar; larger = otherInfo.RecommendedAvgVar; } else { smaller = otherInfo.RecommendedAvgVar; larger = userInfo.RecommendedAvgVar; } model.AddConstr(interval * smaller <= larger + meanDeltaDistance, $"interval_u{userNum}_u{otherNum}_1"); model.AddConstr(interval * smaller >= larger - meanDeltaDistance, $"interval_u{userNum}_u{otherNum}_2"); } } model.SetObjective(minimizeValue); model.ModelSense = GRB.MINIMIZE; model.Update(); model.Optimize(); // if didn't a solution, cancel if (model.Status != GRB.Status.OPTIMAL) { Logger.Warn($"Didn't find solution to time conditions. Gurobi status: {model.Status}"); // todo return(false); } foreach (var userInfo in userTickData) { userInfo.RecommendedAvg = (float)userInfo.RecommendedAvgVar.X; } // (1)necessaryTick from a transition // or!: (3)the largest transition ==> this for now because it's easiest // or!: (2)the most convienient point everyone can convieniently hit var necessaryTick = 2 * userTickData.Max(userInfo => userInfo.RecommendedAvg); userTickData.ForEach(userTick => userTick.TimeFrame = necessaryTick); foreach (var userInfo in userTickData) { model.Reset(); minimizeValue = 0; // do three times // check if any of the last hit the necessary constraint // or the one before // or the one before // last tick for (int i = 0; i < userInfo.AvgNumTicksInTimeFrame; i++) { GRBVar tickVar = model.AddVar(0, double.PositiveInfinity, 0, GRB.CONTINUOUS, $"tick_t{i}"); userInfo.RecommendedTickVars.Add(tickVar); } for (int i = 0; i < userInfo.RecommendedTickVars.Count; i++) { var tick = userInfo.RecommendedTickVars[i]; if (i == 0) { GRBVar interval = model.AddVar(0, double.PositiveInfinity, 0, GRB.CONTINUOUS, $"interval_to_last_tick"); // soft constraint! model.AddConstr( tick - userInfo.LastTickSeconds <= interval * (userInfo.RecommendedAvg + userInfo.StdDelta * stdOffsetFactor), $"interval_to_last_tick_uconstraint"); model.AddConstr( tick - userInfo.LastTickSeconds >= interval * (userInfo.RecommendedAvg - userInfo.StdDelta * stdOffsetFactor), $"interval_to_last_tick_lconstraint"); } else if (i < userInfo.AvgNumTicksInTimeFrame - 1) { var nextTick = userInfo.RecommendedTickVars[i + 1]; model.AddConstr( nextTick - tick <= userInfo.RecommendedAvg + userInfo.StdDelta * stdOffsetFactor, $"delta{i}_uconstraint"); model.AddConstr( nextTick - tick >= userInfo.RecommendedAvg - userInfo.StdDelta * stdOffsetFactor, $"delta{i}_lconstraint"); } } // delta distance minimization minimizeValue = MinimizeDeltaDistance(model, minimizeValue, userInfo.RecommendedTickVars[userInfo.AvgNumTicksInTimeFrame - 1], necessaryTick, "lastTickToNecessary"); if (userInfo.AvgNumTicksInTimeFrame > 1) { minimizeValue = MinimizeDeltaDistance(model, minimizeValue, userInfo.RecommendedTickVars[userInfo.AvgNumTicksInTimeFrame - 2], necessaryTick, "preLastTickToNecessary"); } if (userInfo.AvgNumTicksInTimeFrame > 2) { minimizeValue = MinimizeDeltaDistance(model, minimizeValue, userInfo.RecommendedTickVars[userInfo.AvgNumTicksInTimeFrame - 3], necessaryTick, "prePreLastTickToNecessary"); } model.SetObjective(minimizeValue); model.ModelSense = GRB.MINIMIZE; model.Update(); model.Optimize(); if (model.Status != GRB.Status.OPTIMAL) { Logger.Warn($"Didn't find solution for user. Gurobi status: {model.Status}"); return(false); } userInfo.RecommendedTicks = userInfo.RecommendedTickVars.Select(var => (float)var.X).ToList(); } LastNecessaryTick = necessaryTick; _lastCalculatedTickData = userTickData; return(true); }