google / or-tools

Google's Operations Research tools:
https://developers.google.com/optimization/
Apache License 2.0
10.97k stars 2.1k forks source link

PDPTW with Start/End Nodes Crashes (python) #3782

Closed hj1234 closed 1 year ago

hj1234 commented 1 year ago

What version of OR-Tools and what language are you using? Version: main Language: Python

Issue related to: https://github.com/google/or-tools/issues/2167 (but after python solution please!)

**Which solver are you using Routing Solver

What did you do?

Ran the following code (adapted from the tutorials in the docs):

"""Vehicles Routing Problem (VRP) with Time Windows."""

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['time_matrix'] = [[0, 1648, 2037, 2565, 3385, 2930, 2933, 3701, 3452, 3521, 3506], [1532, 0, 649, 1176, 2102, 1522, 1435, 2245, 2064, 2227, 2501], [2093, 859, 0, 659, 1694, 1354, 1027, 1796, 1547, 1708, 2622], [2464, 1230, 708, 0, 1260, 1135, 768, 1142, 1162, 1323, 2994], [3120, 2130, 1675, 1391, 0, 777, 852, 1350, 2189, 2350, 3961], [2694, 1435, 1180, 1191, 806, 0, 480, 1402, 1985, 2146, 3466], [2885, 1584, 1128, 829, 667, 539, 0, 901, 1560, 1721, 3415], [3545, 2311, 1788, 1279, 1277, 1459, 1148, 0, 914, 1074, 4074], [3407, 2173, 1650, 1327, 1987, 2021, 1538, 1088, 0, 161, 3906], [3432, 2266, 1744, 1441, 2102, 2136, 1653, 1202, 263, 0, 3753], [3345, 2459, 2282, 2810, 3845, 3505, 3178, 3946, 3697, 3645, 0]]
    data['time_windows'] = [
   (0, 32400),
 (14400, 32400),
 (0, 32400),
 (0, 32400),
 (0, 32400),
 (0, 32400),
 (0, 32400),
 (0, 32400),
 (0, 32400),
 (0, 32400),
 (0, 32400)
    ]
    data['num_vehicles'] = 1
    data['depot'] = 0
    data['starts'] = [0]
    data['ends'] = [10]
    return data

def print_solution(data, manager, routing, solution):
    """Prints solution on console."""
    print(f'Objective: {solution.ObjectiveValue()}')
    time_dimension = routing.GetDimensionOrDie('Time')
    total_time = 0
    for vehicle_id in range(data['num_vehicles']):
        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), solution.Min(time_var),
                solution.Max(time_var))
            index = solution.Value(routing.NextVar(index))
        time_var = time_dimension.CumulVar(index)
        plan_output += '{0} Time({1},{2})\n'.format(manager.IndexToNode(index),
                                                    solution.Min(time_var),
                                                    solution.Max(time_var))
        plan_output += 'Time of the route: {}min\n'.format(
            solution.Min(time_var))
        print(plan_output)
        total_time += solution.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)

    # Create and register a transit callback.
    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)

    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Add Time Windows constraint.
    time = 'Time'
    routing.AddDimension(
        transit_callback_index,
        43200,  # allow waiting time
        43200,  # maximum time per vehicle
        False,  # Don't force start cumul to zero.
        time)
    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 == data['depot']:
            continue
        index = manager.NodeToIndex(location_idx)
        time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])
    # Add time window constraints for each vehicle end node.
    depot_idx = data['depot']
    for vehicle_id in range(data['num_vehicles']):
        index = routing.Start(vehicle_id)
        time_dimension.CumulVar(index).SetRange(
            data['time_windows'][depot_idx][0],
            data['time_windows'][depot_idx][1])

    # Instantiate route start and end times to produce feasible times.
    for i in range(data['num_vehicles']):
        routing.AddVariableMinimizedByFinalizer(
            time_dimension.CumulVar(routing.Start(i)))
        routing.AddVariableMinimizedByFinalizer(
            time_dimension.CumulVar(routing.End(i)))

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)

    # Solve the problem.
    solution = routing.SolveWithParameters(search_parameters)

    # Print solution on console.
    if solution:
        print_solution(data, manager, routing, solution)

if __name__ == '__main__':
    main()

What did you expect to see Optimised route with constraints

What did you see instead? Kernel crashes

lperron commented 1 year ago

Most likely a bug in the model. Moving to discussions.