Esempio n. 1
0
def main():
    """Solve the CVRP problem."""
    # Instantiate the data problem.
    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)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the 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)

    # Define cost of each arc.
    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')

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

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

    # Print solution on console.
    if assignment:
        print_solution(data, manager, routing, assignment)
Esempio n. 2
0
def main():
    """Entry point of the program."""
    # Instantiate the data problem.
    # [START data]
    data = create_data_model()
    # [END data]

    # Create the routing index manager.
    # [START index_manager]
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['num_vehicles'], data['depot'])
    # [END index_manager]

    # Create Routing Model.
    # [START routing_model]
    routing = pywrapcp.RoutingModel(manager)

    # [END routing_model]

    # Create and register a transit callback.
    # [START transit_callback]
    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)
    # [END transit_callback]

    # Define cost of each arc.
    # [START arc_cost]
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
    # [END arc_cost]

    # Setting first solution heuristic.
    # [START parameters]
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
    # [END parameters]

    # Solve the problem.
    # [START solve]
    assignment = routing.SolveWithParameters(search_parameters)
    # [END solve]

    # Print solution on console.
    # [START print_solution]
    if assignment:
        print_solution(manager, routing, assignment)
Esempio n. 3
0
 def test_unary_transit_callback(self):
     manager = pywrapcp.RoutingIndexManager(5, 2, 0)
     self.assertIsNotNone(manager)
     routing = pywrapcp.RoutingModel(manager)
     self.assertIsNotNone(routing)
     transit_id = routing.RegisterUnaryTransitCallback(lambda from_index: 1)
     self.assertEqual(1, transit_id)
     routing.SetArcCostEvaluatorOfAllVehicles(transit_id)
     self.assertEqual(routing.ROUTING_NOT_SOLVED, routing.status())
     assignment = routing.Solve()
     self.assertEqual(routing.ROUTING_SUCCESS, routing.status())
     self.assertIsNotNone(assignment)
     self.assertEqual(5, assignment.ObjectiveValue())
