Python Google ortools-带加油的mVRP

Python Google ortools-带加油的mVRP,python,or-tools,Python,Or Tools,我正试图用python在几个加油站(仅用于补给)用加油解决mVRP问题。我找到了这个: 我引用了github的代码,但代码中存在一些问题 1) 我遵循了python中的方法(从上面的github代码) (github代码) 问题 1) 如果我在fuel\u维度的SetValue的for循环中使用idx=manager.NodeToIndex(I),则会产生如下错误: Process finished with exit code -1073741819 (0xC0000005) 如果我使用I而

我正试图用python在几个加油站(仅用于补给)用加油解决mVRP问题。我找到了这个:

我引用了github的代码,但代码中存在一些问题

1) 我遵循了python中的方法(从上面的github代码)

(github代码)

问题

1) 如果我在
fuel\u维度的
SetValue
的for循环中使用
idx=manager.NodeToIndex(I)
,则会产生如下错误:

Process finished with exit code -1073741819 (0xC0000005)
如果我使用
I
而不是
idx
(从
NodeToIndex
),则不会发生错误。有人能解释一下吗

2) 当我打印结果时,结果(尤其是燃料维度)似乎很奇怪。比如说,

结果

8 (fuel: 0) ->  9 (fuel: 0) ->  7 (fuel: 3) ->  11 (fuel: 2) ->  6 (fuel: 4) ->  4 (fuel: 3) ->  5 (fuel: 1) ->  10 (fuel: 0) ->  3 (fuel: 2) ->  2 (fuel: 1) ->  1 (fuel: 0) -> 0
简言之,节点0是虚拟仓库,节点8是代理的指定起始节点。任务节点:[1,2,3,4,5,6,7],站点节点:[8,9,10,11]。特别是,节点8和9是同一个站点,但我复制了它以允许重新访问加油,10和11也是如此。节点之间的距离与1相同,我假设曼哈顿距离

问题是加油站的燃油不是最大燃油(这里是4)。此外,第二个转换(9(燃料:0)->7(燃料:3))应该消耗燃料1,但它不消耗燃料

更糟糕的是转换(11(燃料:2)->6(燃料:4)->4(燃料:3))是完全错误的

上述问题的索引图如下所示:

Process finished with exit code -1073741819 (0xC0000005)

下面是整个代码:

from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

def print_solution(data, manager, routing, solution):    
    max_route_distance = 0
    fuel_dimension = routing.GetDimensionOrDie('Fuel')

    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
        while not routing.IsEnd(index):
            fuel_var = fuel_dimension.CumulVar(index)

            plan_output += ' {} (fuel: {}) -> '.format(manager.IndexToNode(index), solution.Value(fuel_var))
            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)

        max_route_distance = max(route_distance, max_route_distance)


def manhattan_distance(position_1, position_2):
    return (abs(position_1[0] - position_2[0]) +
        abs(position_1[1] - position_2[1]))

def main():
    # Create the routing index manager.
    manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']),
                                       data['num_vehicles'],
                                       data['vStart'],
                                       data['vEnd'])

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

    def fuel_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 -manhattan_distance(data['locations'][from_node], data['locations'][to_node])

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

    fuel_callback_index = routing.RegisterTransitCallback(fuel_callback)
    routing.AddDimension(
        fuel_callback_index,
        data['MFuel'],
        data['MFuel'],
        False,
        'Fuel'
    )

    fuel_dimension = routing.GetDimensionOrDie('Fuel')

    for i in range(routing.Size()):
        if (i not in data['vStation']) or routing.IsStart(i):
            idx = manager.NodeToIndex(i)

            fuel_dimension.SlackVar(i).SetValue(0)

        routing.AddVariableMinimizedByFinalizer(fuel_dimension.CumulVar(i))

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

if __name__ == '__main__':
    main()
谢谢,

此外,下面是数据代码

import numpy as np
from scipy.spatial import distance
np.random.seed(0)

# problem settings
gridX, gridY = 10, 10
N_vehicles = 5
MFuel = 10

coord_stations = [(1,1), (1,4), (1,7), (4,2), (4,5), (4,8), (7,1), (8,4), (4,2), (7,7)]
coord_starts = [(1,1),(1,7),(4,2),(4,8),(8,4)]

coord_srfs = [(x,y) for x in range(gridX) for y in range(gridY) if (x,y) not in coord_stations]

# dummies
dummy_depot = [(0,0)]
N_dummy = 5
N_dummySta = N_dummy * len(coord_stations)


# prerequisite
MFuels = [MFuel] * N_vehicles
N_v = 1 + len(coord_srfs) + N_dummySta

# make map w/ all vertices
map = {}
idx = {}
coord2vertex = {}
for (x,y) in [(x,y) for x in range(gridX) for y in range(gridY)]:
    coord2vertex[(x,y)] = []

map[0] = dummy_depot[0]
idx['depot'] = 0

srfs_idx = []
for i in range(len(coord_srfs)):
    map[i+1] = coord_srfs[i]
    srfs_idx.append(i+1)
    coord2vertex[coord_srfs[i]].append(i+1)
idx['surfaces'] = srfs_idx

stas_idx = []
for i in range(N_dummySta):
    sta_idx = i//N_dummy
    map[i+idx['surfaces'][-1]+1] = coord_stations[sta_idx]
    stas_idx.append(i+idx['surfaces'][-1]+1)
    coord2vertex[coord_stations[sta_idx]].append(i+idx['surfaces'][-1]+1)
idx['stations'] = stas_idx

