I have implemented or tools (python) for Capacited Vehicle Routing Problem and it is working. I just have another goal in mind: I want to build a callback function that gives each route an upper limit for visiting various types of nodes in a certain group of nodes given different sets of nodes. I have these set of parameters:
% we have two sets of nodes groups = [0,1]
% group 0 has nodes of type 0,1,2 and group 1 has nodes of type 3 and 4. type of nodes = [[0,1,2], [3,4]]
% I have 9 nodes and each type is : node_type = [0, 0,2,2,1,3,3,3,4] % each node belongs to a group node_group_type = [0,0,0,0,0,1,1,1,1]
% from group 0 I should have max 2 different types and from group 1 I can have max 1 type of nodes. max_visits_per_type_group = [2, 1]
visits_per_type = [0 for _ in range(len(max_visits_per_type))]
so my vehicle can contains 0,2,0,2,3,3 or 2,1,4, or 2,3,1,3,3 but It can not have 2,1,3,4 since from group 1 we have two different types as 3 and 4.
I write the call back function as:
# Define your callback function to be called after each feasible solution is found
def limit_node_visits(from_index, to_index):
from_node = manager.IndexToNode[from_index]
to_node = manager.IndexToNode[to_index]
from_node_type_group = node_group_type[from_node]
to_node_type_group = node_group_type[to_node]
from_node_type = node_type[from_node]
to_node_typ = node_type[to_node]
if (from_node_type == to_node_type):
return 0 # No cost for same type nodes
elif visits_per_type[from_node_type] >= max_visits_per_type[from_node_type]:
return routing.solver().InfeasibleCost() # Prevent further exploration of this solution
else:
visits_per_type[from_node_type_group] += 1
return 1 # Increment the visit count for the from_node_type
limit_node_visits_index = routing.RegisterUnaryTransitCallback(limit_node_visits)
routing.AddDimensionWithVehicleCapacity(
limit_node_visits_index,
0,
max_visits_per_type_group,
True,
'node_visit')
However, the code doesn't work and it crashes. It seems that there is something wrong with max_visits_per_type_group in the routing.AddDimensionWithVehicleCapacity() function. I am not sure if I defined the call_back function properly as well. I will appreciate if you help me to write these two functions properly.