public Manhattan(RoutingIndexManager manager, Position[] locations, int coefficient) { this.locations_ = locations; this.coefficient_ = coefficient; this.manager_ = manager; }
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()); }
private void AddTimeWindowConstrains(WorkData data, RoutingIndexManager manager, RoutingModel routing) { // Create and register a transit callback int transitCallbackIndex = routing.RegisterTransitCallback( (long fromIndex, long toIndex) => { int fromNode = manager.IndexToNode(fromIndex); int toNode = manager.IndexToNode(toIndex); return(data.DurationMatrix[fromNode, toNode] + data.ServiceTimes[fromNode]); }); routing.AddDimension(transitCallbackIndex, 120, MAX_VEHICLE_ROUTING_TIME, false, "Time"); // Add time window constraints for each location except depot RoutingDimension timeDimension = routing.GetDimensionOrDie("Time"); for (int i = 1; i < data.TimeWindows.GetLength(0); ++i) { long index = manager.NodeToIndex(i); timeDimension.CumulVar(index).SetRange(data.TimeWindows[i][0], data.TimeWindows[i][1]); } // Add time window constraints for each vehicle start node for (int i = 0; i < data.VehiclesAmount; ++i) { long index = routing.Start(i); timeDimension.CumulVar(index).SetRange(data.TimeWindows[0][0], data.TimeWindows[0][1]); routing.AddVariableMinimizedByFinalizer(timeDimension.CumulVar(routing.Start(i))); routing.AddVariableMinimizedByFinalizer(timeDimension.CumulVar(routing.End(i))); } }
public Demand( RoutingIndexManager manager, int[] order_demands) { this.manager_ = manager; this.order_demands_ = order_demands; }
private void AddCapacityConstrains(WorkData data, RoutingIndexManager manager, RoutingModel routing) { // Create and register a transit callback int transitCallbackIndex = routing.RegisterTransitCallback( (long fromIndex, long toIndex) => { // Convert from routing variable Index to distance matrix NodeIndex int fromNode = manager.IndexToNode(fromIndex); int toNode = manager.IndexToNode(toIndex); return(data.DistanceMatrix[fromNode, toNode]); }); // Define cost of each arc. routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // Add Capacity constraint int demandCallbackIndex = routing.RegisterUnaryTransitCallback( (long fromIndex) => { int fromNode = manager.IndexToNode(fromIndex); return(data.Demands[fromNode]); }); // AddDimensionWithVehicleCapacity method, which takes a vector of capacities routing.AddDimensionWithVehicleCapacity(demandCallbackIndex, 0, data.VehicleCapacities, true, "Capacity"); }
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 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"); } }
public void PrintSolution(Day day, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { PrintToConsole(day, routing, manager, solution); //ShowOnMap(day, routing, manager, solution); }
private void AddPenaltiesAndDroppingVisits(WorkData data, RoutingIndexManager manager, RoutingModel routing) { // Allow to drop nodes. for (int i = 1; i < data.DistanceMatrix.GetLength(0); ++i) { routing.AddDisjunction(new long[] { manager.NodeToIndex(i) }, MAX_VEHICLE_PENALTY); } }
public FileOutput ConvertToFileOutput(FileInput input, RoutingIndexManager manager, RoutingModel routing, Assignment solution) { return(new FileOutput() { DroppedLocation = GetDroppedLocations(input, manager, routing, solution), Itineraries = GetItineraries(input, manager, routing, solution), Summaries = GetSummaries(input, manager, routing, solution), Totals = GetTotals(input, manager, routing, solution) }); }
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()); }
public RandomManhattan(RoutingIndexManager manager, int size, int seed) { this.xs_ = new int[size]; this.ys_ = new int[size]; this.manager_ = manager; Random generator = new Random(seed); for (int i = 0; i < size; ++i) { xs_[i] = generator.Next(1000); ys_[i] = generator.Next(1000); } }
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); }
public FileOutput Solve(FileInput input, RoutingSearchParameters searchParameters) { WorkData data = converter.ToWorkData(input); RoutingIndexManager manager = new RoutingIndexManager(data.DistanceMatrix.GetLength(0), data.VehiclesAmount, data.Starts, data.Ends); RoutingModel routing = new RoutingModel(manager); AddCapacityConstrains(data, manager, routing); AddTimeWindowConstrains(data, manager, routing); AddPenaltiesAndDroppingVisits(data, manager, routing); Assignment solution = routing.SolveWithParameters(searchParameters); if (solution == null) { return(null); } return(converter.ConvertToFileOutput(input, manager, routing, solution)); }
public RoutingSolver(DataModel data) { if (this.Data.GetTimeWindows().GetLength(0) != this.Data.GetTimeMatrix().GetLength(0)) { throw new System.ComponentModel.DataAnnotations.ValidationException("Travel Time Matrix and Time Windows Matrix must have the same length."); } this.Data = data; // Create Routing Index Manager // [START index_manager] this.manager = new RoutingIndexManager( this.Data.GetTimeMatrix().GetLength(0), // Total Number of Sites this.Data.GetVehicleNumber(), this.Data.GetDepot()); // [END index_manager] this.timeCallback = new TimeCallback(this.Data, manager); }
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> public static int[] Solve() { int[] result = new int[200]; int cnt = 0; // Create Routing Index Manager RoutingIndexManager manager = new RoutingIndexManager(Ranks, 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((long)distMat[fromNode, toNode]); } ); routing.SetArcCostEvaluatorOfAllVehicles(transitCallbackIndex); // 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); // Inspect solution. var index = routing.Start(0); while (routing.IsEnd(index) == false) { result[cnt++] = Convert.ToInt32(index); var previousIndex = index; index = solution.Value(routing.NextVar(index)); } return(result); }
/// <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); }
void ShowOnMap(Day day, RoutingModel routing, RoutingIndexManager manager, Assignment solution) { List <List <int> > routes = new List <List <int> >(); for (int i = 0; i < day.Vehicles.Count; ++i) { var index = routing.Start(i); List <int> route = new List <int>(); while (routing.IsEnd(index) == false) { route.Add(manager.IndexToNode((int)index)); index = solution.Value(routing.NextVar(index)); } route.Add(manager.IndexToNode((int)index)); routes.Add(route); } for (int i = 0; i < routes.Count; i++) { string url = "https://www.google.com.tr/maps/dir/"; foreach (var item in routes[i]) { url += day.Addresses[item].Replace('+', ',') + "/"; } //url += data.addresses[data.Depot]; Process process = new Process(); process.StartInfo.UseShellExecute = true; process.StartInfo.FileName = "chrome"; process.StartInfo.Arguments = url; process.Start(); } }
/// <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); }
private IList <Dropped> GetDroppedLocations(FileInput input, RoutingIndexManager manager, RoutingModel routing, Assignment solution) { IDictionary <int, string> locationsNames = input.Locations.ToDictionary(k => k.Id - 1, v => v.Name); List <Dropped> droppedLocations = new List <Dropped>(); for (int index = 0; index < routing.Size(); ++index) { if (routing.IsStart(index) || routing.IsEnd(index)) { continue; } if (solution.Value(routing.NextVar(index)) == index) { int node = manager.IndexToNode(index); droppedLocations.Add(new Dropped { LocationName = locationsNames[node] }); } } return(droppedLocations); }
public static void Main(String[] args) { // Instantiate the data problem. DataModel data = new DataModel(); // 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); // Define Transportation Requests. Solver solver = routing.solver(); for (int i = 0; i < data.PickupsDeliveries.GetLength(0); i++) { long pickupIndex = manager.NodeToIndex(data.PickupsDeliveries[i][0]); long deliveryIndex = manager.NodeToIndex(data.PickupsDeliveries[i][1]); routing.AddPickupAndDelivery(pickupIndex, deliveryIndex); solver.Add(solver.MakeEquality( routing.VehicleVar(pickupIndex), routing.VehicleVar(deliveryIndex))); solver.Add(solver.MakeLessOrEqual( distanceDimension.CumulVar(pickupIndex), distanceDimension.CumulVar(deliveryIndex))); } // 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. PrintSolution(data, routing, manager, solution); }
/// <summary> /// Solves the current routing problem. /// </summary> private void Solve(int number_of_orders, int number_of_vehicles) { Console.WriteLine("Creating model with " + number_of_orders + " orders and " + number_of_vehicles + " vehicles."); // Finalizing model int number_of_locations = locations_.Length; RoutingIndexManager manager = new RoutingIndexManager(number_of_locations, number_of_vehicles, vehicle_starts_, vehicle_ends_); RoutingModel model = new RoutingModel(manager); // Setting up dimensions const int big_number = 100000; Manhattan manhattan_callback = new Manhattan(manager, locations_, 1); model.AddDimension(model.RegisterTransitCallback(manhattan_callback.Call), big_number, big_number, false, "time"); RoutingDimension time_dimension = model.GetDimensionOrDie("time"); Demand demand_callback = new Demand(manager, order_demands_); model.AddDimension(model.RegisterUnaryTransitCallback(demand_callback.Call), 0, vehicle_capacity_, true, "capacity"); RoutingDimension capacity_dimension = model.GetDimensionOrDie("capacity"); // Setting up vehicles Manhattan[] cost_callbacks = new Manhattan[number_of_vehicles]; for (int vehicle = 0; vehicle < number_of_vehicles; ++vehicle) { int cost_coefficient = vehicle_cost_coefficients_[vehicle]; Manhattan manhattan_cost_callback = new Manhattan(manager, locations_, cost_coefficient); cost_callbacks[vehicle] = manhattan_cost_callback; int manhattan_cost_index = model.RegisterTransitCallback(manhattan_cost_callback.Call); model.SetArcCostEvaluatorOfVehicle(manhattan_cost_index, vehicle); time_dimension.CumulVar(model.End(vehicle)).SetMax(vehicle_end_time_[vehicle]); } // Setting up orders for (int order = 0; order < number_of_orders; ++order) { time_dimension.CumulVar(order).SetRange(order_time_windows_[order].start_, order_time_windows_[order].end_); long[] orders = { manager.NodeToIndex(order) }; model.AddDisjunction(orders, order_penalties_[order]); } // Solving RoutingSearchParameters search_parameters = operations_research_constraint_solver.DefaultRoutingSearchParameters(); search_parameters.FirstSolutionStrategy = FirstSolutionStrategy.Types.Value.AllUnperformed; Console.WriteLine("Search..."); Assignment solution = model.SolveWithParameters(search_parameters); if (solution != null) { String output = "Total cost: " + solution.ObjectiveValue() + "\n"; // Dropped orders String dropped = ""; for (int order = 0; order < number_of_orders; ++order) { if (solution.Value(model.NextVar(order)) == order) { dropped += " " + order; } } if (dropped.Length > 0) { output += "Dropped orders:" + dropped + "\n"; } // Routes for (int vehicle = 0; vehicle < number_of_vehicles; ++vehicle) { String route = "Vehicle " + vehicle + ": "; long order = model.Start(vehicle); if (model.IsEnd(solution.Value(model.NextVar(order)))) { route += "Empty"; } else { for (; !model.IsEnd(order); order = solution.Value(model.NextVar(order))) { IntVar local_load = capacity_dimension.CumulVar(order); IntVar local_time = time_dimension.CumulVar(order); route += order + " Load(" + solution.Value(local_load) + ") " + "Time(" + solution.Min(local_time) + ", " + solution.Max(local_time) + ") -> "; } IntVar load = capacity_dimension.CumulVar(order); IntVar time = time_dimension.CumulVar(order); route += order + " Load(" + solution.Value(load) + ") " + "Time(" + solution.Min(time) + ", " + solution.Max(time) + ")"; } output += route + "\n"; } Console.WriteLine(output); } }