Esempio n. 4
0
def get_or_tsp(locs, timeout):
    """Entry point of the program."""
    # Instantiate the data problem.
    data = create_data_model(locs, factor=1000)

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(data["distance_matrix"].size(0),
                                           data["num_vehicles"], data["depot"])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the 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)

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

    # Add Distance constraint.
    dimension_name = "Distance"
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        data["max_travel_distance"],  # vehicle maximum travel distance
        True,  # start cumul to zero (vehicles start at the same time)
        dimension_name,
    )
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(
        100)  # not sure what this does

    # Setting guided local search heuristic
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.local_search_metaheuristic = (
        routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
    search_parameters.time_limit.seconds = timeout
    search_parameters.log_search = False
    solution = routing.SolveWithParameters(search_parameters)

    # Print solution on console.
    if solution:
        return get_route_distance(data, manager, routing, solution)
    else:
        raise ValueError("Google OR tools failed.")
def solveGoogle(nodeCount, inputData, points):
    #####GOOGLE SOLVER#####
    print("GOOGLE!!!")
    data = create_data_model(inputData)

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['locations']),
                                           data['num_vehicles'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    #distance_matrix = compute_euclidean_distance_matrix(data['locations'])

    def distance_callback(from_index, to_index):
        """Returns the 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 distance_matrix[from_node][to_node]

        #print("google- %s" %distance_matrix[from_node][to_node])
        if to_index == nodeCount:
            to_index -= 1
        #print("%s-" %from_index,end="")
        #print(to_index)
        x = int(length(points[from_index], points[to_index]) * 100)
        #print(x)
        return x

    transit_callback_index = routing.RegisterTransitCallback(distance_callback)

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

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
    #search_parameters.local_search_metaheuristic = (routing_enums_pb2.LocalSearchMetaheuristic.SIMULATED_ANNEALING)
    search_parameters.lns_time_limit.seconds = 1
    search_parameters.solution_limit = 1

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

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

    return solution
Esempio n. 6
0
def solve_tsp(costs, constraints=[], beam_size=1, gls=False):
    manager = pywrapcp.RoutingIndexManager(len(costs), 1, 0)
    routing = pywrapcp.RoutingModel(manager)

    def distance_callback(from_index, to_index):
        """Returns the 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 costs[from_node][to_node]

    transit_callback_index = routing.RegisterTransitCallback(distance_callback)

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

    # linear order constraints
    if constraints:
        order_callback_index = routing.RegisterUnaryTransitCallback(
            lambda x: 1)  # always add 1
        routing.AddDimension(order_callback_index, 0,
                             len(costs) + 1, True, 'Order')
        order = routing.GetDimensionOrDie('Order')

        for i, j in constraints:
            solver.Add(order.CumulVar(i) < order.CumulVar(j))

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()

    search_parameters.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.GLOBAL_CHEAPEST_ARC
    search_parameters.time_limit.seconds = 1
    search_parameters.solution_limit = 100
    search_parameters.log_search = False

    if gls:
        search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH

    # Solve the problem.
    assignment = routing.SolveWithParameters(search_parameters)
    if assignment:
        out = []
        index = routing.Start(0)
        while not routing.IsEnd(index):
            out.append(manager.IndexToNode(index))
            index = assignment.Value(routing.NextVar(index))
        out.append(manager.IndexToNode(index))
        return out
    else:
        return []
def main():
    """Entry point of the program."""
    # Instantiate the data problem.
    data = create_data_model()

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['locations']),
                                           data['num_vehicles'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    distance_matrix = compute_euclidean_distance_matrix(data['locations'])
    # print(distance_matrix)

    def distance_callback(from_index, to_index):
        """Returns the 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 distance_matrix[from_node][to_node]

    transit_callback_index = routing.RegisterTransitCallback(distance_callback)

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

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

    # Add some fun. Just for test. Eason. 04-21.
    # We can also using Local searching. Like SIMULATED_ANNEALING, GENERIC_TABU_SEARCH, etc.
    # There are other function or method to solve the search processing. We also add some constraints on it.

    # search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    # search_parameters.local_search_metaheuristic = (
    #     routing_enums_pb2.LocalSearchMetaheuristic.SIMULATED_ANNEALING
    # )
    # search_parameters.time_limit.seconds = 5
    # search_parameters.log_search = True

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

    # Print solution on console.
    if solution:
        print_solution(manager, routing, solution)
def main():
    
    # 初始化数据
    data = create_data_model()
 
    # 创建路线管理,tsp_size(城市数量), num_vehicles(车的数量), depot(原点)
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['num_vehicles'], data['depot'])
 
    # 创建 Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # 计算两点之间的距离
    def distance_callback(from_index, to_index):
        # Convert from routing variable Index to distance matrix NodeIndex.
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        #print(data['distance_matrix'][from_node][to_node])
        return data['distance_matrix'][from_node][to_node]

 
    transit_callback_index = routing.RegisterTransitCallback(distance_callback)

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

    # 添加距离约束
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        10000,  # 车辆最大行驶距离
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    # 尽量减少车辆之间的最大距离
    distance_dimension.SetGlobalSpanCostCoefficient(100)
 
    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
 
    # 求解路径规划
    solution = routing.SolveWithParameters(search_parameters)
    # 输出结果
    if solution:
        print_solution(manager, data['num_vehicles'], routing, solution)
    else:
        print(solution)
Esempio n. 9
0
def run(data_, trans_type, time_travel, penalty, indexes):
    """Solve the CVRP problem."""
    # Instantiate the data problem.
    data = create_data_model(data_)

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['tourist'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the 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)

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

    # Add Distance constraint.
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        time_travel,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)

    for node in range(1, len(data['distance_matrix'])):
        routing.AddDisjunction([manager.NodeToIndex(node)], penalty)

    # Solve the problem.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.AUTOMATIC)
    solution = routing.SolveWithParameters(search_parameters)

    if solution:
        print('The Objective Value is {0}'.format(solution.ObjectiveValue()))
    # Print solution on console.
    if solution:
        return print_solution(data, manager, routing, solution, trans_type,
                              indexes)
    else:
        print('Infeasible')
Esempio n. 10
0
def main():
    """Solve the VRP with time windows."""
    data = create_data_model()
    manager = pywrapcp.RoutingIndexManager(len(data['time_matrix']),
                                           data['num_vehicles'], data['depot'])
    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)
    time = 'Time'
    routing.AddDimension(
        transit_callback_index,
        300,  # allow waiting time
        1000,  # 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.
    # also add pickups/dropoffs
    for location_idx, time_window in enumerate(data['time_windows']):
        if location_idx == 0:
            continue
        index = manager.NodeToIndex(location_idx)
        time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])
    for pd, tw in zip(data['pickups_deliveries'], data["time_windows"]):
        pickup, dropoff = pd
        routing.AddPickupAndDelivery(pickup, dropoff)
        routing.solver().Add(
            routing.VehicleVar(pickup) == routing.VehicleVar(dropoff))

        time_dimension.CumulVar(dropoff).SetRange(tw[0], tw[1])

    for i in range(data['num_vehicles']):
        routing.AddVariableMinimizedByFinalizer(
            time_dimension.CumulVar(routing.Start(i)))
        routing.AddVariableMinimizedByFinalizer(
            time_dimension.CumulVar(routing.End(i)))
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PARALLEL_CHEAPEST_INSERTION)
    assignment = routing.SolveWithParameters(search_parameters)
    if assignment:
        print_solution(data, manager, routing, assignment)
Esempio n. 11
0
def main():
    """Solve the CVRP problem."""
    # Instantiate the data problem.
    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)


    transit_callback_indices = []
    for i in range(data['num_vehicles']):
        # Create and register a transit callback.
        def distance_callback(from_index, to_index):
            """Returns the 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]*data['vehicle_speeds'][i]

        transit_callback_index = routing.RegisterTransitCallback(distance_callback)
        transit_callback_indices.append(transit_callback_index)

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

    dimension_name = 'Running Time'
    routing.AddDimensionWithVehicleTransits(
        transit_callback_indices,
        0,
        300000,
        True,
        dimension_name
    )
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(100)

    # 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)
