提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、SA是什么?
  • 二、VRP-SA
    • 1.库
    • 2.代码块.
  • 运行

前言

提示:这里可以添加本文要记录的大概内容:

模拟算法(SA)来求解VRP问题

VRP拆解为TSP问题后,对TSP问题进行算子改变,从而实现可行解之间的改变。

TSP算子改变:可以分为两两元素改变,两两片段改变


提示:以下是本篇文章正文内容,下面案例可供参考

一、SA是什么?

SA 是元启发式的一种,为了跳出局部解,以一定的概率可以接受非改进解的算法。

通过对温度T进行改变,此处是迭代10次温度下降0.9。

温度越低,非改进路线选取的概率越低,但仍然有一定概率被选中

二、使用步骤

1.引入库

代码如下(示例):

import copyimport matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import math
import random

2.定义SA-VRP

代码如下(示例):

class vrp_SA():def __init__(self,file_path,veh_capacity):self.file_path =file_pathself.veh_capacity=veh_capacitydef readfile(self):file =self.file_pathData =pd.read_csv(file)x_cor =list(Data['x_coord'])y_cor =list(Data['y_coord'])demand =list(Data['demand'])index =list(Data['id'])##create dict():nodes={}for i in range(len(demand)):if demand == 0:depot_non_deman = demand[i]nodes[i]=(depot_non_deman,x_cor[i],y_cor[i])else:cus_deman = demand[i]nodes[i] = (cus_deman, x_cor[i], y_cor[i])##depot node:depot_node =nodes[0]###project depot node :nodes[-1] = depot_nodereturn nodes###define initial solution for TSPdef initial(self,nodes):##drop out 0 and -1 nodecount =len(nodes)-2##randomly create nodes listinitial_path =[i for i in range(1,count+1)]random.seed(0)np.random.shuffle(initial_path)return initial_path####define the TSP swap rulesdef swap_single_Nodes(self,path):swap_si_path =copy.deepcopy(path)index1,index2 =np.random.randint(1,100,1)[0],np.random.randint(1,100,1)[0]swap_si_path[index1],swap_si_path[index2] = path[index2],path[index1]print('swap num:',(swap_si_path[index1],swap_si_path[index2]))return swap_si_pathdef swap_seq(self,path,num):oldpath =copy.deepcopy(path)count =len(new_path)swap_seq_path =[]for i in range(0,count,num):if i%2==0:# new_list=[ele1,ele2,ele3,ele4]ele1 = oldpath[i]ele2 = oldpath[i + 1]ele3 = oldpath[i + 2]ele4 = oldpath[i + 3]swap_seq_path.append(ele1)swap_seq_path.append(ele2)swap_seq_path.append(ele3)swap_seq_path.append(ele4)else:ele1 = oldpath[i]ele2 = oldpath[i + 1]ele3 = oldpath[i + 2]ele4 = oldpath[i + 3]swap_seq_path.insert(0,ele1)swap_seq_path.insert(0,ele2)swap_seq_path.insert(0,ele3)swap_seq_path.insert(0,ele4)return swap_seq_path##split TSP routes and get the vehicle num and veh_path:def splitRoutes(self,path,nodes):''':return:vehicle numbervehicle routesvehicle capacity'''num_veh=1route_veh=[]route =[]reminded_capacity =self.veh_capacityfor node in path:if reminded_capacity -nodes[node][0] >=0:route.append(node)reminded_capacity=reminded_capacity -nodes[node][0]else:route_veh.append(route)num_veh = num_veh + 1#update new route nodes:reminded_capacity =self.veh_capacityroute=[node]reminded_capacity =reminded_capacity-nodes[node][0]route_veh.append(route)return num_veh,route_vehdef no_dis(self,point1,point2):''':param point1::param point2::return: two point distance'''node_dis =np.hypot(point1[1]-point2[1],point1[2]-point2[2])return node_disdef vrp_dis(self,route_veh,nodes):''':param route_veh: vehicle routes output from TSP route split:param nodes: node information (x,y):return: a list of vehicle route distance for VRP routing route'''distance =0##get single routes:all_distance =[]for i in range(len(route_veh)):# print(i)##get total pathall_path =[0]+route_veh[i]+[-1]# print('all path:',all_path)each_path_dis=0dis_j = []for j in range(len(all_path)):if j ==len(all_path)-1:point1 =all_path[j]point2 =all_path[0]point1 =nodes[point1]point2=nodes[point2]point_dis =self.no_dis(point1,point2)each_path_dis =each_path_dis +point_diselse:point1 = all_path[j]point2=all_path[j+1]point1 = nodes[point1]point2 = nodes[point2]point_dis = self.no_dis(point1, point2)each_path_dis =each_path_dis +point_dis#print(each_path_dis)dis_j.append(each_path_dis)all_distance.append(dis_j[0])# print('path distance:{}'.format(dis_j))# print(all_distance)return all_distancedef calObj(self,veh_routes):''':param nodes: the (x,y) in file:return: each VRP routing distance'''nodes=self.readfile()total_Obj =sum(self.vrp_dis(veh_routes,nodes=nodes))return total_Obj#########plotdef plotObj(self,Obj_list):''':param Obj_list: list of each path total_Obj(each VRP RROUTING distance):return: plot'''plt.rcParams['axes.unicode_minus']=False #show minus sign# plt.plot(np.arange(1,len(Obj_list)+1),Obj_list)x = [x for x in range(len(Obj_list))]plt.clf()plt.plot(x, Obj_list, label='linear')plt.xlabel('Iterations')plt.ylabel('Obj value')plt.grid()plt.xlim(1,len(Obj_list)+1)return plt.show()###define SA algorithm for VRP:def SA_VRP(self,current_tsp_path,new_tsp_path,t):''':param T0: Initial temportature:param Tend: Termination temportature:param deltaQ: the fraction of delta/q(temporature) ,:param v_cap: Vehicle capacity:param opt_type: Optimization type: 0: Minimize the number of vehicles1: Minimize travel distance:return:核心:TSP变换-新TSP-切分TSP 成VRP-对比成本来模拟退火!!!'''# veh_cap =self.veh_capacity# nodes =self.readfile()# init_TSP_path=self.initial(nodes=nodes)# new_TSP_path =self.swap_single_Nodes(init_TSP_path)curr_num ,curr_vrp =self.splitRoutes(current_tsp_path,nodes)new_veh_num,new_vrp = self.splitRoutes(new_tsp_path, nodes)dis_curr =self.calObj(curr_vrp)dis_new = self.calObj(new_vrp)deltaQ =dis_new-dis_currprint('delta',deltaQ)min_list=[]if deltaQ<0:current_tsp_path =copy.deepcopy(new_tsp_path)dis =self.calObj(new_vrp)min_list.append(dis)else:df = math.exp(-deltaQ / t)if  df >=random.randint(0,1):dis =self.calObj(new_vrp)current_tsp_path = copy.deepcopy(new_tsp_path)min_list.append(dis)else:dis =self.calObj(curr_vrp)current_tsp_path=copy.deepcopy(current_tsp_path)min_list.append(dis)print(current_tsp_path,min_list)return current_tsp_path, min_list

