1 import numpy as np; from _utils.palette_maps import palette_cmap, palette_stops, contrast_text 2 import matplotlib.pyplot as plt 3 from matplotlib.gridspec import GridSpec 4 from matplotlib.patches import FancyArrowPatch 5 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten 6 7 setup_style() 8 np.random.seed(42) 9 10 # === 模拟数据:输入图 / 注意力图 / 输出图 === 11 H, W = 80, 80 12 y, x = np.mgrid[0:H, 0:W] 13 input_img = np.exp(-((x - 28)**2 + (y - 32)**2) / 250) + \ 14 0.6 * np.exp(-((x - 52)**2 + (y - 48)**2) / 200) + \ 15 np.random.normal(0, 0.04, (H, W)) 16 attention = np.exp(-((x - 40)**2 + (y - 40)**2) / 500) * (input_img > 0.2) 17 output_img = input_img * attention * 1.6 18 19 # === 1 行 3 列 + 上方薄色条 === 20 fig = plt.figure(figsize=(9, 4)) 21 gs = GridSpec(2, 3, height_ratios=[0.5, 6], hspace=0.05, wspace=0.12) 22 23 titles = ['(a) 输入', '(b) 注意力图', '(c) 重构输出'] 24 images = [input_img, attention, output_img] 25 v = max(np.max(im) for im in images) 26 27 axes_img = [] 28 for col in range(3): 29 ax = fig.add_subplot(gs[1, col]) 30 im = ax.imshow(images[col], cmap=palette_cmap('sequential'), vmin=0, vmax=v, 31 interpolation='bilinear') 32 ax.set_title(titles[col], fontsize=11, fontweight='bold', 33 color=COLORS['text'], pad=8) 34 ax.axis('off') 35 axes_img.append((ax, im)) 36 37 # === 顶部共享色条 === 38 cbar_ax = fig.add_subplot(gs[0, :]) 39 cbar = fig.colorbar(axes_img[0][1], cax=cbar_ax, orientation='horizontal') 40 cbar.set_label('归一化激活', fontsize=8); cbar.ax.xaxis.set_label_position('top'); cbar.ax.xaxis.set_ticks_position('top') 41 cbar.ax.tick_params(labelsize=7, length=2) 42 cbar.outline.set_linewidth(0.4) 43 cbar.outline.set_edgecolor(COLORS['grid']) 44 45 # === 子图间流向箭头(用 figure-level transform)=== 46 def add_arrow(fig, axL, axR, label=None): 47 bbL = axL.get_position(); bbR = axR.get_position() 48 y_mid = (bbL.y0 + bbL.y1) / 2 49 arrow = FancyArrowPatch((bbL.x1 + 0.005, y_mid), (bbR.x0 - 0.005, y_mid), 50 transform=fig.transFigure, 51 arrowstyle='->', mutation_scale=14, 52 color=COLORS['highlight'], linewidth=1.5, 53 clip_on=False) 54 fig.patches.append(arrow) 55 if label: 56 fig.text((bbL.x1 + bbR.x0) / 2, y_mid + 0.04, label, 57 fontsize=8, ha='center', color=COLORS['highlight'], 58 fontweight='bold', style='italic') 59 60 add_arrow(fig, axes_img[0][0], axes_img[1][0], 'Encoder') 61 add_arrow(fig, axes_img[1][0], axes_img[2][0], 'Decoder') 62 63 save_fig(fig, 'figures/fig_triptych.pdf')