使用TimeWindows矩阵时,如何解决Google Or-Tools解决方案问题?

时间:2019-05-29 14:51:07

标签: java spring or-tools vehicle-routing

我在timeWindows中使用Google Or-Tools VehicleRoutingProblem, 当我尝试使用“时间窗口”时,解决方案要么变为零,要么出现错误

timeDimension.cumulVar (index) .setRange (data.timeWindows [i] [0], data.timeWindows [i] [1]); 线。我花费了所有双精度到长整数的值,然后传输了所有数据。因为所有代码都是用C ++编写的,所以我无法遵循代码。谁能帮忙。

我添加了测试代码和两个Matix文件。

https://drive.google.com/file/d/1lKYQep_yppJP3rhY_n-vZIvKJDbcrfpj/view?usp=sharing distance and duration matrix

https://drive.google.com/file/d/13K6jrnG4QIL1FQw8UxlaWA3rn4RoX7fo/view?usp=sharing time windows


import com.google.ortools.constraintsolver.*;
import com.google.protobuf.Duration;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.logging.Logger;

@RunWith(SpringRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class OrToolsTests3 {


    private static long[][] data;
    private static long[][] timeWindows;
    private static final Logger logger = Logger.getLogger(OrToolsTests3.class.getName());


    static {
        System.loadLibrary("jniortools");
    }


    // [START data_model]
    class DataModel {
        public final long[][] durationMatrix = data;
        public final long[][] timeWindows = OrToolsTests3.timeWindows;
        public final int vehicleNumber = 1;
        public final int depot = 0;
    }
    // [END data_model]

    // [START solution_printer]
    /// @brief Print the solution.
    void printSolution(
            DataModel data, RoutingModel routing, RoutingIndexManager manager, Assignment solution) {
        RoutingDimension timeDimension = routing.getMutableDimension("Time");
        long totalTime = 0;
        for (int i = 0; i < data.vehicleNumber; ++i) {
            long index = routing.start(i);
            logger.info("Route for Vehicle " + i + ":");
            String route = "";
            while (!routing.isEnd(index)) {
                IntVar timeVar = timeDimension.cumulVar(index);
                route += manager.indexToNode(index) + " Time(" + solution.min(timeVar) + ","
                        + solution.max(timeVar) + ") -> ";
                index = solution.value(routing.nextVar(index));
            }
            IntVar timeVar = timeDimension.cumulVar(index);
            route += manager.indexToNode(index) + " Time(" + solution.min(timeVar) + ","
                    + solution.max(timeVar) + ")";
            logger.info(route);
            logger.info("Time of the route: " + solution.min(timeVar) + "min");
            totalTime += solution.min(timeVar);
        }
        logger.info("Total time of all routes: " + totalTime + "min");
    }

    // [END solution_printer]
    @Test
    public void main() throws Exception {
        // Instantiate the data problem.
        // [START data]
        final DataModel data = new DataModel();
        // [END data]

        // Create Routing Index Manager
        // [START index_manager]
        RoutingIndexManager manager =
                new RoutingIndexManager(data.durationMatrix.length, data.vehicleNumber, data.depot);
        // [END index_manager]

        // Create Routing Model.
        // [START routing_model]
        RoutingModel routing = new RoutingModel(manager);
        // [END routing_model]

        // Create and register a transit callback.
        // [START transit_callback]
        final int transitCallbackIndex =
                routing.registerTransitCallback((long fromIndex, long toIndex) -> {
                    // Convert from routing variable Index to user NodeIndex.
                    int fromNode = manager.indexToNode(fromIndex);
                    int toNode = manager.indexToNode(toIndex);
                    return data.durationMatrix[fromNode][toNode];
                });
        // [END transit_callback]

        // Define cost of each arc.
        // [START arc_cost]
        routing.setArcCostEvaluatorOfAllVehicles(transitCallbackIndex);
        // [END arc_cost]

        // Add Time constraint.
        // [START time_constraint]
        routing.addDimension(transitCallbackIndex, // transit callback
                30, // allow waiting time
                30, // vehicle maximum capacities
                false, // start cumul to zero
                "Time");
        RoutingDimension timeDimension = routing.getMutableDimension("Time");
        // Add time window constraints for each location except depot.
        for (int i = 1; i < data.timeWindows.length; ++i) {
            long index = manager.nodeToIndex(i);
            timeDimension.cumulVar(index).setRange(data.timeWindows[i][0], data.timeWindows[i][1]);
        }
        // Add time window constraints for each vehicle start node.
        for (int i = 0; i < data.vehicleNumber; ++i) {
            long index = routing.start(i);
            timeDimension.cumulVar(index).setRange(data.timeWindows[0][0], data.timeWindows[0][1]);
        }
        // [END time_constraint]

        // Instantiate route start and end times to produce feasible times.
        // [START depot_start_end_times]
        for (int i = 0; i < data.vehicleNumber; ++i) {
            routing.addVariableMinimizedByFinalizer(timeDimension.cumulVar(routing.start(i)));
            routing.addVariableMinimizedByFinalizer(timeDimension.cumulVar(routing.end(i)));
        }
        // [END depot_start_end_times]

        // Setting first solution heuristic.
        // [START parameters]
        RoutingSearchParameters searchParameters =
                main.defaultRoutingSearchParameters()
                        .toBuilder()
                        .setTimeLimit(Duration.newBuilder().setSeconds(5).build())
                        .setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
                        .build();
        // [END parameters]

        // Solve the problem.
        // [START solve]
        Assignment solution = routing.solveWithParameters(searchParameters);
        // [END solve]

        // Print solution on console.
        // [START print_solution]
        printSolution(data, routing, manager, solution);
        // [END print_solution]
    }


}

1 个答案:

答案 0 :(得分:0)

您的方法是正确的。我一直在为时间窗而苦苦挣扎,而且我认为您解决它们的方式不对。

确保等待时间(在routing.addDimension时设置)不小于两个固定时间窗口之间的时间。

假设您的位置为9,而下一个位置固定为10,则等待时间30不足以解决问题