运行

if __name__ == '__main__':##read nodes data:file ='cvrp.csv'veh_cap=800vrpsa =vrp_SA(file,veh_cap)nodes =vrpsa.readfile()print(nodes)# ## define initial data:initial_path =vrpsa.initial(nodes)new_path =vrpsa.swap_single_Nodes(initial_path)##initializeT0=1000Tend =0.01MaxIter =500##para value:t = T0num = 0path_list = []dis_list = []rate =0.5# new_TSP_path = vrpsa.swap_single_Nodes(init_TSP_path)# curr_tsp_path, min_dis = vrpsa.SA_VRP(current_tsp_path=init_TSP_path, new_tsp_path=new_TSP_path, t=t)init_TSP_path = vrpsa.initial(nodes=nodes)while t > Tend and MaxIter > 0:if MaxIter % 10 == 0:t = t * rate# else:#     t=tprint('t:',t)###find the new pathnew_TSP_path =vrpsa.swap_single_Nodes(path=init_TSP_path)curr_tsp_path, min_dis = vrpsa.SA_VRP(current_tsp_path=init_TSP_path, new_tsp_path=new_TSP_path, t=t)path_list.append(curr_tsp_path)dis_list.append(min_dis)MaxIter -= 1print('maxiter:', MaxIter)#最小值位置min_dis = min(dis_list)dis_index = dis_list.index(min_dis)#最小值对应的路径shortest_path = path_list[dis_index]new_veh_num, new_vrp = vrpsa.splitRoutes(shortest_path, nodes)print('vehcile distance:{}, best Obj routes:{}:'.format(min_dis,new_vrp))###draw plot:vrpsa.plotObj(dis_list)

此处对迭代算法进行评估-以图为导向。(100个点的VRP问题)