Esempio n. 12
0
def main():
    """Solve the CVRP problem."""
    # Instantiate the data problem.
    #data_file = sys.argv[1]
    data = create_grid_model(3)  # create_model(data_file)

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['num_vehicles'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the 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)

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

    # Add Distance constraint.
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        3000,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(100)

    # 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)
        solution_paths = optops.get_all_routes(data, manager, routing,
                                               solution)
        print_matplotlib_grid(data, solution_paths)
Esempio n. 13
0
 def testTransitCallback(self):
     manager = pywrapcp.RoutingIndexManager(5, 1, 0)
     self.assertIsNotNone(manager)
     model = pywrapcp.RoutingModel(manager)
     self.assertIsNotNone(model)
     cost = model.RegisterTransitCallback(partial(TransitDistance, manager))
     self.assertEqual(1, cost)
     model.SetArcCostEvaluatorOfAllVehicles(cost)
     self.assertEqual(pywrapcp.RoutingModel.ROUTING_NOT_SOLVED,
                      model.status())
     assignment = model.Solve()
     self.assertTrue(assignment)
     self.assertEqual(pywrapcp.RoutingModel.ROUTING_SUCCESS, model.status())
     self.assertEqual(20, assignment.ObjectiveValue())
Esempio n. 14
0
def main():
    #address_dataframe = calculate_geocodes()
    distance_matrix = calculate_distance_matrix(coordinates, gmaps)
    data = create_data_model(distance_matrix, 5, 0)

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['num_vehicles'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the 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)

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

    # Add Distance constraint.
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        80,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(100)

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()

    search_parameters.local_search_metaheuristic = (
        routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
    search_parameters.time_limit.seconds = 120
    search_parameters.log_search = False

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

    # Print solution on console.
    if solution:
        print_solution(data, manager, routing, solution)  #, address_dataframe)
def get_target_order(distance, starting_pos):
    manager = pywrapcp.RoutingIndexManager(len(distance), 1, starting_pos)
    routing = pywrapcp.RoutingModel(manager)
    distance_callback = create_distance_callback(distance, manager)
    transit_callback_index = routing.RegisterTransitCallback(distance_callback)
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)

    # Solve the problem.
    assignment = routing.SolveWithParameters(search_parameters)
    target_order = get_solution(manager, routing, assignment, 0)
    return target_order
    def main(self):
        """Entry point of the program."""
        # Instantiate the data problem.
        data = self.create_data_model(self)

        # Create the routing index manager.
        manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                               data['num_vehicles'], data['depot'])
        # Create Routing Model.
        routing = pywrapcp.RoutingModel(manager)

        def distance_callback(from_index, to_index):
            """Returns the 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)

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

        # Setting first solution heuristic.
        # The first solution strategy is the method the solver uses to find an initial solution.
        # Saving, CHRISTOFIDES, LOCAL_CHEAPEST_INSERTION, GLOBAL_CHEAPEST_ARC

        search_parameters = pywrapcp.DefaultRoutingSearchParameters()
        search_parameters.first_solution_strategy = (
            routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)

        # Add some fun. Just for test. Eason.
        # The guided local search, which enables the solver to escape a local minimum.
        # The belows are local search strategies (also called metaheuristics.
        # The methods included Automatic, Greedy_search, simulated_annealing, tabu_search, ....
        # search_parameters = pywrapcp.DefaultRoutingSearchParameters()
        # search_parameters.local_search_metaheuristic = (
        #     routing_enums_pb2.LocalSearchMetaheuristic.OBJECTIVE_TABU_SEARCH
        # )
        # search_parameters.time_limit.seconds = 10
        # search_parameters.solution_limit = 159
        # search_parameters.log_search = True

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

        # Print solution on console.
        if solution:
            final_index = self.print_solution(manager, routing, solution)
        return final_index
def get_route_json(json_data):
    '''

    :param request_data:
    :return:
    '''
    # init model input data
    node_list = json_data['nodeList']
    points_len = len(node_list)
    distance_matrix = np.zeros((points_len, points_len), dtype=np.int)
    for row in range(points_len):
        for col in range(row + 1, points_len):
            X_0, Y_0, X_1, Y_1 = node_list[row]['longitude'], node_list[row]['latitude'], node_list[col]['longitude'], \
                                 node_list[col]['latitude']
            distance_matrix[row, col] = get_navi_distance(X_0, Y_0, X_1, Y_1)

    distance_matrix_1 = distance_matrix + distance_matrix.T
    distance_matrix_1[:, 0] = 0

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(distance_matrix_1), 1, 0)

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    def distance_callback(from_index, to_index):
        """Returns the 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 distance_matrix_1[from_node][to_node]

    transit_callback_index = routing.RegisterTransitCallback(distance_callback)

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

    # 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:
        return print_solution(json_data, manager, routing, solution)
    else:
        return "Failed"
