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."); } }
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; }
private IList <Summary> GetSummaries(FileInput input, RoutingIndexManager manager, RoutingModel routing, Assignment solution) { int vehiclesAmount = input.Vehicles.Count(); IDictionary <int, string> vehiclesNames = input.Vehicles.ToDictionary(k => k.Id - 1, v => v.Name); List <Summary> summaries = new List <Summary>(); RoutingDimension capacityDimension = routing.GetDimensionOrDie("Capacity"); RoutingDimension timeDimension = routing.GetMutableDimension("Time"); for (int vehicleIndex = 0; vehicleIndex < vehiclesAmount; ++vehicleIndex) { long load = 0; long routeDistance = 0; long routeIndex = routing.Start(vehicleIndex); int numberOfVisits = 0; while (routing.IsEnd(routeIndex) == false) { long previousVehicleIndex = routeIndex; load += solution.Value(capacityDimension.CumulVar(routeIndex)); routeDistance += routing.GetArcCostForVehicle(previousVehicleIndex, routeIndex, 0); ++numberOfVisits; routeIndex = solution.Value(routing.NextVar(routeIndex)); } load += solution.Value(capacityDimension.CumulVar(routeIndex)); long vehicleSpentTime = solution.Min(timeDimension.CumulVar(routeIndex)); summaries.Add(new Summary { VehicleName = vehiclesNames[vehicleIndex], Load = (int)load, Distance = (int)routeDistance, Time = (int)vehicleSpentTime, NumberOfVisits = numberOfVisits }); } return(summaries); }
private IList <Totals> GetTotals(FileInput input, RoutingIndexManager manager, RoutingModel routing, Assignment solution) { int vehiclesAmount = input.Vehicles.Count(); List <Totals> totals = new List <Totals>(); RoutingDimension capacityDimension = routing.GetDimensionOrDie("Capacity"); RoutingDimension timeDimension = routing.GetMutableDimension("Time"); long totalLoad = 0; long totalTime = 0; long totalDistance = 0; for (int vehicleIndex = 0; vehicleIndex < vehiclesAmount; ++vehicleIndex) { long load = 0; long routeDistance = 0; long routeIndex = routing.Start(vehicleIndex); while (routing.IsEnd(routeIndex) == false) { long previousRouteIndex = routeIndex; load += solution.Value(capacityDimension.CumulVar(routeIndex)); routeDistance += routing.GetArcCostForVehicle(previousRouteIndex, routeIndex, 0); routeIndex = solution.Value(routing.NextVar(routeIndex)); } load += solution.Value(capacityDimension.CumulVar(routeIndex)); totalLoad += load; totalTime += solution.Min(timeDimension.CumulVar(routeIndex)); totalDistance += routeDistance; } totals.Add(new Totals { Load = (int)totalLoad, Distance = (int)totalDistance, Time = (int)totalTime }); return(totals); }
/// <summary> /// Print the solution. /// </summary> static string PrintSolution(RoutingModel routing, RoutingIndexManager manager, Assignment solution) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("Objective: {0} miles\r\n", solution.ObjectiveValue()); // Inspect solution. sb.AppendFormat("Route:"); long routeDistance = 0; var index = routing.Start(0); while (routing.IsEnd(index) == false) { sb.AppendFormat("{0} -> ", manager.IndexToNode((int)index)); var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } sb.AppendFormat("{0}\r\n", manager.IndexToNode((int)index)); sb.AppendFormat("Route distance: {0}miles\r\n", routeDistance); return(sb.ToString()); }
private IList <Itineraries> GetItineraries(FileInput input, RoutingIndexManager manager, RoutingModel routing, Assignment solution) { int vehiclesAmount = input.Vehicles.Count(); DateTime minDate = input.Locations.Select(l => l.From).Min(); IDictionary <int, string> vehiclesNames = input.Vehicles.ToDictionary(k => k.Id - 1, v => v.Name); List <Itineraries> itineraries = new List <Itineraries>(); RoutingDimension capacityDimension = routing.GetDimensionOrDie("Capacity"); RoutingDimension timeDimension = routing.GetMutableDimension("Time"); for (int vehicleIndex = 0; vehicleIndex < vehiclesAmount; ++vehicleIndex) { long load = 0; long routeIndex = routing.Start(vehicleIndex); while (routing.IsEnd(routeIndex) == false) { long previousRouteIndex = routeIndex; load += solution.Value(capacityDimension.CumulVar(routeIndex)); long distance = routing.GetArcCostForVehicle(previousRouteIndex, routeIndex, 0); IntVar timeVar = timeDimension.CumulVar(routeIndex); itineraries.Add(new Itineraries { VehicleName = vehiclesNames[vehicleIndex], Load = (int)load, Distance = (int)distance, From = minDate.AddMinutes(solution.Min(timeVar)), To = minDate.AddMinutes(solution.Max(timeVar)) }); routeIndex = solution.Value(routing.NextVar(routeIndex)); } } return(itineraries); }
/// <summary> /// Print the solution. /// </summary> static void PrintSolution(DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { long totalDistance = 0; for (int i = 0; i < data.VehicleNumber; ++i) { Console.WriteLine("Route for Vehicle {0}:", i); long routeDistance = 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)); routeDistance += routing.GetArcCostForVehicle(previousIndex, index, 0); } Console.WriteLine("{0}", manager.IndexToNode((int)index)); Console.WriteLine("Distance of the route: {0}m", routeDistance); totalDistance += routeDistance; } Console.WriteLine("Total Distance of all routes: {0}m", totalDistance); }
/// <summary> /// Solves the current routing problem. /// </summary> static void Solve() { // Instantiate the data problem. // [START data] const int num_location = 5; const int num_vehicles = 1; const int depot = 0; // [END data] // Create Routing Index Manager // [START index_manager] RoutingIndexManager manager = new RoutingIndexManager(num_location, num_vehicles, depot); // [END index_manager] // Create Routing Model. // [START routing_model] RoutingModel routing = new RoutingModel(manager); // [END routing_model] // Define cost of each arc. // [START arc_cost] routing.SetArcCostEvaluatorOfAllVehicles( routing.RegisterTransitCallback( (long FromIndex, long ToIndex) => { return(1L); } )); // [END arc_cost] // Setting first solution heuristic. // [START parameters] RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathCheapestArc; // [END parameters] // Solve the problem. // [START solve] Assignment solution = routing.SolveWithParameters(searchParameters); // [END solve] // Print solution on console. // [START print_solution] Console.WriteLine("Objective: {0}", solution.ObjectiveValue()); // Inspect solution. long index = routing.Start(0); Console.WriteLine("Route for Vehicle 0:"); long route_distance = 0; while (routing.IsEnd(index) == false) { Console.Write("{0} -> ", manager.IndexToNode((int)index)); long previousIndex = index; index = solution.Value(routing.NextVar(index)); route_distance += routing.GetArcCostForVehicle(previousIndex, index, 0); } Console.WriteLine("{0}", manager.IndexToNode(index)); Console.WriteLine("Distance of the route: {0}m", route_distance); // [END print_solution] }
//IntVar x; //IntVar y;//Reduntant public void SolveVrpProblem(Day day, ConfigParams cfg, VrpProblem vrpProblem, IDataOutput dataOutput, int[] VCMinMax) { this.day = day; this.cfg = cfg; //Google Distance Matrix API (Duration matrix) // Create Routing Index Manager manager = new RoutingIndexManager( day.TimeMatrix.GetLength(0), day.Vehicles.Count, day.Depot); // Create Routing Model. 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(day.TimeMatrix[fromNode, toNode]); } ); // Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // Add Distance constraint. if (day.TimeWindowsActive != true) { routing.AddDimension(transitCallbackIndex, 0, 700000, true, // start cumul to zero "Distance"); RoutingDimension distanceDimension = routing.GetMutableDimension("Distance"); distanceDimension.SetGlobalSpanCostCoefficient(100); } else { routing.AddDimension( transitCallbackIndex, // transit callback 1000, // allow waiting time 600, // vehicle maximum capacities false, // start cumul to zero "Time"); TimeWindowInit(day, routing, manager);//Set Time Window Constraints } if (day.MaxVisitsActive != 0) { int demandCallbackIndex = routing.RegisterUnaryTransitCallback( (long fromIndex) => { // Convert from routing variable Index to demand NodeIndex. var fromNode = manager.IndexToNode(fromIndex); return(day.Demands[fromNode]); } ); routing.AddDimensionWithVehicleCapacity( demandCallbackIndex, 0, // null capacity slack day.VehicleCapacities, // vehicle maximum capacities true, // start cumul to zero "Capacity"); } // Allow to drop nodes. for (int i = 1; i < day.TimeMatrix.GetLength(0); ++i) { routing.AddDisjunction( new long[] { manager.NodeToIndex(i) }, day.Locations.ElementAt(i).Penalty); } // Setting first solution heuristic. RoutingSearchParameters searchParameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); searchParameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.PathMostConstrainedArc; //metaheuristic searchParameters.LocalSearchMetaheuristic = LocalSearchMetaheuristic.Types.Value.GuidedLocalSearch; searchParameters.TimeLimit = new Duration { Seconds = cfg.SolutionDuration }; searchParameters.LogSearch = true; solver = routing.solver(); //TODO //Some location must be on same route. //solver.Add(routing.VehicleVar(manager.NodeToIndex(2)) == routing.VehicleVar(manager.NodeToIndex(5))); //One node takes precedence over the another. //routing.AddPickupAndDelivery(manager.NodeToIndex(2), manager.NodeToIndex(5)); //Constraint variable //x = solver.MakeIntVar(day.Vehicles.Count, day.Vehicles.Count, "x"); //Number of vehicle restriction - old version //solver.Add(x < 7); //Number of vehicle restriction -new version //y = solver.MakeIntVar(routing.Vehicles(), routing.Vehicles(), "y"); //solver.Add(y <= VCMinMax[1]);//Reduntant // Solve the problem. solution = routing.SolveWithParameters(searchParameters); day.LocationDropped = false; // Display dropped nodes. List <int> droppedNodes = new List <int>(); for (int index = 0; index < routing.Size(); ++index) { if (routing.IsStart(index) || routing.IsEnd(index)) { continue; } if (solution.Value(routing.NextVar(index)) == index) { droppedNodes.Add(manager.IndexToNode((int)index)); day.LocationDropped = true; } } day.DroppedLocations.Clear(); Console.WriteLine(day.Locations.ElementAt(0).Name); if (droppedNodes != null) { foreach (var item in droppedNodes) { Location location = LocationDB.Locations.Where(x => x.Position.strPos_ == day.Addresses[item]).ToList().ElementAt(0); if (location != null) { Console.WriteLine(location.Name); day.DroppedLocations.Add(location); } } } List <int> AssignedNodes = new List <int>(); Console.WriteLine(manager.GetNumberOfNodes()); //Inspect Infeasable Nodes for (int i = 0; i < day.Vehicles.Count; i++) { var index = routing.Start(i); int j = 0; while (routing.IsEnd(index) == false) { j++; index = solution.Value(routing.NextVar(index)); } if (j == 1) { day.InfeasibleNodes = true; foreach (var item in day.DroppedLocations) { LocationDB.Locations.Where(x => x.ClientRef == item.ClientRef).ToList().ElementAt(0).Infeasible = true; } if (day.Vehicles.Count - 1 >= 1) { day.SetVehicleNumber(day.Vehicles.Count - 1); day.ResetResults(); vrpProblem.SolveVrpProblem(day, cfg, vrpProblem, dataOutput, VCMinMax); } return; } } // Inspect solution. day.TotalDur = 0; day.MinDur = 100000; for (int i = 0; i < day.Vehicles.Count; i++) { long routeDuration = 0; var index = routing.Start(i); while (routing.IsEnd(index) == false) { var previousIndex = index; index = solution.Value(routing.NextVar(index)); routeDuration += routing.GetArcCostForVehicle(previousIndex, index, 0); } day.TotalDur += routeDuration; day.MaxDur = Math.Max(routeDuration, day.MaxDur); day.MinDur = Math.Min(routeDuration, day.MinDur); } day.AvgDur = day.TotalDur / day.Vehicles.Count; }