VRP_SA-模拟退火相关推荐

  1. poj2420A Star not a Tree?(模拟退火)

    链接 求某一点到其它点距离和最小,求这个和,这个点 为费马点. 做法:模拟退火 1 #include <iostream> 2 #include<cstdio> 3 #incl ...

  2. 模拟退火 HDU - 2899 Strange Function

    Strange Function [ HDU - 2899 ] 题目大意: 函数 F(x) = 6x7 + 8x6 + 7x3 + 5x2 - yx, 其中x的范围是0 ≤ x ≤ 100. 输入y值 ...

  3. 局部邻域搜索-爬山法,模拟退火,禁忌,迭代局部搜索,变邻域局部搜索的简单阐释

    原文来源: 局部搜索算法 - JiePro - 博客园 https://www.cnblogs.com/JiePro/p/Metaheuristics_0.html 局部搜索算法 目录: 1.数学定义 ...

  4. 2018-4-8模拟退火算法

    阅读资料来源: <智能优化算法以及matlab实现>第七章 [图文]智能优化算法_数学建模_王成章_模拟退火法_2011_百度文库 https://wenku.baidu.com/view ...

  5. 2018-4-8使用兔子的例子对比说明遗传算法,局部搜索,禁忌搜索,模拟退火方法

    文章的来源: [图文]智能优化算法_数学建模_王成章_模拟退火法_2011_百度文库 https://wenku.baidu.com/view/335c56e94afe04a1b071de13.htm ...

  6. HDU2899(二分查找+or+模拟退火算法)

    这道题其实是利用函数求导,判断求导后的函数是否大于零或者小于零,等于零情况,从而判断原函数的单调性,代入X求出函数的最小值. 模拟退火算法: 方法一:二分 #include<stdio.h> ...

  7. luogu P4035 [JSOI2008]球形空间产生器(高斯消元 / 模拟退火)

    整理的算法模板合集: ACM模板 点我看算法全家桶系列!!! 实际上是一个全新的精炼模板整合计划 数据范围只开到了10,而且是经典的力学结构,所以我们可以用模拟退火,可以做一下 nnn 维的正交分解h ...

  8. R语言基于模拟退火(Simulated Annealing)进行特征筛选(feature selection)

    R语言基于模拟退火(Simulated Annealing)进行特征筛选(feature selection) 特征选择的目的 1.简化模型,使模型更易于理解:去除不相关的特征会降低学习任务的难度.并 ...

  9. python模拟退火(Simulated Annealing)参数寻优实战

    python模拟退火(Simulated Annealing)参数寻优实战 目录 python模拟退火(Simulated Annealing)参数寻优实战 模拟退火 模拟退火算法流程

  10. 梯度下降之模拟退火、梯度下降之学习计划、牛顿法、拟牛顿法、共轭梯度法

    梯度下降之模拟退火.梯度下降之学习计划.牛顿法.拟牛顿法.共轭梯度法 目录

最新文章

  1. iOS UI 12 block传值
  2. c语言87,C语言程序设计87300.doc
  3. 1189C. Candies
  4. 深度学习的实用层面 —— 1.2 偏差/方差
  5. skinmagic对VC中程序窗口的换肤
  6. 2021-2025年中国一氧化碳烟雾报警器行业市场供需与战略研究报告
  7. 使用Cscope阅读Linux源码
  8. Error: new BigNumber() not a base 16 number
  9. 【Net Core系列】(前言).net core学习笔记
  10. 记录一次Tx_LCN连接失败的问题( There is no normal TM )
  11. 【HL7】快速入门 HL7 协议
  12. HTTP 协议的演变历程
  13. 如何搭建App自动化测试框架?
  14. FPGA零基础学习:数码管驱动设计
  15. Genbank的gbff格式转gff3格式(补充)
  16. 揭秘微信营销“暗黑产业链”:粉丝阅读量明码标价
  17. Irrlicht学习笔记(8)--SpecialFX
  18. 没有时间可以浪费了!探险家伊泽瑞尔...
  19. 详解:二极管M7和A7的区别
  20. 初中计算机flash考试题,【信息技术中考专区】Flash操作题专练(七)!

热门文章

  1. 优秀课件笔记之计算机软件立法保护
  2. java计算机毕业设计网上宠物商店系统源码+系统+数据库+lw文档+mybatis+运行部署
  3. laravel框架图片无法显示问题
  4. 山东大学2019级软件工程应用与实践——基于人工智能的多肽药物分析问题(十二)
  5. 计算机体系结构复习笔记
  6. SPSS 自动线性建模 模型导出方法
  7. 【0-1背包】二进制灰狼算法解决0-1背包问题【Matlab】
  8. position四个属性详解
  9. A Survey on Big Data Market: Pricing, Trading and Protection
  10. 一个能在vue3中运行的JSON编辑器,能展示JSON数据的高亮,打开时有默认数据