Esempio n. 18
0
def vrp_processing(data=None):

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['num_vehicles'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the 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)

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

    # Add Distance constraint.
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        5000,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(100)

    # Setting first solution heuristic.

    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.local_search_metaheuristic = (
        routing_enums_pb2.LocalSearchMetaheuristic.GREEDY_DESCENT)
    search_parameters.time_limit.seconds = 30
    #search_parameters.log_search = True
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
    )  # FIRST SOLUTION STRATEGY WILL BE USED TO COMPARE ALGORITHMS

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

    # Print solution on console.
    if solution:
        print_solution_vrp(data, manager, routing, solution)
Esempio n. 19
0
def main():
    """Entry point of the program."""
    # Instantiate the data problem.
    data_test = create_data_model()
    data_test = data  # from api test data

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data_test['distance_matrix']),
                                           data_test['num_vehicles'],
                                           data_test['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # def distance_callback(from_index, to_index):
    #     """Returns the 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]

    def distanceCallback(from_index, to_index):
        """ ortools tsp solver method, gets distances from the distance matrix
        using numpy array slicing, rather than python lists
        NOTE IMPORTANT: For some reason, this function definition must be defined AFTER the 'manager' 
        instance is created, for some reason. 
        See https://stackoverflow.com/questions/55862927/python-or-tools-function-does-not-work-when-called-from-within-a-python-package
        """
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        # return data['distance_matrix'][from_node, to_node]
        # NOTE: This is the problem,
        return data_test['distance_matrix'][from_node, to_node]

    transit_callback_index = routing.RegisterTransitCallback(distanceCallback)

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

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

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

    # Print solution on console.
    if assignment:
        print_solution(manager, routing, assignment)
Esempio n. 20
0
 def test_transit_matrix(self):
     manager = pywrapcp.RoutingIndexManager(5, 2, 0)
     self.assertIsNotNone(manager)
     routing = pywrapcp.RoutingModel(manager)
     self.assertIsNotNone(routing)
     matrix = [[i + 1 for i in range(5)] for j in range(5)]
     transit_id = routing.RegisterTransitMatrix(matrix)
     self.assertEqual(1, transit_id)
     routing.SetArcCostEvaluatorOfAllVehicles(transit_id)
     self.assertEqual(routing.ROUTING_NOT_SOLVED, routing.status())
     assignment = routing.Solve()
     self.assertEqual(routing.ROUTING_SUCCESS, routing.status())
     self.assertIsNotNone(assignment)
     self.assertEqual(15, assignment.ObjectiveValue())
Esempio n. 21
0
def solve_route(destinations: List[Destination]) -> List[Destination]:
    """Travelling salesman problem solver

    Takes a list of destinations and sorts them such that the total time taken to visit each one is
    minimized. This is known as the travelling salesman problem.

    Much of the code in this function is borrowed from the example here:
    https://developers.google.com/optimization/routing/tsp

    Args:
        destinations: A list of places to visit. It is assumed that the first destination in the
            list is the first and last destination for the trip, otherwise known as the "depot".

    Returns:
        The list of places ordered such that visiting them in that order minimizes the total trip
        time.
    """

    # pre-compute a matrix of distances between each destination
    distance_matrix = np.zeros((len(destinations),)*2)
    for idx, dest in enumerate(destinations):
        for jdx in range(idx + 1, len(destinations)):
            distance_matrix[idx, jdx] = dest.distance_to(destinations[jdx])
    distance_matrix += np.transpose(distance_matrix)

    manager = pywrapcp.RoutingIndexManager(len(destinations), 1, 0)
    routing = pywrapcp.RoutingModel(manager)

    def distance_callback(from_index, to_index):
        """Returns the distance between the two nodes."""
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        return distance_matrix[from_node][to_node]
    transit_callback_index = routing.RegisterTransitCallback(distance_callback)
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)  # pylint: disable=no-member

    solution = routing.SolveWithParameters(search_parameters)

    index = routing.Start(0)
    route = [destinations[manager.IndexToNode(index)]]
    while not routing.IsEnd(index):
        index = solution.Value(routing.NextVar(index))
        route.append(destinations[manager.IndexToNode(index)])

    return route
