问题描述
我想找到一辆车可以拥有的最短路线距离和车辆承载能力。这是一个有能力的车辆路线问题(Google OR 工具)。我想在代码之间使用 for- 循环,以便它为保存在一个位置的所有地区提供 distance_optimization。
例如:out_1 = get_sol( "banswara",1) 仅显示“banswara”区的 fos(车辆)路线。我想编写一个 for 循环,以便输出对所有地区显示相同的结果。
我的代码:
dist = distanceMetric.get_metric('haversine')
def create_data_model(df_user,no_fos):
"""Stores the data for the problem."""
data = {}
data['distance_matrix'] = dist.pairwise(df_user [['lat','lon']].to_numpy())*6373
data['num_vehicles'] = no_fos
data['depot'] = 0
return data
def print_solution(data,manager,routing,solution):
"""Prints solution on console."""
max_route_distance = 0
for vehicle_id in range(data['num_vehicles']):
index = routing.Start(vehicle_id)
plan_output = 'Route for FOS {}:\n'.format(vehicle_id)
route_distance = 0
while not routing.IsEnd(index):
plan_output += ' {} -> '.format(manager.IndexToNode(index))
prevIoUs_index = index
index = solution.Value(routing.Nextvar(index))
route_distance += routing.GetArcCostForVehicle(
prevIoUs_index,index,vehicle_id)
plan_output += '{}\n'.format(manager.IndexToNode(index))
plan_output += 'distance of the route: {}m\n'.format(route_distance)
print(plan_output)
max_route_distance = max(route_distance,max_route_distance)
print('Maximum of the route distances: {}Km'.format(max_route_distance))
def distance(x,y,data):
dis = data['distance_matrix'][x][y]
return dis
def get_routes(solution,df_user,data):
"""Get vehicle routes from a solution and store them in an array."""
# Get vehicle routes and store them in a two dimensional array whose
# i,j entry is the jth location visited by vehicle i along its route.
routes = []
#routes_dist = []
for route_nbr in range(routing.vehicles()):
index = routing.Start(route_nbr)
route = [manager.IndexToNode(index)]
while not routing.IsEnd(index):
index = solution.Value(routing.Nextvar(index))
route.append(manager.IndexToNode(index))
routes.append(route)
#routes = get_routes(solution,manager)
routes_t = pd.DataFrame(routes).T
col_to_iter = routes_t.columns
routes_t['route_info'] = routes_t.index
routes_t = pd.melt(routes_t,id_vars=['route_info'],value_vars=col_to_iter)
routes_t = routes_t.drop_duplicates(subset='value',keep="first")
df_user['value'] = df_user.index
df_user_out = pd.merge(df_user,routes_t,on="value")
df_user_out = df_user_out.sort_values(by=['variable','route_info'])
df_user_out['route_lag'] = df_user_out.groupby('variable')['value'].shift(-1).fillna(0)
df_user_out['route_lag'] = df_user_out['route_lag'].astype(np.int64)
df_user_out['route_info'] = df_user_out['route_info'].astype(np.int64)
df_user_out['dist'] = df_user_out.apply(lambda row: distance(row['route_lag'],row['value'],data),axis=1)
return df_user_out
def get_sol(sub_dist_fil,fos_cnt):
df_user_org_sub = df_user_org[(df_user_org.sub_district == sub_dist_fil) ]
df_user_org_sub.reset_index( inplace=True,drop=True)
fos_cnt=fos_cnt
data = create_data_model(df_user_org_sub,fos_cnt)
# 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,# 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)
out_df = get_routes(solution,df_user_org_sub,data)
# Print solution on console.
if solution:
print_solution(data,solution)
return out_df
out_1 = get_sol( "banswara",1)
输出如下:
FOS 0 的路由: 0 -> 14 -> 1 -> 9 -> 8 -> 7 -> 10 -> 11 -> 16 -> 13 -> 15 -> 12 -> 4 -> 3 -> 2 -> 5 -> 6 - > 0 路线距离:217m
最大路线距离:217Km
因此,上面的输出仅适用于 banswara 区,但我希望通过在其间编写 for 循环来为所有区提供相同的结果。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)