public void SimpleLambdaCallback(bool callGC) { // Create Routing Index Manager RoutingIndexManager manager = new RoutingIndexManager( 5 /*locations*/, 1 /*vehicle*/, 0 /*depot*/); // Create Routing Model. RoutingModel routing = new RoutingModel(manager); // Create a distance callback. int transitCallbackIndex = routing.RegisterTransitCallback( (long fromIndex, long toIndex) => { // Convert from routing variable Index to distance matrix NodeIndex. var fromNode = manager.IndexToNode(fromIndex); var toNode = manager.IndexToNode(toIndex); return(Math.Abs(toNode - fromNode)); }); // Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex); if (callGC) { GC.Collect(); } // Setting first solution heuristic. RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; Assignment solution = routing.SolveWithParameters(searchParameters); // 0 --(+1)-> 1 --(+1)-> 2 --(+1)-> 3 --(+1)-> 4 --(+4)-> 0 := +8 Assert.Equal(8, solution.ObjectiveValue()); }
public object Exec(RoutingModel route, ParamContainer helper) { if (route.auth_users.FirstOrDefault(f => f.Trim() == "*") == null) { ISessionProvider sessionProvider = helper.GetKey(CommonConst.CommonValue.PARAM_SESSION_PROVIDER); IHttpContextProxy httpProxy = helper.GetKey(CommonConst.CommonValue.PARAM_HTTPREQUESTPROXY); if (sessionProvider == null || httpProxy == null) { string error = "ActionExecuter.Exec sessionProvider is null or HttpContextProxy is null on ParamContainer"; _logger.Error(error); throw new UnauthorizedAccessException(error); } var authToken = httpProxy.GetHeaders().FirstOrDefault(f => f.Key.ToLower() == ""); var sessionUser = sessionProvider.GetValue <UserModel>(CommonConst.CommonValue.SESSION_USER_KEY); // add auth here. if (sessionUser == null) { throw new UnauthorizedAccessException("No session user found"); } if (!route.auth_users.Where(i => sessionUser.groups.Contains(i)).Any()) { throw new UnauthorizedAccessException("Unauthorized"); } return(Exec(route.ExecultAssembly, route.ExecuteType, route.ExecuteMethod, helper)); } else { return(Exec(route.ExecultAssembly, route.ExecuteType, route.ExecuteMethod, helper)); } }
private void init() { DataReader dr = new SyntheticData(); CellDescription cellData = dr.FetchData(); travellingDistance = cellData.TravellingTimeArm1; //LUDDE: Why is this set to Arm1's Travelling arrivalTime? // number of vehicles we have nbRoutes = 3; // number of visists we have to make nbNodes = 58 + nbRoutes * 2; List <int> initStarts = new List <int>(); List <int> initEnds = new List <int>(); // ENDS AND STARTS NEED TO BE IN THE BEGINNING! for (int i = 0; i < nbRoutes; i++) { initStarts.Add(i); initEnds.Add(i + nbRoutes); } starts = initStarts.ToArray(); ends = initEnds.ToArray(); routing = new RoutingModel(nbNodes, nbRoutes, starts, ends); }
public void TestVectorDimension() { // Create Routing Index Manager RoutingIndexManager manager = new RoutingIndexManager(5 /*locations*/, 1 /*vehicle*/, 0 /*depot*/); // Create Routing Model. RoutingModel routing = new RoutingModel(manager); // Create a distance callback. long[] vector = new long[] { 1, 1, 1, 1, 1 }; IntBoolPair result = routing.AddVectorDimension( vector, /*capacity=*/ 10, /*fix_start_cumul_to_zero=*/ true, "Dimension"); // Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(result.first); // Setting first solution heuristic. RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; Assignment solution = routing.SolveWithParameters(searchParameters); // 0 --(+1)-> 1 --(+1)-> 2 --(+1)-> 3 --(+1)-> 4 --(+1)-> 0 := +5 Assert.Equal(5, solution.ObjectiveValue()); }
static void TimeWindowInit(Day day, RoutingModel routing, RoutingIndexManager manager) { RoutingDimension timeDimension = routing.GetMutableDimension("Time"); timeDimension.SetGlobalSpanCostCoefficient(100); // Add time window constraints for each location except depot. for (int i = 1; i < day.TimeWindows.GetLength(0); i++) { long index = manager.NodeToIndex(i); timeDimension.CumulVar(index).SetRange( day.TimeWindows[i, 0], day.TimeWindows[i, 1]); } // Add time window constraints for each vehicle start node. for (int i = 0; i < day.Vehicles.Count; i++) { long index = routing.Start(i); timeDimension.CumulVar(index).SetRange( day.TimeWindows[0, 0], day.TimeWindows[0, 1]); routing.AddVariableMinimizedByFinalizer( timeDimension.CumulVar(routing.Start(i))); routing.AddVariableMinimizedByFinalizer( timeDimension.CumulVar(routing.End(i))); } }
public void TestTransitMatrix() { // Create Routing Index Manager RoutingIndexManager manager = new RoutingIndexManager(5 /*locations*/, 1 /*vehicle*/, 0 /*depot*/); // Create Routing Model. RoutingModel routing = new RoutingModel(manager); // Create a distance callback. long[][] matrix = new long[][] { new long[] { 1, 1, 1, 1, 1 }, new long[] { 1, 1, 1, 1, 1 }, new long[] { 1, 1, 1, 1, 1 }, new long[] { 1, 1, 1, 1, 1 }, new long[] { 1, 1, 1, 1, 1 }, }; int transitCallbackIndex = routing.RegisterTransitMatrix(matrix); // Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // Setting first solution heuristic. RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; Assignment solution = routing.SolveWithParameters(searchParameters); // 0 --(+1)-> 1 --(+1)-> 2 --(+1)-> 3 --(+1)-> 4 --(+1)-> 0 := +5 Assert.Equal(5, solution.ObjectiveValue()); }
public int PrintStatus(RoutingModel routing) { switch (routing.GetStatus()) { case 0: Console.WriteLine("Problem is not solved yet."); return(0); case 1: Console.WriteLine("Problem is solved"); return(1); case 2: Console.WriteLine("No solution found to the problem."); return(2); case 3: Console.WriteLine("Time limit reached before finding a solution."); return(3); case 4: Console.WriteLine("Model, model parameters, or flags are not valid."); return(4); default: return(-1); } }
private static void Test() { int[,] locations = { { 82, 76 }, { 96, 44 }, { 50, 5 }, { 49, 8 }, { 13, 7 }, { 29, 89 }, { 58, 30 }, { 84, 39 }, { 14, 24 }, { 12, 39 }, { 3, 82 }, { 5, 10 }, { 98, 52 }, { 84, 25 }, { 61, 59 }, { 1, 65 }, { 88, 51 }, { 91, 2 }, { 19, 32 }, { 93, 3 }, { 50, 93 }, { 98, 14 }, { 5, 42 }, { 42, 9 }, { 61, 62 }, { 9, 97 }, { 80, 55 }, { 57, 69 }, { 23, 15 }, { 20, 70 }, { 85, 60 }, { 98, 5 } }; int[] demands = { 0, 19, 21, 6, 19, 7, 12, 16, 6, 16, 8, 14, 21, 16, 3, 22, 18, 19, 1, 24, 8, 12, 4, 8, 24, 24, 2, 20, 15, 2, 14, 9 }; int num_locations = locations.Length; int depot = 0; // The depot is the start and end point of each route. int num_vehicles = 5; // Create routing model if (locations.Length > 0) { RoutingModel routing = new RoutingModel(num_locations, num_vehicles, depot); var search_parameters = RoutingModel.DefaultSearchParameters(); // Setting first solution heuristic: the // method for finding a first solution to the problem. search_parameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; routing.SetArcCostEvaluatorOfAllVehicles(new DistanceLocationsCallback(locations)); } }
private static void AddPickupAndDropoff(FeatureCollection run, RoutingModel routing) { const int pickup = 0, dropoff = 1; var groups = run .Features .Where(x => x.Properties.ContainsKey("orderId")) .GroupBy(x => x.Properties["orderId"]); foreach (var group in groups) { var pickupStop = group.Single(x => Convert.ToInt32(x.Properties["stopKind"]) == pickup); var dropoffStop = group.Single(x => Convert.ToInt32(x.Properties["stopKind"]) == dropoff); int pickupNode = run.Features.IndexOf(pickupStop), dropoffNode = run.Features.IndexOf(dropoffStop); // Set route precedence routing.AddPickupAndDelivery(pickupNode, dropoffNode); // Link same vehicle to both nodes var constraint = routing .solver() .MakeEquality( routing.VehicleVar(routing.NodeToIndex(pickupNode)), routing.VehicleVar(routing.NodeToIndex(dropoffNode))); routing.solver().Add(constraint); } }
public static ParamContainer CreateParamContainer(RoutingModel route, IHttpContextProxy httpProxy, ILogger loggerController, IActionExecuter actionExecuter) { var paramContainer = CreateParamContainer(loggerController, actionExecuter); ILogReader logReader = Logger.GetLogReader(); IDBService dbService = paramContainer.GetKey(CommonConst.CommonValue.PARAM_DBPROXY); IViewEngine viewEngine = paramContainer.GetKey(CommonConst.CommonValue.PARAM_VIEW_ENGINE); ResponseBuilder responseBuilder = new ResponseBuilder(loggerController, logReader, httpProxy); ISessionProvider sessionProvider = new SessionProvider(httpProxy, dbService, loggerController); IwwwrootContentHandler ContentHandler = new WwwrootContentHandler(httpProxy, dbService, viewEngine, actionExecuter, loggerController); (dbService as MongoDBService).User = () => { string result = string.Empty; var user = sessionProvider.GetValue <UserModel>(CommonConst.CommonValue.SESSION_USER_KEY); if (user != null) { result = string.Format("{0}::{1}", user.id, user.name); } return(result); }; (loggerController as Logger).DBProxy = dbService; paramContainer.AddKey(CommonConst.CommonValue.PARAM_ROUTE, () => { return(route); }); paramContainer.AddKey(CommonConst.CommonValue.PARAM_HTTPREQUESTPROXY, () => { return(httpProxy); }); paramContainer.AddKey(CommonConst.CommonValue.PARAM_RESPONBUILDER, () => { return(responseBuilder); }); paramContainer.AddKey(CommonConst.CommonValue.PARAM_SESSION_PROVIDER, () => { return(sessionProvider); }); paramContainer.AddKey(CommonConst.CommonValue.PARAM_CONTENT_HANDLER, () => { return(ContentHandler); }); return(paramContainer); }
public static int[] Run(long[] DistanceMatrix, int num, int VehicleNumber, int Depot, RoutingSearchParameters searchParameters) { // Instantiate the data problem. // Create Routing Index Manager RoutingIndexManager manager = new RoutingIndexManager( num, VehicleNumber, Depot); // Create Routing Model. RoutingModel routing = new RoutingModel(manager); int transitCallbackIndex = routing.RegisterTransitCallback( (long fromIndex, long toIndex) => { // Convert from routing variable Index to distance matrix NodeIndex. var fromNode = manager.IndexToNode(fromIndex); var toNode = manager.IndexToNode(toIndex); return(DistanceMatrix[fromNode * num + toNode]); } ); // Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // Solve the problem. Assignment solution = routing.SolveWithParameters(searchParameters); // Print solution on console. return(GetOrder(routing, manager, solution)); }
static void Solve(int size, int forbidden, int seed) { RoutingIndexManager manager = new RoutingIndexManager(size, 1, 0); RoutingModel routing = new RoutingModel(manager); // Setting the cost function. // Put a permanent callback to the distance accessor here. The callback // has the following signature: ResultCallback2<int64_t, int64_t, int64_t>. // The two arguments are the from and to node inidices. RandomManhattan distances = new RandomManhattan(manager, size, seed); routing.SetArcCostEvaluatorOfAllVehicles(routing.RegisterTransitCallback(distances.Call)); // Forbid node connections (randomly). Random randomizer = new Random(); long forbidden_connections = 0; while (forbidden_connections < forbidden) { long from = randomizer.Next(size - 1); long to = randomizer.Next(size - 1) + 1; if (routing.NextVar(from).Contains(to)) { Console.WriteLine("Forbidding connection {0} -> {1}", from, to); routing.NextVar(from).RemoveValue(to); ++forbidden_connections; } } // Add dummy dimension to test API. routing.AddDimension(routing.RegisterUnaryTransitCallback((long index) => { return(1); }), size + 1, size + 1, true, "dummy"); // Solve, returns a solution if any (owned by RoutingModel). RoutingSearchParameters search_parameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); // Setting first solution heuristic (cheapest addition). search_parameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; Assignment solution = routing.SolveWithParameters(search_parameters); Console.WriteLine("Status = {0}", routing.GetStatus()); if (solution != null) { // Solution cost. Console.WriteLine("Cost = {0}", solution.ObjectiveValue()); // Inspect solution. // Only one route here; otherwise iterate from 0 to routing.vehicles() - 1 int route_number = 0; for (long node = routing.Start(route_number); !routing.IsEnd(node); node = solution.Value(routing.NextVar(node))) { Console.Write("{0} -> ", node); } Console.WriteLine("0"); } }
/// <summary> /// 并发分支信息填写验证 /// </summary> /// <param name="model">要验证的信息</param> /// <returns>验证结果</returns> private string ParallelPropertyValidate(RoutingModel model) { if (string.IsNullOrEmpty(model.Group)) { return(model.Name + "必须有分组信息"); } return(string.Empty); }
public void PrintSolution(Day day, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { PrintToConsole(day, routing, manager, solution); //ShowOnMap(day, routing, manager, solution); }
public void AddConstraints(RoutingData data, RoutingModel model, IntVar cumulTime, RoutingDimension timeDim, int visit) { // forbid visit in unavailable var unavailableStarts = data.Unavailable[visit].Select(u => u.startFrom).ToList(); var unavailableEnds = data.Unavailable[visit].Select(u => u.startEnd).ToList(); var constraint = model.solver().MakeNotMemberCt(cumulTime, new CpIntVector(unavailableStarts), new CpIntVector(unavailableEnds)); model.solver().Add(constraint); }
static void Solve(int size, int forbidden, int seed) { RoutingModel routing = new RoutingModel(size, 1); // Setting first solution heuristic (cheapest addition). routing.SetFirstSolutionStrategy(RoutingModel.ROUTING_PATH_CHEAPEST_ARC); // Setting the cost function. // Put a permanent callback to the distance accessor here. The callback // has the following signature: ResultCallback2<int64, int64, int64>. // The two arguments are the from and to node inidices. RandomManhattan distances = new RandomManhattan(size, seed); routing.SetCost(distances); // Forbid node connections (randomly). Random randomizer = new Random(); long forbidden_connections = 0; while (forbidden_connections < forbidden) { long from = randomizer.Next(size - 1); long to = randomizer.Next(size - 1) + 1; if (routing.NextVar(from).Contains(to)) { Console.WriteLine("Forbidding connection {0} -> {1}", from, to); routing.NextVar(from).RemoveValue(to); ++forbidden_connections; } } // Add dummy dimension to test API. routing.AddDimension(new ConstantCallback(), size + 1, size + 1, true, "dummy"); // Solve, returns a solution if any (owned by RoutingModel). Assignment solution = routing.Solve(); if (solution != null) { // Solution cost. Console.WriteLine("Cost = {0}", solution.ObjectiveValue()); // Inspect solution. // Only one route here; otherwise iterate from 0 to routing.vehicles() - 1 int route_number = 0; for (long node = routing.Start(route_number); !routing.IsEnd(node); node = solution.Value(routing.NextVar(node))) { Console.Write("{0} -> ", node); } Console.WriteLine("0"); } }
private static void ExecEvent(IActionExecuter actionExecuter, RoutingModel route, ParamContainer paramContainer, Models.ExecutionEventType eventType) { IDBService dbProxy = paramContainer.GetKey(CommonConst.CommonValue.PARAM_DBPROXY); ILogger logger = paramContainer.GetKey(CommonConst.CommonValue.PARAM_LOGGER); foreach (var eventSubscriber in EventSubscription.GetInstance(dbProxy, logger).GetSubscriptions(route.GetEventName(), eventType)) { actionExecuter.Exec(eventSubscriber.ExecultAssembly, eventSubscriber.ExecuteType, eventSubscriber.ExecuteMethod, paramContainer); } }
public override Utils.ResultInfo RoutingValidate(RoutingModel model) { if (model.Type == ActivityTypeEnum.Process_Parallel) { var msg = ParallelPropertyValidate(model); if (string.IsNullOrEmpty(msg)) { if (ParalleStack.Any(p => p.Group == model.Group)) { var existParallelStart = ParalleStack.First(p => p.Group == model.Group); Info.AppendError(string.Format("并发开始{0}和并发开始{1}分组{2}冲突", existParallelStart.Name, model.Name, model.Group)); return(Info); } ParalleStack.Push(model); } else { Info.AppendError(msg); } } else if (model.Type == ActivityTypeEnum.Parallel) { var msg = ParallelPropertyValidate(model); if (string.IsNullOrEmpty(msg)) { if (ParalleStack.Any()) { var lastModel = ParalleStack.Last(); if (lastModel.Type == ActivityTypeEnum.Process_Parallel && lastModel.Group == model.Group) { if (lastModel.DefaultCount != model.DefaultCount) { ParallelSetMsg(model.Name, string.Format("并发开始{0}和并发结束{1}数量分支数量必须匹配", model.Name, lastModel.Name)); return(Info); } lastModel.Pop(); if (lastModel.ParallelTrigger) { ParalleStack.Pop(); } } return(Info); } ParallelSetMsg(model.Name, string.Format("并发结束{0}必须有对应的并发开始", model.Name)); } else { Info.AppendError(msg); } } return(base.RoutingValidate(model)); }
/// <summary> /// Builds the OptimizationResult. /// Note: OptimizationResult.TimeElapsed will not be set. /// </summary> /// <param name="data"></param> /// <param name="model"></param> /// <param name="solution"></param> /// <returns></returns> private static OptimizationResult CreateResult(RoutingData data, RoutingModel model, Assignment solution) { var ret = new OptimizationResult { OptimizationInput = data.Input, ResultState = GetResultState(model), Routes = GetRoutes(data, model, solution), }; return(ret); }
public void PrintToConsole( Day day, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { Console.WriteLine("Day " + day.DayNum); if (day.Locations.Count != 0) { // Display dropped nodes. string droppedNodes = "Dropped nodes:"; for (int index = 0; index < routing.Size(); ++index) { if (routing.IsStart(index) || routing.IsEnd(index)) { continue; } if (solution.Value(routing.NextVar(index)) == index) { droppedNodes += " " + manager.IndexToNode(index); } } Console.WriteLine("{0}", droppedNodes); // Inspect solution. for (int i = 0; i < day.Vehicles.Count; i++) { Console.WriteLine("Route for Vehicle {0}:", i); long routeDuration = 0; var index = routing.Start(i); while (routing.IsEnd(index) == false) { Console.Write("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDuration += routing.GetArcCostForVehicle(previousIndex, index, 0); } Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Duration of the route: {0}mins", routeDuration); } Console.WriteLine("Minimum duration of the routes: {0}mins", day.MinDur); Console.WriteLine("Maximum duration of the routes: {0}mins", day.MaxDur); } else { Console.WriteLine("This day is holiday."); } }
/// <summary> /// Print the solution. /// </summary> static void VRP_LongestSingleRoute() { Console.WriteLine("VRP_LongestSingleRoute!"); // Instantiate the data problem. ORDataModel data = new ORDataModel(); // public RoutingIndexManager(int num_nodes, int num_vehicles, int depot); //public RoutingIndexManager(int num_nodes, int num_vehicles, int[] starts, int[] ends); // Create Routing Index Manager RoutingIndexManager manager = new RoutingIndexManager( data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); // Create Routing Model. RoutingModel routing = new RoutingModel(manager); // Create and register a transit callback. int transitCallbackIndex = routing.RegisterTransitCallback( (long fromIndex, long toIndex) => { // Convert from routing variable Index to distance matrix NodeIndex. var fromNode = manager.IndexToNode(fromIndex); var toNode = manager.IndexToNode(toIndex); return(data.DistanceMatrix[fromNode, toNode]); } ); // Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // Add Distance constraint. routing.AddDimension(transitCallbackIndex, 0, 3000, true, // start cumul to zero "Distance"); RoutingDimension distanceDimension = routing.GetMutableDimension("Distance"); distanceDimension.SetGlobalSpanCostCoefficient(100); // Setting first solution heuristic. RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // Solve the problem. Assignment solution = routing.SolveWithParameters(searchParameters); // Print solution on console. PrintSolutionPathCheapest(data, routing, manager, solution); }
static int[] GetOrder(RoutingModel routing, RoutingIndexManager manager, Assignment solution) { List <int> order = new List <int>(); var index = routing.Start(0); while (routing.IsEnd(index) == false) { order.Add(manager.IndexToNode((int)index)); index = solution.Value(routing.NextVar(index)); } return(order.ToArray()); }
/// <summary> /// Returns the Routes from the solution. /// </summary> /// <param name="data"></param> /// <param name="model"></param> /// <param name="solution"></param> /// <returns></returns> private static Route[] GetRoutes(RoutingData data, RoutingModel model, Assignment solution) { if (solution == null) { return(new Route[0]); } // Routes var routes = new List <Route>(); for (int santa = 0; santa < data.NumberOfSantas; ++santa) { long visit = model.Start(santa); if (model.IsEnd(solution.Value(model.NextVar(visit)))) { // empty } else { var waypoints = new List <Waypoint>(); void AddWaypoint(long v) { var startTime = solution.Value(model.CumulVar(v, DimensionTime)); var visitId = (v >= data.Visits.Length || v < 0) ? Constants.VisitIdHome : data.Visits[v].Id; waypoints.Add(new Waypoint { StartTime = (int)startTime, VisitId = visitId, }); } for (; !model.IsEnd(visit); visit = solution.Value(model.NextVar(visit))) { AddWaypoint(visit); } // add end { AddWaypoint(visit); } routes.Add(new Route { SantaId = data.SantaIds[santa], Waypoints = waypoints.ToArray(), }); } } return(routes.ToArray()); }
private void Distancia() { long routeDistance = 0; RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; DataModel data = new DataModel(Distancias, 1, 0); RoutingIndexManager manager = new RoutingIndexManager( data.DistanceMatrix.GetLength(0), data.VehicleNumber, data.Depot); RoutingModel routing = new RoutingModel(manager); int transitCallbackIndex = routing.RegisterTransitCallback( (long fromIndex, long toIndex) => { // Convert from routing variable Index to distance matrix NodeIndex. var fromNode = manager.IndexToNode(fromIndex); var toNode = manager.IndexToNode(toIndex); return(data.DistanceMatrix[fromNode, toNode]); }); routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex); Assignment solution = routing.SolveWithParameters(searchParameters); var index = routing.Start(0); int indice = 1; string CadenaR = ""; string c = ""; while (routing.IsEnd(index) == false) { //Recorrido[indice] = manager.IndexToNode((int)index); c = manager.IndexToNode((int)index).ToString(); CadenaR = CadenaR + " - " + c; var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); indice++; } //Recorrido[indice] = manager.IndexToNode((int)index); c = manager.IndexToNode((int)index).ToString(); CadenaR = CadenaR + " - " + c; Km = routeDistance; CadenaRecorrido = CadenaR; }
public void AddConstraints(RoutingData data, RoutingModel model, IntVar cumulTime, RoutingDimension timeDim, int visit) { var desired = InternalSolver.GetDesired(data, visit); if (desired.HasValue) { // add soft time window for desired cumulTime.SetRange(desired.Value.from, desired.Value.to); } else { // forbid visit in unavailable new UnavailableOnlyStrategy().AddConstraints(data, model, cumulTime, timeDim, visit); } }
public void AddConstraints(RoutingData data, RoutingModel model, IntVar cumulTime, RoutingDimension timeDim, int visit) { // forbid visit in unavailable new UnavailableOnlyStrategy().AddConstraints(data, model, cumulTime, timeDim, visit); // add soft time window for desired var desired = InternalSolver.GetDesired(data, visit); if (desired.HasValue) { var cost = InternalSolver.GetDesiredCoefficient(data, visit); timeDim.SetCumulVarSoftUpperBound(visit, desired.Value.to, cost); timeDim.SetCumulVarSoftLowerBound(visit, desired.Value.from, cost); } }
private static NodeEvaluator2 SetCost(FeatureCollection collection, RoutingModel routing) { var coordinates = collection .Features .Select(x => x.Geometry) .Cast <Point>() .Select(x => x.Coordinates) .Cast <GeographicPosition>() .ToArray(); var nodeEvaluator = new HaversineDistanceEvaluator(coordinates); routing.SetCost(nodeEvaluator); return(nodeEvaluator); }
public override void Solve() { var pparser = new Pparser(FpatIn); int n, l; pparser.Fetch(out n, out l); var rgnode = pparser.FetchN <string>(n); rgnode.Insert(0, "X"); var model = new RoutingModel(n, 1); model.SetFirstSolutionStrategy(RoutingModel.ROUTING_GLOBAL_CHEAPEST_ARC); //model.SetMetaheuristic(RoutingModel.ROUTING_TABU_SEARCH); model.SetCost(new NodeEval(rgnode.ToArray())); model.SetDepot(0); for (int i = 0; i < n; i++) { var varI = model.NextVar(i); for (int j = 0; j < n; j++) { if (i == j) { continue; } if (!NodeEval.FMatch(rgnode[i], rgnode[j])) { varI.RemoveValue(j); } } } Console.WriteLine("solving"); Assignment solution = model.Solve(); model.UpdateTimeLimit(1000 * 60 * 3); if (solution != null) { // Solution cost. Console.WriteLine("Cost = {0}", solution.ObjectiveValue()); for (var inode = (int)model.Start(0); !model.IsEnd(inode); inode = (int)solution.Value(model.NextVar(inode))) { Console.WriteLine(rgnode[inode]); } Console.WriteLine("0"); } }
/// <summary> /// Returns the ResultState matching the given routingModel /// </summary> /// <param name="routingModel"></param> /// <returns></returns> private static ResultState GetResultState(RoutingModel routingModel) { // timeout if (routingModel.Status() == RoutingModel.ROUTING_FAIL_TIMEOUT) { return(ResultState.TimeLimitReached); } // success if (routingModel.Status() == RoutingModel.ROUTING_FAIL_TIMEOUT) { return(ResultState.Finished); } // error, may be one of those: // ROUTING_NOT_SOLVED // ROUTING_FAIL // ROUTING_INVALID return(ResultState.Error); }
private List <Destination> ExtractWaybillsFromSolution(Assignment solution, RoutingModel model, List <Destination> destinations) { var result = new List <Destination>(); var index = model.Start(0); while (!model.IsEnd(index)) { if (index < destinations.Count) { var currentDestination = destinations[(int)index]; result.Add(currentDestination); } index = solution.Value(model.NextVar(index)); } return(result); }