微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过日期循环解决方案Python 中 ORTools 的 CVRP 问题

如何解决通过日期循环解决方案Python 中 ORTools 的 CVRP 问题

我们希望为 CVRP 解决方案创建一个日期循环。 我们正在上传一个月的订单(需求),然后为该月的每一周创建一个独特的路线。

我们似乎无法弄清楚如何让模型每周打印一个解决方案。 目前,它正在每天打印完整的解决方案,使用代码:“for date in data['date']:”,在“print_routing_guide”定义下。

我觉得日期需要以某种方式附加到索引中?或围绕“solution = routing.solveWithParameters(search_parameters)”循环日期?

有谁知道用什么代码解决这个问题?

任何帮助将不胜感激! 谢谢!

请查看我们在下面使用的代码

def print_routing_guide(data,manager,routing,solution):
    """Print solution on console."""
    print('\n')
    total_distance = 0
    total_load = 0
    for date in data['date']:
        print('\n')
        print('Date is: {}'.format(date))
        print('____________________________________________________________________________________________________')
        total_distance_days = 0
        total_load_days = 0
        for vehicle_id in range(data['num_vehicles']):
            index = routing.Start(vehicle_id)
            plan_output = 'Route for vehicle {}:\n'.format(vehicle_id+1)
            route_distance = 0
            route_load = 0
            while not routing.IsEnd(index):
                node_index = manager.IndexToNode(index)
                route_load += data['demands'][node_index]
                load_weight = data['demands'][node_index]
                plan_output += '{0} ({1:,} lbs) -> '.format(data['location_names'][node_index],round(load_weight))
                prevIoUs_index = index 
                index = solution.Value(routing.Nextvar(index))
                route_distance += routing.GetArcCostForVehicle(prevIoUs_index,index,vehicle_id)
            plan_output += '{0} ({1:,} lbs)\n'.format(manager.IndexToNode(index),round(route_load))
            plan_output += 'distance: {:,} mi\n'.format(route_distance)
            plan_output += 'Weight: {:,} lbs\n'.format(round(route_load))
            print(plan_output)
            total_distance_days += route_distance
            total_load_days += route_load
        total_distance += total_distance_days
        total_load += total_load_days
        print('Total distance: {:,} mi'.format(total_distance_days))
        print('Total Weight: {:,} lbs'.format(round(total_load_days)))
    print('\n')
    print('____________________________________________________________________________________________________')
    print('Totals:')
    print('Total distance: {:,} mi'.format(total_distance))
    print('Total Weight: {:,} lbs'.format(round(total_load)))




def routing_guide():
    """Solve the CVRP problem."""
    # Instantiate the data problem.
    data = routing_guide_data()

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

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


    # Create and register a transit callback.
    def distance_callback(from_index,to_index):
        """Return 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):
        """Return 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,# null capacity slack
        data['vehicle_capacities'],# vehicle maximum capacities
        True,# start cumul to zero
        'Capacity')




    #Number of locations per vehicle
    def num_of_locations(from_index):
        """Return 1 for any locations except depot."""
        # Convert from routing variable Index to user NodeIndex.
        from_node = manager.IndexToNode(from_index)
        return 1 if (from_node != 0) else 0;
    
    counter_callback_index = routing.RegisterUnaryTransitCallback(num_of_locations)
    
    routing.AddDimensionWithVehicleCapacity(
        counter_callback_index,# null slack
        [ 5000 for i in range(data['num_vehicles']) ],# maximum locations per vehicle
        True,# start cumul to zero
        'num_of_locations')



    # 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.GUIDED_LOCAL_SEARCH)
    #search_parameters.solution_limit = 100000000
    search_parameters.time_limit.FromSeconds(1)
    search_parameters.log_search = False

    # Solve the problem.
    # Print solution on console.


    solution = routing.solveWithParameters(search_parameters)
    if solution:
        print('Solution Found:')
        print_routing_guide(data,solution)
        
    else:
        print('Solution not Found!')


#data['date']
#sorted(df["Shipment Create Date"])

if __name__ == '__main__':
    routing_guide()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。