如何在Google OR工具路线优化中限制每辆车的位置数量

时间:2020-07-06 12:28:59

标签: c# or-tools

我已经实现了用于路径优化的Or-Tools。它的工作正常。我只想实现每辆车的限制位置数量的一件事。例如,每辆车最多可定义两个(2)位置。

我已经尝试实现“容量约束”,但是它不起作用。我也尝试实现SetSpanUpperBoundForVehicle函数,在这种情况下,解决方案对象为null。

这是我的代码

RoutingDimension timeDimension = routing.GetMutableDimension("Time");
            timeDimension.SetSpanUpperBoundForVehicle(2, 0);
            timeDimension.SetSpanUpperBoundForVehicle(2, 1);
            timeDimension.SetSpanUpperBoundForVehicle(2, 2);

我如何限制此数量的路线?请帮忙。

1 个答案:

答案 0 :(得分:4)

只需创建一个计数器尺寸,在每个位置添加1,然后将每辆车的容量限制为允许的最大位置数。

例如重用vrp.py示例并添加:

   # Create counter
    def counter_callback(from_index):
        """Returns 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(counter_callback)

    routing.AddDimensionWithVehicleCapacity(
        counter_callback_index,
        0,  # null slack
        [4,5,4,6],  # maximum locations per vehicle
        True,  # start cumul to zero
        'Counter')

可能的输出:

%python vrp.py
Objective: 6780
Route for vehicle 0:
 0 -> 7 -> 0
Distance of the route: 388m

Route for vehicle 1:
 0 -> 14 -> 16 -> 15 -> 3 -> 4 -> 0
Distance of the route: 2716m

Route for vehicle 2:
 0 -> 13 -> 12 -> 11 -> 1 -> 0
Distance of the route: 1804m

Route for vehicle 3:
 0 -> 5 -> 8 -> 6 -> 2 -> 10 -> 9 -> 0
Distance of the route: 1872m

Total Distance of all routes: 6780m

如您所见,路由遵守4, 5, 4, 6位置限制。

注意:对于C#语法,请参见 https://github.com/google/or-tools/blob/stable/ortools/constraint_solver/samples/VrpCapacity.cshttps://github.com/google/or-tools/blob/stable/ortools/constraint_solver/samples/VrpCapacity.csproj