2

I am trying to solve a capacitated pickup and delivery problem using ortools. Each vehicle has a capacity of 1 and, provided that the number of deliveries/jobs > number of vehicles, has to be utilised at least once. Of course, there has to be a solution but I am unable to find it. I have tried the approach described here as follows:

# Set Minimum Number of nodes
  count_dimension_name = 'count'
  # assume some variable num_nodes holds the total number of nodes
  routing.AddConstantDimension(
      1, # increment by one every time
      len(data['demands']),  # number of nodes incl depot
      True,  # set count to zero
      count_dimension_name)
  count_dimension = routing.GetDimensionOrDie(count_dimension_name)
  for veh in range(0, data['num_vehicles']):
      index_end = routing.End(veh)
      count_dimension.SetCumulVarSoftLowerBound(index_end,
                                                2,
                                                100000)

However, for the reproducible example (full code below) there is always one vehicle which is not utilised at all (more vehicles for other examples). How can I force each vehicle to be used and still be able to find at least a feasible solution? Perhaps by changing the search methods?

Reproducible Code:


from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['distance_matrix'] = [[0, 641, 331, 360, 3, 331, 2, 920, 2, 342, 3, 331, 342, 920, 1], 
 [641, 0, 505, 663, 643, 504, 639, 1556, 638, 397, 644, 505, 397, 1556, 641], 
 [331, 505, 0, 623, 334, 1, 329, 1188, 329, 110, 333, 0, 111, 1187, 330], 
 [360, 663, 623, 0, 358, 623, 360, 1007, 359, 575, 359, 623, 574, 1006, 361], 
 [3, 643, 334, 358, 0, 335, 6, 917, 5, 345, 1, 334, 345, 917, 4], 
 [331, 504, 1, 623, 335, 0, 329, 1188, 330, 110, 334, 0, 110, 1188, 330], 
 [2, 639, 329, 360, 6, 329, 0, 923, 1, 340, 5, 329, 340, 922, 2], 
 [920, 1556, 1188, 1007, 917, 1188, 923, 0, 923, 1242, 917, 1188, 1242, 0, 921], 
 [2, 638, 329, 359, 5, 330, 1, 923, 0, 340, 5, 330, 340, 922, 3], 
 [342, 397, 110, 575, 345, 110, 340, 1242, 340, 0, 345, 110, 0, 1242, 341], 
 [3, 644, 333, 359, 1, 334, 5, 917, 5, 345, 0, 334, 345, 917, 4], 
 [331, 505, 0, 623, 334, 0, 329, 1188, 330, 110, 334, 0, 110, 1188, 330], 
 [342, 397, 111, 574, 345, 110, 340, 1242, 340, 0, 345, 110, 0, 1242, 341], 
 [920, 1556, 1187, 1006, 917, 1188, 922, 0, 922, 1242, 917, 1188, 1242, 0, 920], 
 [1, 641, 330, 361, 4, 330, 2, 921, 3, 341, 4, 330, 341, 920, 0]]
    data['pickups_deliveries'] = [[ 1,  8],
       [ 2,  9],
       [ 3, 10],
       [ 4, 11],
       [ 5, 12],
       [ 6, 13],
       [ 7, 14]]
    data['num_vehicles'] = 4
    data['depot'] = 0
    data['vehicle_capacities'] = [1, 1, 1, 1]
    data['demands'] = [0, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1]

    return data

def print_solution(data, manager, routing, assignment):
    """Prints assignment on console."""
    total_distance = 0
    total_load = 0
    for vehicle_id in range(data['num_vehicles']):
        index = routing.Start(vehicle_id)
        plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
        route_distance = 0
        route_load = 0
        while not routing.IsEnd(index):
            node_index = manager.IndexToNode(index)
            route_load += data['demands'][node_index]
            plan_output += ' {0} Load({1}) -> '.format(node_index, route_load)
            previous_index = index
            index = assignment.Value(routing.NextVar(index))
            route_distance += routing.GetArcCostForVehicle(
                previous_index, index, vehicle_id)
        plan_output += ' {0} Load({1})\n'.format(manager.IndexToNode(index),
                                                 route_load)
        plan_output += 'Distance of the route: {}m\n'.format(route_distance)
        plan_output += 'Load of the route: {}\n'.format(route_load)
        print(plan_output)
        total_distance += route_distance
        total_load += route_load
    print('Total distance of all routes: {}m'.format(total_distance))
    print('Total load of all routes: {}'.format(total_load))
   
def main():    
  """Entry point of the program."""
  
  data = create_data_model()
  
  # Create the routing index manager.
  manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                         data['num_vehicles'], data['depot'])
  
  # Create Routing Model.
  routing = pywrapcp.RoutingModel(manager)
  
  # Define cost of each arc.
  def distance_callback(from_index, to_index):
      """Returns the manhattan distance between the two nodes."""
      # Convert from routing variable Index to distance matrix NodeIndex.
      from_node = manager.IndexToNode(from_index)
      to_node = manager.IndexToNode(to_index)
      return data['distance_matrix'][from_node][to_node]
  
  transit_callback_index = routing.RegisterTransitCallback(distance_callback)
  routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  
  # Add Capacity constraint.
  def demand_callback(from_index):
      """Returns the demand of the node."""
      # Convert from routing variable Index to demands NodeIndex.
      from_node = manager.IndexToNode(from_index)
      return data['demands'][from_node]
  
  demand_callback_index = routing.RegisterUnaryTransitCallback(
      demand_callback)
  routing.AddDimensionWithVehicleCapacity(
      demand_callback_index,
      0,  # null capacity slack
      data['vehicle_capacities'],  # vehicle maximum capacities
      True,  # start cumul to zero
      'Capacity')
  
  # Add Distance constraint.
  dimension_name = 'Distance'
  routing.AddDimension(
      transit_callback_index,
      0,  # no slack
      1000000,  # vehicle maximum travel distance
      True,  # start cumul to zero
      dimension_name)
  distance_dimension = routing.GetDimensionOrDie(dimension_name)
  distance_dimension.SetGlobalSpanCostCoefficient(100)
  
  # Set Minimum Number of nodes
  count_dimension_name = 'count'
  # assume some variable num_nodes holds the total number of nodes
  routing.AddConstantDimension(
      1, # increment by one every time
      len(data['demands']),  # number of nodes incl depot
      True,  # set count to zero
      count_dimension_name)
  count_dimension = routing.GetDimensionOrDie(count_dimension_name)
  for veh in range(0, data['num_vehicles']):
      index_end = routing.End(veh)
      count_dimension.SetCumulVarSoftLowerBound(index_end,
                                                2,
                                                100000)
   
  # 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(distance_dimension.CumulVar(pickup_index) <= distance_dimension.CumulVar(delivery_index))
  
  # Define Search Approach
  search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  search_parameters.first_solution_strategy = (routing_enums_pb2.FirstSolutionStrategy.AUTOMATIC)
  search_parameters.local_search_metaheuristic = (routing_enums_pb2.LocalSearchMetaheuristic.AUTOMATIC)
  search_parameters.time_limit.FromSeconds(10)
  
  
  # Solve the problem.
  assignment = routing.SolveWithParameters(search_parameters)
  
  # Print solution on console.
  if assignment:
      print_solution(data, manager, routing, assignment)


if __name__ == '__main__':
    main()


D.Wies
  • 53
  • 5

0 Answers0