首页 > 其他分享 >1

1

时间:2024-10-27 14:19:59浏览次数:1  
标签: inl plt weight len nx np

``import numpy as np
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
a = pd.read_excel(r"ti6_7.xlsx")
b = a.values

s = list(b[:, 0])
x = b[:, 1]
y = b[:, 2]
num = b[:, 3].astype(float)
ad = b[:, 4:].astype(str)

inl = np.where(num == 1)[0]
in2 = np.where(num == 2)[0]
in3 = np.where(np.isnan(num))[0]
plt.plot(x[inl], y[inl], 'Pk')
for i in range(len(inl)):
plt.text(x[inl[i]] + 10, y[inl[i]], s[inl[i]])
plt.plot(x[in2], y[in2], '*k')
for i in range(len(in2)):
plt.text(x[in2[i]] + 10, y[in2[i]], s[in2[i]])
plt.plot(x[in3], y[in3], '.k')
for i in range(len(in3)):
plt.text(x[in3[i]] + 10, y[in3[i]], s[in3[i]])

c = np.zeros((len(s), len(s)))
G = nx.Graph()
G.add_nodes_from(s)
eds = []

for i in range(len(s)):
tt = list(ad[i])
tt = [t for t in tt if t != 'nan' and t != '']
for k in range(len(tt)):
j = s.index(tt[k])
c[i, j] = np.sqrt((x[i] - x[j]) ** 2 + (y[i] - y[j]) ** 2)

i, j = np.nonzero(c)
for k in range(len(i)):
if c[i[k], j[k]] > 0:
eds.append([s[i[k]], s[j[k]], c[i[k], j[k]]])
G.add_weighted_edges_from([(s[i[k]], s[j[k]], c[i[k], j[k]])])

T = nx.minimum_spanning_tree(G, weight='weight')
w = nx.get_edge_attributes(T, 'weight')
LT = sum(w.values())
print('最小生成树的长度为:', round(LT, 4))

pos = dict(zip(s, b[:, [1, 2]]))
plt.figure()
nx.draw_networkx(T, pos, node_size=180, font_weight='bold', with_labels=True, node_color='w')
plt.show()

求最短路径和距离

if 'L' in G and 'R3' in G:
p = nx.shortest_path(G, 'L', 'R3', weight='weight')
d = nx.shortest_path_length(G, 'L', 'R3', weight='weight')
print('最短路径为:', p)
print('最短距离为:', round(d, 4))

# 绘制最短路径  
plt.figure()  
nx.draw_networkx(G, pos, node_size=180, font_weight='bold', with_labels=True, node_color='w')  
path_edges = list(zip(p, p[1:]))  
nx.draw_networkx_edges(G, pos, edgelist=path_edges, edge_color='r', style='dashed', width=4)  
plt.show()  

else:
print("'L' 或 'R3' 不在图中")

标签:,inl,plt,weight,len,nx,np
From: https://www.cnblogs.com/Lntano/p/18508313

相关文章