Hello I'm trying to setup my own pickup and delivery problem with time windows and custom start/end locations using python (3.6) and ortools (Version 7) library. In the below example I have a PDP where I set time windows and start/end locations. The below example will not run - it crashes and I've found some issues. During debugging I've noticed that when I go to set my time_window constraints NodeToIndex(location_idx) returns -1 . Is there any reason I should even use NodeToIndex in this case? Why Can't I just use location_idx? If I instead use location_idx to set the CumulVar then the code proceeds with time windows set however then fails when going to setup the "pickups_deliveries". I don't think it likes that I'm setting up delivery at an end node. Why is that the case? Can someone recommend how to do this?
Essentially from a high level I want the find the route for a driver at any start point I give it, to go to the depot and pick up 2+ packages and deliver them at different locations.
from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp
from ortools.constraint_solver.pywrapcp import RoutingIndexManager, RoutingModel
def create_data_model():
"""Stores the data for the problem."""
data = {}
data['time_matrix'] = [
#Dr #De #C1 #C2
[0, 5, 3, 10], # Driver
[5, 0, 4, 8], # Depot
[3, 4, 0, 4], # Customer 1
[10, 8, 4, 0] # Customer 2
]
data['pickups_deliveries'] = [
[1, 2],
[1, 3]
]
data['time_windows'] = [
(0, 0), # driver
(6, 6), # depot
(10, 12), # c1
(12, 16) # c2
]
data['starts'] = [0]
data['ends'] = [3]
data['num_vehicles'] = 1
return data
# todo replace with time one
def print_solution(data, manager: RoutingIndexManager, routing: RoutingModel, assignment):
"""Prints assignment on console."""
time_dimension = routing.GetDimensionOrDie('Time')
total_time = 0
for vehicle_id in range(data['num_vehicles']):
# Model inspection. Returns the variable index of the starting node of a vehicle route.
index = routing.Start(vehicle_id)
plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
while not routing.IsEnd(index):
time_var = time_dimension.CumulVar(index)
plan_output += '{0} Time({1},{2}) -> '.format(
manager.IndexToNode(index), assignment.Min(time_var),
assignment.Max(time_var))
index = assignment.Value(routing.NextVar(index))
# handles the end location
time_var = time_dimension.CumulVar(index)
plan_output += '{0} Time({1},{2})\n'.format(
manager.IndexToNode(index), assignment.Min(time_var),
assignment.Max(time_var))
plan_output += 'Time of the route: {}min\n'.format(
assignment.Min(time_var))
print(plan_output)
total_time += assignment.Min(time_var)
print('Total time of all routes: {}min'.format(total_time))
def main():
"""Solve the VRP with time windows."""
# Instantiate the data problem.
data = create_data_model()
# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(
len(data['time_matrix']), data['num_vehicles'], data['starts'],
data['ends'])
# Create Routing Model.
routing = pywrapcp.RoutingModel(manager)
def time_callback(from_index, to_index):
"""Returns the travel time between the two nodes."""
# Convert from routing variable Index to time matrix NodeIndex.
from_node = manager.IndexToNode(from_index)
to_node = manager.IndexToNode(to_index)
return data['time_matrix'][from_node][to_node]
transit_callback_index = routing.RegisterTransitCallback(time_callback)
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
# The code creates a dimension for the travel time of the vehicles, similar to the dimensions
# for travel distance or demands in previous examples. Dimensions keep track of quantities that
# accumulate over a vehicle's route. In the code above, time_dimension.CumulVar(index) is the
# cumulative travel time when a vehicle arrives at the location with the given index.
time = 'Time'
routing.AddDimension(
transit_callback_index,
30, # allow waiting time
30, # maximum time per vehicle
False, # Don't force start cumul to zero.
time)
# Returns a dimension from its name. Dies if the dimension does not exist.
time_dimension = routing.GetDimensionOrDie(time)
# Add time window constraints for each location except depot.
for location_idx, time_window in enumerate(data['time_windows']):
if location_idx == 0: # idx 0 and 1 are the driver and customer
continue
# NodeToIndex returns -1 for end nodes
index = manager.NodeToIndex(location_idx)
time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])
# Not sure if I need this? Removed for now
# Add time window constraints for each vehicle start node.
# for vehicle_id in range(data['num_vehicles']):
# # Model inspection. Returns the variable index of the starting node of a vehicle route.
# start_index = routing.Start(vehicle_id)
# time_dimension.CumulVar(start_index).SetRange(data['time_windows'][0][0],
# data['time_windows'][0][1])
for i in range(data['num_vehicles']):
routing.AddVariableMinimizedByFinalizer(
time_dimension.CumulVar(routing.Start(i)))
routing.AddVariableMinimizedByFinalizer(
time_dimension.CumulVar(routing.End(i)))
# Define Transportation Requests.
for request in data['pickups_deliveries']:
pickup_index = manager.NodeToIndex(request[0])
delivery_index = manager.NodeToIndex(request[1])
routing.AddPickupAndDelivery(pickup_index, delivery_index)
routing.solver().Add(
routing.VehicleVar(pickup_index) == routing.VehicleVar(
delivery_index))
routing.solver().Add(
time_dimension.CumulVar(pickup_index) <=
time_dimension.CumulVar(delivery_index))
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.time_limit.seconds = 30
search_parameters.first_solution_strategy = (
routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
assignment = routing.SolveWithParameters(search_parameters)
if assignment:
print_solution(data, manager, routing, assignment)
if __name__ == '__main__':
main()
I believe start and end nodes cannot be visits. So you need more nodes.
Reopen if this is wrong.
Did you resolved this?
Most helpful comment
I believe start and end nodes cannot be visits. So you need more nodes.
Reopen if this is wrong.