Search code examples
pythonpython-3.xor-tools

Google OR-Tools: Different cost for same node base on position in route


I have a list of costs for each node based on the position of a node in a route. The depot is positioned at 0.

costs = [
    {"part": 0, "final": 0},
    {"part": 2, "final": 3},
    {"part": 4, "final": 2},
    {"part": 1, "final": 3},
]

It means if node 1 is part of a route, it will cost only 2, but if it is the final destination, it will cost 3.

So the optimized route should be: 0 -> 1 -> 3 -> 2, which will cost part of 1, part of 3, and final of 2, total cost is 5.

Currently, I can not find a proper way to set a dynamic cost for a node based on its position in a route. Any idea is appreciated.

I'm using Python with the Google OR-Tools package.

Many thanks.


Solution

  • I found a simple solution, set the cost from every node to the depot equal to the final cost, and the cost from every node to each other equal to its part cost.

    Here is my cost matrix that solves my problem:

    [0,0,0,0]
    [3,0,2,2]
    [2,4,0,4]
    [3,1,1,0]
    

    So a node will cost its final price if the next node of the trip is the depot, and part price if next node is another node.