or-tools solves the problem of vrpstw

25 views
Skip to first unread message

qingxia tang

unread,
Jul 24, 2024, 8:37:39 PM (24 hours ago) Jul 24
to or-tools-discuss
VRP has a soft time window problem, the goal is to minimize the total cost, cost = distance cost + early arrival and late penalty cost, early arrival cost =(customer point time window start time - vehicle arrival time)* penalty factor, late arrival cost =(vehicle arrival time - customer point time window end time)* penalty factor, the target cost calculation is incorrect. Error :root: Error in callback :' solver 'object has no property' value '. How do I get the vehicle arrival time? or how to implement OR-Tools to solve vrp soft time window problem? Here's my code

def time_and_cost_callback(from_index, to_index):
try:
from_node = manager.IndexToNode(from_index)
to_node = manager.IndexToNode(to_index)
distance = data["time_matrix"][from_node][to_node]

# 获取CumulVar的值
from_time_var = time_dimension.CumulVar(from_index)
to_time_var = time_dimension.CumulVar(to_index)

# 获取solver
solver = routing.solver()

# 计算实际的时间值
from_time_value = solver.Value(from_time_var)
to_time_value = solver.Value(to_time_var)
travel_time = distance + from_time_value

start_tw, end_tw = data['time_windows'][to_node]
early_penalty = max(0, start_tw - travel_time) * 5
late_penalty = max(0, travel_time - end_tw) * 20

cost = distance + early_penalty + late_penalty
logging.debug(f"Cost from {from_node} to {to_node}: {cost}")
return cost
except Exception as e:
logging.error(f"Error in callback: {e}")
return 0
manager = pywrapcp.RoutingIndexManager(
len(data["time_matrix"]), data["num_vehicles"], data["depot"]
)
print(f"number of nodes: {manager.GetNumberOfNodes()}")
print(f"number of vehicles: {manager.GetNumberOfVehicles()}")
print(f"depot: {data['depot']}")

routing = pywrapcp.RoutingModel(manager)

# demand_callback_index = routing.RegisterUnaryTransitCallback(demand_callback)
# routing.AddDimensionWithVehicleCapacity(
# demand_callback_index,
# 0, # null capacity slack
# data["vehicle_capacities"], # vehicle maximum capacities
# True, # start cumul to zero
# "Capacity"
# )

# 注册回调函数并添加约束
transit_callback_index = routing.RegisterTransitCallback(time_and_cost_callback)
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

# Add Time Window constraint
time1 = "Time"
routing.AddDimension(
transit_callback_index,
10000000, # allow waiting time
# so 3-20 400 3-50 250 5-20 200 5-50 300
# hom 3-20 1150 3-50 1500 5-20 850 5-50 1150
# ran 3-20 700 3-50 350 5-20 5-50 700
100000000, # maximum time per vehicle
False, # Don't force start cumul to zero.
time1
)
time_dimension = routing.GetDimensionOrDie(time1)
# 只添加软时间窗惩罚,不使用 SetRange
for location_idx, time_window in enumerate(data["time_windows"]):
index = manager.NodeToIndex(location_idx)
# 设置软下界:如果早到,则产生惩罚
time_dimension.SetCumulVarSoftLowerBound(index, time_window[0], 1)
# 设置软上界:如果晚到,则产生惩罚
time_dimension.SetCumulVarSoftUpperBound(index, time_window[1], 4)

# 确保每个客户只能被一辆车服务一次
for node in range(1, manager.GetNumberOfNodes()):
index = manager.NodeToIndex(node)
time_dimension.CumulVar(index).SetMin(1)

for vehicle_id in range(data["num_vehicles"]):
start_index = routing.Start(vehicle_id)
routing.AddVariableMinimizedByFinalizer(time_dimension.CumulVar(start_index))
end_index = routing.End(vehicle_id)
routing.AddVariableMinimizedByFinalizer(time_dimension.CumulVar(end_index))
# Ensure each vehicle visits at least one node
routing.AddVariableMinimizedByFinalizer(routing.ActiveVar(start_index))

# Solve the problem with search parameters
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy = routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC
# search_parameters.local_search_metaheuristic = routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH
# search_parameters.time_limit.seconds = 1200 # 增加求解时间限制


# Solve the problem.
print("Start solving...")
solution = routing.SolveWithParameters(search_parameters)
Reply all
Reply to author
Forward
0 new messages