1

I am using OR tools to solve VRP without any constraints. Here is the source code:

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    data['distance_matrix'] = [
        [0, 20079, 2613, 8005, 19277, 12468, 13701],
        [0, 0, 21285, 16012, 32574, 35394, 28806],
        [0, 18233, 0, 5392, 19965, 19650, 13064],
        [0, 15013, 5639, 0, 22883, 22570, 15982],
        [0, 32991, 19256, 21815, 0, 18414, 9112],
        [0, 34348, 16976, 23122, 15678, 0, 14647],
        [0, 27652, 13917, 16476, 8043, 14820, 0]
    ]
    data['num_vehicles'] = 6
    data['depot'] = 0
    return data

def test(request):
    # 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)
    
    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

    dimension_name = 'Distance'
    routing.AddDimension(
        transit_callback_index,
        0,  # no slack
        1000000000,  # vehicle maximum travel distance
        True,  # start cumul to zero
        dimension_name)
    distance_dimension = routing.GetDimensionOrDie(dimension_name)
    distance_dimension.SetGlobalSpanCostCoefficient(1)
    
    # 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)

    return HttpResponse('')

This works like a charm, except in my case, the cost per unit distance is not linear. Say for for 0-5km, it costs 10rs/km. Then for 5-10km, it costs 25rs/km .

This means the single distance matrix no longer holds good, and I must do something else.

Is there any way I can achieve this? Thanks in advance!

Mizux
  • 8,222
  • 7
  • 32
  • 48
Shrihari S
  • 13
  • 3

0 Answers0