1 import numpy as np, matplotlib.pyplot as plt
   2 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten
   3 setup_style()
   4 np.random.seed(42)
   5 
   6 n_nodes = 10
   7 pos = np.random.rand(n_nodes, 2) * 8
   8 labels = [f'N{i}' for i in range(n_nodes)]
   9 
  10 # 随机生成边
  11 edges = []
  12 for i in range(n_nodes):
  13     for j in range(i+1, n_nodes):
  14         if np.random.rand() < 0.3:
  15             w = np.sqrt(np.sum((pos[i]-pos[j])**2))
  16             edges.append((i, j, w))
  17 
  18 # 最优路径(模拟)
  19 path = [0, 3, 7, 5, 9, 2, 6, 1, 8, 4, 0]
  20 
  21 fig, ax = plt.subplots(figsize=(8, 7))
  22 ax.grid(True, linestyle='--', alpha=0.1); ax.set_axisbelow(True)
  23 
  24 # 普通边(浅色)
  25 for i, j, w in edges:
  26     ax.plot([pos[i,0], pos[j,0]], [pos[i,1], pos[j,1]],
  27             color=COLORS['grid'], linewidth=0.8, alpha=0.3, zorder=1)
  28 
  29 # 最优路径(粗线)
  30 for k in range(len(path)-1):
  31     i, j = path[k], path[k+1]
  32     ax.plot([pos[i,0], pos[j,0]], [pos[i,1], pos[j,1]],
  33             color=PALETTE[0], linewidth=3, alpha=0.8, zorder=3)
  34     # 边权标签
  35     mx, my = (pos[i,0]+pos[j,0])/2, (pos[i,1]+pos[j,1])/2
  36     w = np.sqrt(np.sum((pos[i]-pos[j])**2))
  37     ax.text(mx, my, f'{w:.1f}', fontsize=7, ha='center', va='center',
  38             bbox=dict(facecolor='white', alpha=0.8, edgecolor='none', pad=1))
  39 
  40 # 节点
  41 for i in range(n_nodes):
  42     is_depot = (i == 0)
  43     c = COLORS['down'] if is_depot else PALETTE[0]
  44     s = 200 if is_depot else 120
  45     marker = 's' if is_depot else 'o'
  46     ax.scatter(pos[i,0], pos[i,1], s=s, color=_lighten(c, 0.3), edgecolor=c,
  47               linewidth=1.5, zorder=5, marker=marker)
  48     ax.text(pos[i,0], pos[i,1]+0.3, labels[i], ha='center', va='bottom',
  49             fontsize=9, fontweight='bold',
  50             bbox=dict(facecolor='white', alpha=0.8, edgecolor=COLORS['grid'], pad=1.5))
  51 
  52 ax.set_xlabel('坐标 X', fontsize=11); ax.set_ylabel('坐标 Y', fontsize=11)
  53 ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
  54 fig.tight_layout()
  55 save_fig(fig, 'figures/fig_network_path.pdf')