- 数学模型作业(2)中计算欧式距离有误,已更改。
- 内容(代码)接数学模型作业(2)
- 初学python和数学模型,不足之处请大佬指出。
- 给个赞(上次已经骗过关注了~~~)
- 导入相关参数
shape = 613
alpha1 = 25
alpha2 = 15
beta1 = 20
beta2 = 25
theta = 30
delta = 0.001
- 建立 List 格式的垂直校正点集合 V 和水平校正点集合 H,保存在一个 txt文件中。
# 建立垂直校正点集合V和水平校正点集合H
V = []
H = []
VH = []
for i in range(0, shape):
if prop[i] == 1:
V.append(i)
if prop[i] == 0:
H.append(i)
VH = V + H
file = open('校正点集合.txt', 'w')
for i in range(len(VH)):
s = str(VH[i]) + '\n'
file.write(s)
file.close()
- 用 python 输出减少边之后最短路模型的邻接矩阵,存放在
excel 文件中。
- 分析:
(1) 剪枝可以剪去任意点为起点到垂直校正点不符合垂直校正条件的枝
(2)剪枝可以剪去任意点为起点到水平校正点不符合水平校正条件的枝
(3) 剪枝可以剪去以B点为终点,距离超过 θ / δ \theta/\delta θ/δ的枝 - 安装gurobi,参考另一篇(Gurobi9.0.3安装)
- 将距离矩阵dist转换为tupledict类型,用dict_dist存放邻接矩阵(要调用gurobi库:from gurobipy import *)
# 将距离矩阵dist转换为tupledict类型,用dict_dist存放邻接矩阵
dict_dist = {
}
for i in range(shape):
for j in range(shape):
dict_dist[i, j] = dist[i][j]
dict_dist = tupledict(dict_dist)
- 剪枝实现
# step1:剪去到垂直校正点不符合要求的边
for i in range(1, shape-1):
for j in V:
if dist[i][j] > min(alpha1, alpha2) / delta:
dict_dist[i, j] = 0
# step2:剪去到水平校正点不符合要求的边
for i in range(1, shape-1):
for j in H:
if dist[i][j] > min(beta1, beta2) / delta:
dict_dist[i, j] = 0
# step3:剪去距离终点B超过30000m的边
for i in range(shape-1):
if dist[i][shape-1] > theta / delta:
dict_dist[i, shape-1] = 0
# 定义边集
edge = []
for i in range(shape):
for j in range(shape):
if dict_dist[i, j] != 0:
edge.append((i, j))
print("剪枝之后的边数:", len(edge))
- 邻接矩阵存入excel表格
# 将 剪枝后的邻接矩阵写入到 dict_dist_save.xlsx 中
dict_dist_save = np.zeros(shape=(shape, shape))
for i in range(shape):
for j in range(shape):
dict_dist_save[i][j] = dict_dist[i, j]
dict_dist_save = pd.DataFrame(dict_dist_save)
writer = pd.ExcelWriter('dict_dist.xlsx')
dict_dist_save.to_excel(writer, 'sheet1')
writer.save()
- 结果
来源:oschina
链接:https://my.oschina.net/u/4353573/blog/4678349