粒子群算法+Split 求解异构车辆路径规划问题
天公爱作美,清风皓月任我飞
信息传递
- python实现6种智能算法求解CVRP问题
- python实现7种智能算法求解MDVRP问题
- python实现7种智能算法求解MDVRPTW问题
- Python版MDHFVRPTW问题智能求解算法代码【TS算法】
- Python版MDHFVRPTW问题智能求解算法代码【SA算法】
- Python版MDHFVRPTW问题智能求解算法代码【GA算法】
- Python版MDHFVRPTW问题智能求解算法代码【DPSO算法】
- Python版MDHFVRPTW问题智能求解算法代码【DE算法】
- Python版MDHFVRPTW问题智能求解算法代码【ACO算法】
- Python版HVRP问题智能求解算法代码【GA算法】
- Python版HVRP问题智能求解算法代码【DPSO算法】
1. 适用场景
- 求解HVRP或MDHVRP
- 多车辆类型
- 车辆容量不小于需求节点最大需求
- (多)车辆基地
- 车场车辆总数满足实际需求
2. 求解效果
(1)收敛曲线
(2)车辆路径
3. 代码分析
Christian Prins给出的HVRP的Split方法过程如下:
以上算法在搜索过程中需求节点的备选标签规模会非常大,占用内存且降低搜索效率,因此采用了帕累托思想来遗传非支配解(19行~21行)。为了进一步控制备选标签数量,本期文章还附加实现了通过剩余容量与剩余需求来判断是否产生新的备选标签,提前避免产生不可行的标签。尽管如此,当考虑的异构车辆类型较多、需求点规模较大时,求解效率依然较低(代码结构、python特性、硬件环境)。所以本期文章进一步加入了最大标签数量参数来控制每个需求节点的备选标签规模,通过调节该参数实现速度与质量的相对均衡。
4. 数据格式
这里采用solomon开源数据对算法进行测试,数据文件结构如下图所示,共100个需求点,3个车场,3类车辆,以.csv文件储存数据。
demand.csv文件内容如下图,其中第一行为标题栏,节点id从0开始递增编号。
depot.csv文件内容如下图,其中第一行为标题栏,依次为:车场id,车场平面x坐标,车场平面y坐标,车辆类型,车辆装载量,车辆数量,固定成本,单位里程运输成本。
5. 分步实现
(1)代码整体架构
(2)数据结构
定义Sol()类,Demand()类,Vehicle()类,Model()类,其属性如下表:
- Sol()类,表示一个可行解
属性 | 描述 |
---|---|
node_id_list | 需求节点id有序排列集合 |
obj | 优化目标值 |
route_list | 车辆路径集合,对应MDVRPTW的解 |
- Demand()类,表示一个需求节点
属性 | 描述 |
---|---|
id | 物理节点id,需唯一 |
x_coord | 物理节点x坐标 |
y_coord | 物理节点y坐标 |
demand | 物理节点需求 |
- Vehicle()类,表示一个车队节点
属性 | 描述 |
---|---|
depot_id | 车辆归属的车场节点节点id,需唯一 |
x_coord | 车辆归属车场节点x坐标 |
y_coord | 车辆归属车场节点y坐标 |
type | 车辆类型 |
capacity | 车辆容量 |
free_speed | 车辆运营速度 |
fixed_cost | 车辆固定成本 |
variable_cost | 车辆变动成本 |
- Model()类,存储算法参数
属性 | 描述 |
---|---|
best_sol | 全局最优解,值类型为Sol() |
demand_dict | 需求节点集合(字典),值类型为Demand() |
vehicle_dict | 车队集合(字典),值类型为Vehicle() |
vehicle_type_list | 车队id集合 |
demand_id_list | 需求节点id集合 |
sol_list | 种群,值类型为Sol() |
distance_matrix | 节点距离矩阵 |
number_of_demands | 需求节点数量 |
pl | 个体历史最优解 |
pg | 种群历史最优解 |
v | 粒子更新速度 |
Vmax | 最大速度 |
w | 惯性权重 |
c1 | 学习因子 |
c2 | 学习因子 |
popsize | 种群规模 |
(3)数据读取
def readCSVFile(demand_file,depot_file,model):
with open(demand_file,'r') as f:
demand_reader=csv.DictReader(f)
for row in demand_reader:
demand = Demand()
demand.id = int(row['id'])
demand.x_coord = float(row['x_coord'])
demand.y_coord = float(row['y_coord'])
demand.demand = float(row['demand'])
model.demand_dict[demand.id] = demand
model.demand_id_list.append(demand.id)
model.number_of_demands=len(model.demand_id_list)
with open(depot_file, 'r') as f:
depot_reader = csv.DictReader(f)
for row in depot_reader:
vehicle = Vehicle()
vehicle.depot_id = row['depot_id']
vehicle.x_coord = float(row['x_coord'])
vehicle.y_coord = float(row['y_coord'])
vehicle.type = row['vehicle_type']
vehicle.capacity=float(row['vehicle_capacity'])
vehicle.numbers=float(row['number_of_vehicle'])
vehicle.fixed_cost=float(row['fixed_cost'])
vehicle.variable_cost=float(row['variable_cost'])
model.vehicle_dict[vehicle.type] = vehicle
model.vehicle_type_list.append(vehicle.type)
(4)距离计算
def calDistanceMatrix(model):
for i in range(len(model.demand_id_list)):
from_node_id = model.demand_id_list[i]
for j in range(i + 1, len(model.demand_id_list)):
to_node_id = model.demand_id_list[j]
dist = math.sqrt((model.demand_dict[from_node_id].x_coord - model.demand_dict[to_node_id].x_coord) ** 2
+ (model.demand_dict[from_node_id].y_coord - model.demand_dict[to_node_id].y_coord) ** 2)
model.distance_matrix[from_node_id, to_node_id] = int(dist)
model.distance_matrix[to_node_id, from_node_id] = int(dist)
for _, vehicle in model.vehicle_dict.items():
dist = math.sqrt((model.demand_dict[from_node_id].x_coord - vehicle.x_coord) ** 2
+ (model.demand_dict[from_node_id].y_coord - vehicle.y_coord) ** 2)
model.distance_matrix[from_node_id, vehicle.type] = int(dist)
model.distance_matrix[vehicle.type, from_node_id] = int(dist)
(5)路径成本计算
def calTravelCost(route_list,model):
obj=0
for route in route_list:
vehicle=model.vehicle_dict[route[0]]
distance=0
fixed_cost=vehicle.fixed_cost
variable_cost=vehicle.variable_cost
for i in range(len(route) - 1):
from_node = route[i]
to_node = route[i + 1]
distance += model.distance_matrix[from_node, to_node]
obj += fixed_cost + distance * variable_cost
return obj
(6)目标函数计算
def calObj(node_id_list,model):
vehicle_routes = splitRoutes(node_id_list, model)
if vehicle_routes:
return calTravelCost(vehicle_routes,model),vehicle_routes
else:
return 10**9,None
(7)初始解
def genInitialSol(model):
demand_id_list=copy.deepcopy(model.demand_id_list)
best_sol=Sol()
best_sol.obj=float('inf')
for i in range(model.popsize):
seed = int(random.randint(0, 10))
random.seed(seed)
random.shuffle(demand_id_list)
sol=Sol()
sol.node_id_list= copy.deepcopy(demand_id_list)
sol.obj,sol.route_list=calObj(sol.node_id_list,model)
model.sol_list.append(sol)
model.v.append([model.Vmax]*len(model.demand_id_list))
model.pl.append(sol)
if sol.obj<best_sol.obj:
best_sol=copy.deepcopy(sol)
model.best_sol=best_sol
model.pg=best_sol.node_id_list
(8)位置更新
def updatePosition(model):
w=model.w
c1=model.c1
c2=model.c2
pg = model.pg
for id,sol in enumerate(model.sol_list):
x=sol.node_id_list
v=model.v[id]
pl=model.pl[id].node_id_list
r1=random.random()
r2=random.random()
new_v=[]
for i in range(len(model.demand_id_list)):
v_=w*v[i]+c1*r1*(pl[i]-x[i])+c2*r2*(pg[i]-x[i])
if v_>0:
new_v.append(min(v_,model.Vmax))
else:
new_v.append(max(v_,-model.Vmax))
new_x=[min(int(x[i]+new_v[i]),len(model.demand_id_list)-1) for i in range(len(model.demand_id_list)) ]
new_x=adjustRoutes(new_x,model)
model.v[id]=new_v
new_x_obj,new_x_routes=calObj(new_x,model)
if new_x_obj<model.pl[id].obj:
model.pl[id].node_id_list=copy.deepcopy(new_x)
model.pl[id].obj=new_x_obj
model.pl[id].route_list=new_x_routes
if new_x_obj<model.best_sol.obj:
model.best_sol.obj=copy.deepcopy(new_x_obj)
model.best_sol.node_id_list=copy.deepcopy(new_x)
model.best_sol.route_list=copy.deepcopy(new_x_routes)
model.pg=copy.deepcopy(new_x)
model.sol_list[id].node_id_list = copy.deepcopy(new_x)
model.sol_list[id].obj = copy.deepcopy(new_x_obj)
model.sol_list[id].route_list = copy.deepcopy(new_x_routes)
(9)路径提取
def extractRoutes(V,node_id_list,model):
route_list = []
min_obj=float('inf')
pred_label_id=None
v_type=None
# search the min cost label of last node of the node_id_list
for label in V[model.number_of_demands-1]:
if label[3]<=min_obj:
min_obj=label[3]
pred_label_id=label[1]
v_type=label[2]
# generate routes by pred_label_id
route=[node_id_list[-1]]
indexs=list(range(0,model.number_of_demands))[::-1]
start=1
while pred_label_id!=1:
for i in indexs[start:]:
stop=False
for label in V[i]:
if label[0]==pred_label_id:
stop=True
pred_label_id=label[1]
start=i
v_type_=label[2]
break
if not stop:
route.insert(0,node_id_list[i])
else:
route.insert(0,v_type)
route.append(v_type)
route_list.append(route)
route=[node_id_list[i]]
v_type=v_type_
route.insert(0,v_type)
route.append(v_type)
route_list.append(route)
return route_list
(10)绘制收敛曲线
def plotObj(obj_list):
plt.rcParams['font.sans-serif'] = ['SimHei'] #show chinese
plt.rcParams['axes.unicode_minus'] = False # Show minus sign
plt.plot(np.arange(1,len(obj_list)+1),obj_list)
plt.xlabel('Iterations')
plt.ylabel('Obj Value')
plt.grid()
plt.xlim(1,len(obj_list)+1)
plt.show()
(11)绘制车辆路径
def plotRoutes(model):
for route in model.best_sol.route_list:
x_coord=[model.vehicle_dict[route[0]].x_coord]
y_coord=[model.vehicle_dict[route[0]].y_coord]
for node_id in route[1:-1]:
x_coord.append(model.demand_dict[node_id].x_coord)
y_coord.append(model.demand_dict[node_id].y_coord)
x_coord.append(model.vehicle_dict[route[-1]].x_coord)
y_coord.append(model.vehicle_dict[route[-1]].y_coord)
plt.grid()
if route[0]=='v1':
plt.plot(x_coord,y_coord,marker='o',color='black',linewidth=0.5,markersize=5)
elif route[0]=='v2':
plt.plot(x_coord,y_coord,marker='o',color='orange',linewidth=0.5,markersize=5)
elif route[0]=='v3':
plt.plot(x_coord,y_coord,marker='o',color='r',linewidth=0.5,markersize=5)
else:
plt.plot(x_coord, y_coord, marker='o', color='b', linewidth=0.5, markersize=5)
plt.xlabel('x_coord')
plt.ylabel('y_coord')
plt.show()
(12)输出结果
def outPut(model):
work=xlsxwriter.Workbook('result.xlsx')
worksheet=work.add_worksheet()
worksheet.write(0, 0, 'obj')
worksheet.write(0, 1,model.best_sol.obj)
worksheet.write(1, 0,'vehicleID')
worksheet.write(1, 1,'depotID')
worksheet.write(1, 2, 'vehicleType')
worksheet.write(1, 3,'route')
for row,route in enumerate(model.best_sol.route_list):
worksheet.write(row+2,0,str(row+1))
depot_id=model.vehicle_dict[route[0]].depot_id
worksheet.write(row+2,1,depot_id)
worksheet.write(row+2,2,route[0])
r=[str(i)for i in route]
worksheet.write(row+2,3, '-'.join(r))
work.close()
(13)主函数
def run(demand_file,depot_file,epochs,popsize,Vmax,v_cap,w,c1,c2,max_labels):
"""
:param demand_file: demand 文件路径
:param depot_file: depot 文件路径
:param epochs: 迭代次数
:param popsize: 邻域规模
:param v_cap: 车辆容量
:param Vmax :最大速度
:param w: 惯性权重
:param c1:学习因子
:param c2:学习因子
:param max_labels: maxium number of labels of each node
:return:
"""
model=Model()
model.vehicle_cap=v_cap
model.w=w
model.c1=c1
model.c2=c2
model.Vmax=Vmax
model.max_labels = max_labels
model.popsize = popsize
readCSVFile(demand_file,depot_file,model)
calDistanceMatrix(model)
history_best_obj=[]
genInitialSol(model)
history_best_obj.append(model.best_sol.obj)
start_time = time.time()
for ep in range(epochs):
updatePosition(model)
history_best_obj.append(model.best_sol.obj)
print("%s/%s, best obj: %.3f, runtime: %.3f" % (ep + 1, epochs, model.best_sol.obj, time.time() - start_time))
plotObj(history_best_obj)
plotRoutes(model)
outPut(model)
6. 完整代码
如有错误,欢迎交流。
https://download.csdn.net/download/python_n/85808334
参考
- Order-first split-second methods for vehicle routing problems: A review