1 import shutil, os 2 os.makedirs('_utils', exist_ok=True) 3 for f in ['plot_utils.py']: 4 src = os.path.join(os.path.dirname(__file__), f) 5 if os.path.exists(src): 6 shutil.copy2(src, f'_utils/{f}') 7 8 import numpy as np 9 import matplotlib.pyplot as plt 10 from matplotlib.path import Path 11 from matplotlib.patches import PathPatch, Rectangle 12 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten 13 setup_style() 14 15 16 def draw_sankey(ax, source_nodes, target_nodes, flows, 17 source_colors=None, target_colors=None, 18 left_x=0.10, right_x=0.90, 19 node_width=0.025, node_gap=0.03, 20 title_top=None): 21 """D3 风格 Sankey 图(矩形节点 + 贝塞尔流带)。 22 23 Args: 24 source_nodes: list of (name, total_value),例如 [('国产', 1473), ('俄罗斯', 1500)] 25 target_nodes: list of (name, total_value),例如 [('总供给', 3000)] 26 flows: list of dict {source_idx: int, target_idx: int, value: float} 27 source_colors / target_colors: 可选,None 时自动按 PALETTE 分色 28 node_width: 矩形宽度(相对坐标 0-1) 29 node_gap: 同侧节点间垂直间距 30 title_top: 顶部副标题(如"流量守恒 (万 m³)") 31 """ 32 total_src = sum(v for _, v in source_nodes) 33 total_tgt = sum(v for _, v in target_nodes) 34 if abs(total_src - total_tgt) > 1e-3: 35 raise ValueError(f'流量不守恒:source 合计 {total_src} ≠ target 合计 {total_tgt}') 36 37 Y_MARGIN = 0.08 38 avail_h_src = (1 - 2 * Y_MARGIN) - node_gap * max(0, len(source_nodes) - 1) 39 avail_h_tgt = (1 - 2 * Y_MARGIN) - node_gap * max(0, len(target_nodes) - 1) 40 41 src_ranges = [] 42 y = 1 - Y_MARGIN 43 for _, v in source_nodes: 44 h = v / total_src * avail_h_src 45 src_ranges.append((y - h, y)) 46 y = y - h - node_gap 47 48 tgt_ranges = [] 49 y = 1 - Y_MARGIN 50 for _, v in target_nodes: 51 h = v / total_tgt * avail_h_tgt 52 tgt_ranges.append((y - h, y)) 53 y = y - h - node_gap 54 55 if source_colors is None: 56 source_colors = [PALETTE[i % len(PALETTE)] for i in range(len(source_nodes))] 57 if target_colors is None: 58 target_colors = [COLORS.get('text', '#444444')] * len(target_nodes) 59 60 # 左侧节点矩形 + 标签 61 for i, ((name, v), (y0, y1)) in enumerate(zip(source_nodes, src_ranges)): 62 rect = Rectangle((left_x - node_width / 2, y0), node_width, y1 - y0, 63 facecolor=source_colors[i], edgecolor='none', alpha=0.92, zorder=3) 64 ax.add_patch(rect) 65 ax.text(left_x - node_width / 2 - 0.012, (y0 + y1) / 2, 66 f'{name}\n{v:g}', 67 ha='right', va='center', fontsize=9, 68 color=COLORS.get('text', '#222'), fontweight='bold') 69 70 # 右侧节点矩形 + 标签 71 for i, ((name, v), (y0, y1)) in enumerate(zip(target_nodes, tgt_ranges)): 72 rect = Rectangle((right_x - node_width / 2, y0), node_width, y1 - y0, 73 facecolor=target_colors[i], edgecolor='none', alpha=0.92, zorder=3) 74 ax.add_patch(rect) 75 ax.text(right_x + node_width / 2 + 0.012, (y0 + y1) / 2, 76 f'{name}\n{v:g}', 77 ha='left', va='center', fontsize=9, 78 color=COLORS.get('text', '#222'), fontweight='bold') 79 80 # 贝塞尔流带 81 src_top_used = [r[1] for r in src_ranges] 82 tgt_top_used = [r[1] for r in tgt_ranges] 83 84 for flow in flows: 85 si, ti, val = flow['source_idx'], flow['target_idx'], flow['value'] 86 s_h = val / total_src * avail_h_src 87 t_h = val / total_tgt * avail_h_tgt 88 s_y_top = src_top_used[si]; s_y_bot = s_y_top - s_h; src_top_used[si] = s_y_bot 89 t_y_top = tgt_top_used[ti]; t_y_bot = t_y_top - t_h; tgt_top_used[ti] = t_y_bot 90 91 mid_x = (left_x + right_x) / 2 92 path_data = [ 93 (Path.MOVETO, (left_x + node_width / 2, s_y_top)), 94 (Path.CURVE4, (mid_x, s_y_top)), 95 (Path.CURVE4, (mid_x, t_y_top)), 96 (Path.CURVE4, (right_x - node_width / 2, t_y_top)), 97 (Path.LINETO, (right_x - node_width / 2, t_y_bot)), 98 (Path.CURVE4, (mid_x, t_y_bot)), 99 (Path.CURVE4, (mid_x, s_y_bot)), 100 (Path.CURVE4, (left_x + node_width / 2, s_y_bot)), 101 (Path.CLOSEPOLY, (left_x + node_width / 2, s_y_top)), 102 ] 103 codes, verts = zip(*path_data) 104 flow_color = flow.get('color', source_colors[si]) 105 patch = PathPatch(Path(verts, codes), 106 facecolor=flow_color, edgecolor='none', alpha=0.42, zorder=2) 107 ax.add_patch(patch) 108 109 if title_top: 110 ax.text(0.5, 0.98, title_top, ha='center', va='top', 111 fontsize=10, color=COLORS.get('text', '#444'), fontweight='bold') 112 113 ax.set_xlim(0, 1); ax.set_ylim(0, 1) 114 ax.set_aspect('auto'); ax.axis('off') 115 116 117 # ── 示例 1: 多 source → 单 target(资源分配场景) 118 fig, ax = plt.subplots(figsize=(9, 5)) 119 source_nodes = [('国产', 1473), ('俄罗斯', 1500), ('卡塔尔', 27)] 120 target_nodes = [('总供给 = 需求 (万 m³)', 3000)] 121 flows = [ 122 {'source_idx': 0, 'target_idx': 0, 'value': 1473}, 123 {'source_idx': 1, 'target_idx': 0, 'value': 1500}, 124 {'source_idx': 2, 'target_idx': 0, 'value': 27}, 125 ] 126 draw_sankey(ax, source_nodes, target_nodes, flows, 127 title_top='问题一 最优供应量分配(流量守恒,万 m³)') 128 129 auto_rate = 1473 / 3000 * 100 130 import_rate = (1500 + 27) / 3000 * 100 131 ax.text(0.05, 0.04, 132 f'自给率 = {auto_rate:.1f}% 进口依赖 = {import_rate:.1f}%', 133 ha='left', va='bottom', fontsize=8.5, 134 color=COLORS.get('text', '#444'), 135 bbox=dict(boxstyle='round,pad=0.4', facecolor='white', 136 edgecolor='#cccccc', linewidth=0.5)) 137 138 fig.tight_layout() 139 save_fig(fig, 'figures/fig_sankey_supply.pdf') 140 141 142 # ── 示例 2: 单 source → 多 target(数据分流场景) 143 fig, ax = plt.subplots(figsize=(10, 5.5)) 144 source_nodes = [('原始数据', 1000)] 145 target_nodes = [('训练集', 600), ('测试集', 300), ('验证集', 100)] 146 flows = [ 147 {'source_idx': 0, 'target_idx': 0, 'value': 600, 'color': PALETTE[0]}, 148 {'source_idx': 0, 'target_idx': 1, 'value': 300, 'color': PALETTE[1]}, 149 {'source_idx': 0, 'target_idx': 2, 'value': 100, 'color': PALETTE[2]}, 150 ] 151 draw_sankey(ax, source_nodes, target_nodes, flows, 152 target_colors=[PALETTE[0], PALETTE[1], PALETTE[2]], 153 title_top='数据集划分') 154 fig.tight_layout() 155 save_fig(fig, 'figures/fig_sankey_split.pdf') 156 157 158 # ── 示例 3: 多对多 159 fig, ax = plt.subplots(figsize=(10.5, 6)) 160 source_nodes = [('来源A', 500), ('来源B', 300), ('来源C', 200)] 161 target_nodes = [('去向X', 400), ('去向Y', 350), ('去向Z', 150), ('去向W', 100)] 162 flows = [ 163 {'source_idx': 0, 'target_idx': 0, 'value': 300}, 164 {'source_idx': 0, 'target_idx': 1, 'value': 150}, 165 {'source_idx': 0, 'target_idx': 2, 'value': 50}, 166 {'source_idx': 1, 'target_idx': 0, 'value': 100}, 167 {'source_idx': 1, 'target_idx': 1, 'value': 150}, 168 {'source_idx': 1, 'target_idx': 3, 'value': 50}, 169 {'source_idx': 2, 'target_idx': 1, 'value': 50}, 170 {'source_idx': 2, 'target_idx': 2, 'value': 100}, 171 {'source_idx': 2, 'target_idx': 3, 'value': 50}, 172 ] 173 draw_sankey(ax, source_nodes, target_nodes, flows, 174 title_top='多对多流向分析') 175 fig.tight_layout() 176 save_fig(fig, 'figures/fig_sankey_many.pdf')