def main():
    """Entry point of the program."""
    # Instantiate the data problem.
    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)

    def distance_callback(from_index, to_index):
        """Returns the 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)

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

    # Add Distance constraint.
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        3000,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(100)

    # Add Load Time constraint
    dimension_name = 'LoadTime'  # in hours
    routing.AddDimension(transit_callback_index, 0, 8, False, dimension_name)

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

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

    # Print solution on console.
    if assignment:
        print_solution(data, manager, routing, assignment)
Esempio n. 23
0
 def testCallback(self):
     manager = pywrapcp.RoutingIndexManager(10, 1, 0)
     model = pywrapcp.RoutingModel(manager)
     cost = model.RegisterTransitCallback(partial(TransitDistance, manager))
     model.SetArcCostEvaluatorOfAllVehicles(cost)
     callback = Callback(model)
     model.AddAtSolutionCallback(callback)
     search_parameters = pywrapcp.DefaultRoutingSearchParameters()
     search_parameters.first_solution_strategy = (
         routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
     assignment = model.SolveWithParameters(search_parameters)
     self.assertEqual(90, assignment.ObjectiveValue())
     self.assertEqual(1, len(callback.costs))
     self.assertEqual(90, callback.costs[0])
Esempio n. 24
0
def main():
    """Solve the VRP with time windows.
        处理带时间窗的VPR问题
    """
    data = create_data_model()
    manager = pywrapcp.RoutingIndexManager(len(data['time_matrix']),
                                           data['num_vehicles'], data['depot'])
    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)
    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)
    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:
            continue
        index = manager.NodeToIndex(location_idx)
        time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])
    # Add time window constraints for each vehicle start node.
    for vehicle_id in range(data['num_vehicles']):
        index = routing.Start(vehicle_id)
        time_dimension.CumulVar(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)))

    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
    solution = routing.SolveWithParameters(search_parameters)
    if solution:
        print_solution(data, manager, routing, solution)
Esempio n. 25
0
def setup_model(d,t,v):
    # common to both with and without breaks
    num_nodes = len(t.index)
    manager = pywrapcp.RoutingIndexManager(
        num_nodes,
        len(v),
        v[0].depot_index)
    routing = pywrapcp.RoutingModel(manager)
    time_callback = E.create_time_callback2(t, d)
    demand_callback = E.create_demand_callback(t.index,d)

    transit_callback_index = routing.RegisterTransitCallback(
        partial(time_callback, manager)
    )

    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # count
    routing.AddConstantDimension(
        1, # increment by one every time
        num_nodes,  # max count is visit all the nodes
        True,  # set count to zero
        count_dimension_name)
    count_dimension = routing.GetDimensionOrDie(count_dimension_name)

    # time
    routing.AddDimension(
        transit_callback_index, # same "cost" evaluator as above
        # d.horizon,  # try infinite slack
        0, # try no slack
        d.horizon,  # max time is end of time horizon
        False,  # don't set time to zero...vehicles can wait at depot if necessary
        time_dimension_name)
    time_dimension = routing.GetDimensionOrDie(time_dimension_name)
    # time_dimension.SetGlobalSpanCostCoefficient(100)

    # capacity/demand
    demand_evaluator_index = routing.RegisterUnaryTransitCallback(
        partial(demand_callback, manager))
    vehicle_capacities = [veh.capacity for veh in v]
    routing.AddDimensionWithVehicleCapacity(
        demand_evaluator_index,
        0,  # null capacity slack
        vehicle_capacities,
        True,  # start cumul to zero
        cap_dimension_name)
    cap_dimension = routing.GetDimensionOrDie(cap_dimension_name)

    return (num_nodes,manager,routing)
Esempio n. 26
0
def vrp_solve(user_data: dict) -> dict:
    """Solve the CVRP problem."""
    # Instantiate the data problem.
    # data = create_data_model()
    data = user_data

    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['num_vehicles'], data['depot'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the 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)

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

    # Add Distance constraint.
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        3000,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(100)

    # 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)

    # Returns solution if one is found
    if solution:
        return _return_solution(data, manager, routing, solution)
    else:
        return {'Message': 'No solution', 'Status': 'Failure'}
Esempio n. 27
0
def VRPtime_windows_algorithm(locations, vehicles, avg_speed, time_windows,
                              depot_location):
    # Algorithm implemented using Google OR Tools and with help from this link: https://developers.google.com/optimization/routing/vrptw
    time_matrix = VRP_module.getTimeMatrix(locations, avg_speed)
    manager = pywrapcp.RoutingIndexManager(len(time_matrix), vehicles,
                                           depot_location)
    routing = pywrapcp.RoutingModel(manager)

    def time_callback(from_index, to_index):
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
        return time_matrix[from_node][to_node]

    transit_callback_index = routing.RegisterTransitCallback(time_callback)

    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    time = 'Time'
    routing.AddDimension(transit_callback_index, 30, 30, False, time)
    time_dimension = routing.GetDimensionOrDie(time)

    for location_idx, time_window in enumerate(time_windows):
        if location_idx == 0:
            continue
        index = manager.NodeToIndex(location_idx)
        time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])

    for vehicle_id in range(vehicles):
        index = routing.Start(vehicle_id)
        time_dimension.CumulVar(index).SetRange(time_windows[0][0],
                                                time_windows[0][1])

    for i in range(vehicles):
        routing.AddVariableMinimizedByFinalizer(
            time_dimension.CumulVar(routing.Start(i)))
        routing.AddVariableMinimizedByFinalizer(
            time_dimension.CumulVar(routing.End(i)))

    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)

    solution = routing.SolveWithParameters(search_parameters)

    if solution:
        return generate_solution(locations, solution, vehicles, routing,
                                 manager)
    else:
        return "No solution found"
Esempio n. 28
0
def solver(data, no_empty_vehicles=False):
    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                           data['num_vehicles'],
                                           data['depots'], data['depots'])

    # Create Routing Model.
    routing = pywrapcp.RoutingModel(manager)

    # Create and register a transit callback.
    def distance_callback(from_index, to_index):
        """Returns the 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)
    # Define cost of each arc.
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    # Add Distance constraint.
    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        30000,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(100)

    # Setting first solution heuristic.
    search_parameters = pywrapcp.DefaultRoutingSearchParameters()
    search_parameters.first_solution_strategy = (
        routing_enums_pb2.FirstSolutionStrategy.AUTOMATIC)
    search_parameters.local_search_metaheuristic = (
        routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
    search_parameters.time_limit.seconds = 10
    search_parameters.lns_time_limit.seconds = 50
    search_parameters.log_search = True

    #Ensure all vehicles serve atleast one station
    if no_empty_vehicles:
        no_empty_routes(data, routing)

    # Create a solver
    solution = routing.SolveWithParameters(search_parameters)
    return manager, routing, solution
Esempio n. 29
0
    def __init__(self,
                 locs: int,
                 num_vehicles=int,
                 depo=0,
                 starts=None,
                 ends=None):
        self.locs = locs
        self.num_vehicles = num_vehicles
        self.depo = depo
        self.starts = starts
        self.ends = ends

        if self.starts is None and self.ends is None:
            self.manager = pywrapcp.RoutingIndexManager(
                self.locs, self.num_vehicles, self.depo)
        else:
            assert len(self.starts) == len(self.ends) == self.num_vehicles
            self.manager = pywrapcp.RoutingIndexManager(
                self.locs, self.num_vehicles, self.starts, self.ends)
        self.routing = pywrapcp.RoutingModel(self.manager)
        self.solution = None
        self.search_parameters = pywrapcp.DefaultRoutingSearchParameters()
        self._solution = None
        self.objective = np.Inf
Esempio n. 30
0
 def test_matrix_dimension_2(self):
     manager = pywrapcp.RoutingIndexManager(5, 2, 0)
     self.assertIsNotNone(manager)
     routing = pywrapcp.RoutingModel(manager)
     self.assertIsNotNone(routing)
     matrix = [[i+1 for i in range(5)] for j in range(5)]
     routing.AddMatrixDimension(
             matrix,
             10, # capacity
             True, # fix_start_cumul_to_zero
             "DimensionName")
     transit_id = routing.RegisterTransitMatrix(matrix)
     self.assertEqual(2, transit_id)
     routing.SetArcCostEvaluatorOfAllVehicles(transit_id)
     self.assertTrue(routing.Solve())