第六章例题及作业3035
例题6.10
import networkx as nx
L=[(1,2,20),(1,5,15),(2,3,20),(2,4,60),(2,5,25),(3,4,30),(3,5,18),(5,6,15)]
G=nx.Graph();G.add_nodes_from(np.arange(1,7))
G.add_weighted_edges_from(L)
d=nx.floyd_warshall_numpy(G)
md=np.max(d,axis=1)
mmd=min(md)
ind=np.argmin(md)+1
print(d);print("最小值为:",mmd)
print("最小值的地址为:",ind)
例题6.11
import cvxpy as cp
L=[(1,2,18),(1,5,15),(2,3,20),(2,4,60),(2,5,12),(3,4,30),(3,5,18),(4,6,10),(5,6,15)]
a=np.ones((6,6))*100000
for i in range(len(L)):
a[L[i][0]-1,L[i][1]-1]=L[i][2]
a[L[i][1]-1,L[i][0]-1]=L[i][2]
x=cp.Variable((6,6),integer=True)
obj=cp.Minimize(cp.sum(cp.multiply(a,x)))
con=[sum(x[1,:])==1,sum(x[:,1])==0,
sum(x[:,3])==1,x>=0,x<=1]
for i in set(range(6))-{1,3}:
con.append(sum(x[i,:])==sum(x[:,i]))
prob=cp.Problem(obj,con)
prob.solve(solver='GLPK_MI')
print("最优值为:",prob.value)
print("最优解为:\n",x.value)
i,j=np.nonzero(x.value)
print("最短路径的起点:",i+1)
print("最短路径的终点:",j+1)
习题6.1
import pandas as pd
import cvxpy as cp
import networkx as nx
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Times New Roman + SimSun + WFM Sans SC']
plt.rcParams['mathtext.fontset']='stix'
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['figure.dpi'] = 200
plt.rcParams['xtick.direction']='in'
plt.rcParams['ytick.direction']='in'
nodes_labels = ['v' + str(i) for i in range(1, 7)]
nodes_labels = dict(zip(range(1,7), nodes_labels))
L1 = [(1,2), (1,3), (1,4), (2,3), (2,6), (3,4), (4,5), (5,6)]
G1 = nx.Graph()
G1.add_edges_from(L1)
L2 = [(1,2,7), (1,3,3), (1,4,12), (2,3,1), (2,6,1), (3,4,8), (4,5,9), (5,6,3)]
G2 = nx.Graph()
G2.add_weighted_edges_from(L2)
L3 = [(2,1,7), (1,3,3), (4,1,12), (2,3,1), (6,2,1), (3,4,8), (5,4,9), (5,6,3)]
G3 = nx.DiGraph()
G3.add_weighted_edges_from(L3)
fig = plt.figure(dpi=400, figsize=(9,3))
ax = fig.add_subplot(131)
pos1 = nx.planar_layout(G1)
nx.draw(G1, pos1, labels=nodes_labels, with_labels='True', font_color='w', node_size=100, font_size=8)
ax1 = fig.add_subplot(132)
pos2 = nx.planar_layout(G2)
nx.draw(G2, pos2, labels=nodes_labels, with_labels='True', font_color='w', node_size=100, font_size=8)
edgelabels = nx.get_edge_attributes(G2, 'weight')
nx.draw_networkx_edge_labels(G2, pos2, edge_labels=edgelabels, font_size=6)
ax2 = fig.add_subplot(133)
pos3 = nx.planar_layout(G3)
nx.draw(G3, pos3, labels=nodes_labels, with_labels='True', font_color='w', node_size=100, font_size=8)
edgelabels = nx.get_edge_attributes(G3, 'weight')
nx.draw_networkx_edge_labels(G3, pos3, edge_labels=edgelabels, font_size=6)
fig.show()
习题6.3
import pandas as pd
import cvxpy as cp
import networkx as nx
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Times New Roman + SimSun + WFM Sans SC']
plt.rcParams['mathtext.fontset']='stix'
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['figure.dpi'] = 200
plt.rcParams['xtick.direction']='in'
plt.rcParams['ytick.direction']='in'
L=[(1,2,20),(1,5,15),(2,3,20),(2,4,60),(2,5,25),
(3,4,30),(3,5,18),(4,5,35),(4,6,10),(5,6,15)]
G = nx.Graph()
G.add_weighted_edges_from(L)
T = nx.minimum_spanning_tree(G)
w = nx.get_edge_attributes(T, 'weight')
print("最小生成树的长度为:", sum(w.values()))
nodes_labels = ['v' + str(i) for i in range(1, 7)]
nodes_labels = dict(zip(range(1,7), nodes_labels))
pos = nx.spring_layout(T)
nx.draw(T, pos, with_labels=True, labels=nodes_labels, font_color='w')
nx.draw_networkx_edge_labels(T, pos, edge_labels=w)
plt.show()
习题6.4
import pandas as pd
import cvxpy as cp
import networkx as nx
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Times New Roman + SimSun + WFM Sans SC']
plt.rcParams['mathtext.fontset']='stix'
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['figure.dpi'] = 200
plt.rcParams['xtick.direction']='in'
plt.rcParams['ytick.direction']='in'
price = np.array([2.5, 2.6, 2.8, 3.1])
sell = np.array([2.0, 1.6, 1.3, 1.1])
cost = np.array([0.3, 0.8, 1.5, 2.0])
cumsum_cost = np.cumsum(cost)
year_num = 4
W = np.zeros((year_num+1, year_num+1))
for i in range(year_num+1):
W[i,i] = 0
for i in range(year_num+1):
for j in range(i+1, year_num+1):
W[i, j] = price[i] + cumsum_cost[j-i-1] - sell[j-i-1]
W[np.isinf(W)] = 0
G = nx.DiGraph(W)
path = nx.shortest_path(G, 0, year_num, weight='weight')
dis = nx.shortest_path_length(G, 0, year_num, weight='weight')
print("应当在以下年份购置新设备", np.array(path[:-1]) + 1)
print("最少费用", round(dis,1))
习题6.5
import pandas as pd
import cvxpy as cp
import networkx as nx
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Times New Roman + SimSun + WFM Sans SC']
plt.rcParams['mathtext.fontset']='stix'
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['figure.dpi'] = 200
plt.rcParams['xtick.direction']='in'
plt.rcParams['ytick.direction']='in'
n = 6
A=np.zeros((n,n))
A[0,[1,2]]=[2,7]
A[1,2:5]=[4,6,8]
A[2,[3,4]]=[1,3]
A[3,[4,5]]=[1,6]
A[4,5]=3
G = nx.Graph(A)
dis = nx.floyd_warshall_numpy(G)
dis_max = np.max(dis, axis=1)
hosp_loc = np.argmin(dis_max) + 1
print(hosp_loc)
stu = np.array([50, 40, 60, 20, 70, 90])
stu_dis = stu@dis
scho_loc = np.argmin(stu_dis) + 1
print(scho_loc)
习题6.7
import pandas as pd
import cvxpy as cp
import networkx as nx
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['Times New Roman + SimSun + WFM Sans SC']
plt.rcParams['mathtext.fontset']='stix'
plt.rcParams['axes.unicode_minus']=False
plt.rcParams['figure.dpi'] = 200
plt.rcParams['xtick.direction']='in'
plt.rcParams['ytick.direction']='in'
df = pd.read_excel('C:/Users/qazws/OneDrive/python代码/python建模作业/ti6_7.xlsx')
D = df.values
print(df)
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
print(W)
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()