问题描述
我正在尝试使用 ortools 解决无能力的取货和送货问题。每辆车的容量为 1,如果交付/作业的数量 > 车辆数量,必须至少使用一次。当然,必须有一个解决方案,但我无法找到它。我已经尝试了 here 描述的方法,如下所示:
# 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)
但是,对于可重现的示例(下面的完整代码),总是有一种车辆根本没有被使用(其他示例则有更多车辆)。如何强制使用每辆车并仍然能够找到至少一个可行的解决方案?也许通过改变搜索方法?
可重现的代码:
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,920,342,1],[641,505,663,643,504,639,1556,638,397,644,641],[331,623,334,1,329,1188,110,333,111,1187,330],[360,358,1007,359,575,574,1006,361],[3,335,6,917,5,345,4],330,[2,923,340,922,2],[920,1242,921],3],[342,341],920],[1,361,4,921,341,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]
data['demands'] = [0,-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,# 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,# 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,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,assignment)
if __name__ == '__main__':
main()
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)