Search code examples
pythonlogicor-toolsvehicle-routing

How do I make demand_callback consider a variable that depends on to_node in ortools?


I'm solving a vehicle routing problem using google ortools, and i need the demand_calback function take into consideration the time_visits (that depends on from_node and it's working) and the displacement between two nodes (that depends on from_node and to_node).

The problem is that the demand_callback function doesn't accept another parameter besides from_node, so i can't call to_node (and as consequence i can't consider the displacement time).

My code is:

# Add Capacity constraint.
def demand_callback(from_index):
   """Returns the demand of the node."""
   # Convert from routing variable Index to demands NodeIndex.
   from_node = manager.IndexToNode(from_index)
   '''Creates callback to get demands at each location.'''
   _time_visits = data['time_visits']
   return _time_visits[from_node] 

And I would like the code to look like this:

 def demand_callback(from_index, to_index):
    """Returns the demand of the node."""
    # Convert from routing variable Index to demands NodeIndex.
    from_node = manager.IndexToNode(from_index)
    to_node = manager.IndexToNode(to_index)

    '''Creates callback to get demands at each location.'''
    _time_visits = data['time_visits']
    _displacements = data['matrix_displacement'][from_node]

    result = _time_visits[from_node] + _displacements[from_node][to_node]
    return result

Solution

  • In the example, for demand dimension we advertise the use of unary callback.
    Here, it seems you want to use a regular callback...

    def demand_callback(from_index, to_index):
        """Returns the demand of the node."""
        # Convert from routing variable Index to demands NodeIndex.
        from_node = manager.IndexToNode(from_index)
        to_node = manager.IndexToNode(to_index)
    
        '''Creates callback to get demands at each location.'''
        _time_visits = data['time_visits']
        _displacements = data['matrix_displacement'][from_node]
    
        result = _time_visits[from_node] + _displacements[from_node][to_node]
        return result
    

    Then register it using RegisterTransitCallback() instead of RegisterUnaryTransitCallback().

    demand_callback_index = routing.RegisterTransitCallback(demand_callback)