# make distance matrix w/ all vertices
dist_mat = np.zeros((N_v, N_v), dtype=int)
for i in range(N_v):
    for j in range(N_v):
        if i == 0 or j == 0:
            dist_mat[i,j] = 0
        else:
            if i == j:
                dist_mat[i,j] = 0
            else:
                dist_mat[i,j] = sum(abs(np.array(map[j])-np.array(map[i])))
distance_matrix = dist_mat.tolist()

v_starts = [coord2vertex[coord][0] for coord in coord_starts]

data = dict()
data['distance_matrix'] = distance_matrix
data['num_vehicles'] = N_vehicles
data['vStart'] = v_starts
data['vEnd'] = [0] * N_vehicles
data['MFuel'] = MFuel
data['vStation'] = idx['stations']
data['vSrf'] = idx['surfaces']
data['locations'] = list(map.values())
data['num_locations'] = len(data['locations'])

print('Problem is generated.\n# of vehicles: {} (w/ capacities: {})\n# of tasks: {} (w/ locations: {} & demands: {})\n'.format(N_vehicles, v_capas, N_tasks, coord_tasks, t_demands))
谢谢大家!

作为盲修复(由于您没有提供
数据进行测试,因此已编辑),我将重写:

#添加燃油限制。
维度名称='燃料'
def fuel_回调(从_索引到_索引):
“”“返回两个节点之间的距离。”“”
#将路由变量索引转换为距离矩阵节点索引。
from_node=manager.IndexToNode(from_index)
to_node=manager.IndexToNode(to_index)
返回-曼哈顿距离(数据['locations'][从节点],数据['locations'][到节点])
fuel\u callback\u index=routing.RegisterTransitCallback(fuel\u callback)
routing.AddDimension(
燃料指数,
数据['MFuel'],
数据['MFuel'],
假,,
维度(名称)
fuel\u dimension=routing.GetDimensionOrde(维度名称)
对于范围内的i(len(数据['distance_matrix']):
如果(i不在数据['vStation']中)和
(i不在数据['vStart']中)和
(我不在数据['vEnd']中):
idx=manager.NodeToIndex(i)
燃料尺寸SlackVar(idx).设定值(0)
路由.AddVariableMinimizedByFinalizer(fuel_dimension.CumulVar(idx))
对于曼哈顿,如果您有浮点值,请注意
int()
cast!:

def曼哈顿_距离(位置_1,位置_2):
返回整数(abs(位置1[0]-位置2[0])+
abs(位置_1[1]-位置_2[1]))

感谢您使用或使用工具,今天下午(巴黎时间)我将试着看一看在这里发布…IIRC NodeToIndex没有定义起点和终点,因为在VRP的情况下,车辆段内部是重复的,因此每辆车都有自己的起点/终点位置,但这意味着这不是一个双交叉点,而是一个1->N关系。你能给我们提供数据对象吗?你还必须将所有距离都设置为整数!否则,SWIG包装器会从Python浮动值转换为C++整数。@ Mizux,谢谢你的友好回复,抱歉迟到。我用我的数据代码编辑了上面的内容。
import numpy as np
from scipy.spatial import distance
np.random.seed(0)

# problem settings
gridX, gridY = 10, 10
N_vehicles = 5
MFuel = 10

coord_stations = [(1,1), (1,4), (1,7), (4,2), (4,5), (4,8), (7,1), (8,4), (4,2), (7,7)]
coord_starts = [(1,1),(1,7),(4,2),(4,8),(8,4)]

coord_srfs = [(x,y) for x in range(gridX) for y in range(gridY) if (x,y) not in coord_stations]

# dummies
dummy_depot = [(0,0)]
N_dummy = 5
N_dummySta = N_dummy * len(coord_stations)


# prerequisite
MFuels = [MFuel] * N_vehicles
N_v = 1 + len(coord_srfs) + N_dummySta

# make map w/ all vertices
map = {}
idx = {}
coord2vertex = {}
for (x,y) in [(x,y) for x in range(gridX) for y in range(gridY)]:
    coord2vertex[(x,y)] = []

map[0] = dummy_depot[0]
idx['depot'] = 0

srfs_idx = []
for i in range(len(coord_srfs)):
    map[i+1] = coord_srfs[i]
    srfs_idx.append(i+1)
    coord2vertex[coord_srfs[i]].append(i+1)
idx['surfaces'] = srfs_idx

stas_idx = []
for i in range(N_dummySta):
    sta_idx = i//N_dummy
    map[i+idx['surfaces'][-1]+1] = coord_stations[sta_idx]
    stas_idx.append(i+idx['surfaces'][-1]+1)
    coord2vertex[coord_stations[sta_idx]].append(i+idx['surfaces'][-1]+1)
idx['stations'] = stas_idx

# make distance matrix w/ all vertices
dist_mat = np.zeros((N_v, N_v), dtype=int)
for i in range(N_v):
    for j in range(N_v):
        if i == 0 or j == 0:
            dist_mat[i,j] = 0
        else:
            if i == j:
                dist_mat[i,j] = 0
            else:
                dist_mat[i,j] = sum(abs(np.array(map[j])-np.array(map[i])))
distance_matrix = dist_mat.tolist()

v_starts = [coord2vertex[coord][0] for coord in coord_starts]

data = dict()
data['distance_matrix'] = distance_matrix
data['num_vehicles'] = N_vehicles
data['vStart'] = v_starts
data['vEnd'] = [0] * N_vehicles
data['MFuel'] = MFuel
data['vStation'] = idx['stations']
data['vSrf'] = idx['surfaces']
data['locations'] = list(map.values())
data['num_locations'] = len(data['locations'])

print('Problem is generated.\n# of vehicles: {} (w/ capacities: {})\n# of tasks: {} (w/ locations: {} & demands: {})\n'.format(N_vehicles, v_capas, N_tasks, coord_tasks, t_demands))