6,7
import numpy as np
import pandas as pd
import cvxpy as cp
import networkx as nx
import matplotlib.pyplot as plt
df = pd.read_excel('F:\python数学建模与算法\源程序\《Python数学建模算法与应用》程序和数据\第6章 图论模型\data6.xlsx')
D = df.values
dots = D[:, 0]
xs = D[:, 1]
ys = D[:, 2]
types = D[:, 3].astype('float')
ind1 = np.where(types == 1)[0]
ind2 = np.where(types == 2)[0]
indnan = np.where(np.isnan(types))[0]
dot_num = len(dots)
W = np.zeros((dot_num, dot_num))
for i in range(dot_num):
this_dot = D[i, 0]
this_id = np.where(dots == this_dot)
neighbour_dots = D[i, 4:7]
for d in neighbour_dots:
if d is not np.nan:
neighbour_id = np.where(dots == d)
W[this_id, neighbour_id] = 1
W += W.T
fig = plt.figure(dpi=600)
ax = fig.add_subplot(111)
ax.plot(xs[ind1], ys[ind1], '', color='r', markersize=7, zorder=10, label='一类重要目标')
ax.plot(xs[ind2], ys[ind2], 'x', color='#f86b1d', markersize=5, zorder=10, label='二类重要目标')
ax.plot(xs[indnan], ys[indnan], '.k', markersize=5, zorder=10, label='一般目标')
for i in range(len(dots)):
ax.text(xs[i]+10, ys[i]+15, dots[i], fontsize=5)
for i in range(dot_num):
for j in range(i+1, dot_num):
if W[i,j] != 0:
ax.plot([xs[i], xs[j]], [ys[i], ys[j]], color='k', linewidth=0.5)
ax.legend(fontsize=5)
fig.show()
WW = []
for i in range(dot_num):
for j in range(i+1, dot_num):
if W[i,j] != 0:
WW.append([i, j, np.sqrt((xs[i]-xs[j])2 + (ys[i]-ys[j])2)])
G = nx.Graph()
G.add_weighted_edges_from(WW)
T = nx.minimum_spanning_tree(G)
w = nx.get_edge_attributes(T, 'weight')
print("最小生成树的长度为:", sum(w.values()))
np.array(G.nodes)
indL = np.where(dots'L')[0][0]
indR3 = np.where(dots'R3')[0][0]
path = nx.shortest_path(G, indL, indR3, weight='weight')
dis = nx.shortest_path_length(G, indL, indR3, weight='weight')
path_lb = dots[path]
print("最短路径为:", path_lb)
print("最短距离为:", dis)
fig = plt.figure(dpi=600)
ax = fig.add_subplot(111)
ax.plot(xs[ind1], ys[ind1], '', color='r', markersize=7, zorder=10, label='一类重要目标')
ax.plot(xs[ind2], ys[ind2], 'x', color='#f86b1d', markersize=5, zorder=10, label='二类重要目标')
ax.plot(xs[indnan], ys[indnan], '.k', markersize=5, zorder=10, label='一般目标')
for i in range(len(dots)):
ax.text(xs[i]+10, ys[i]+15, dots[i], fontsize=5)
for i in range(dot_num):
for j in range(i+1, dot_num):
if W[i,j] != 0:
ax.plot([xs[i], xs[j]], [ys[i], ys[j]], color='k', linewidth=0.5)
for i, j in zip(path[:-1], path[1:]):
ax.plot([xs[i], xs[j]], [ys[i], ys[j]], color='cornflowerblue', linewidth=1)
ax.legend(fontsize=5)
fig.show()