1 import numpy as np 2 import matplotlib.pyplot as plt 3 from matplotlib.gridspec import GridSpec 4 from scipy.stats import gaussian_kde 5 from _utils.plot_utils import setup_style, save_fig, PALETTE, COLORS, _lighten 6 7 setup_style() 8 np.random.seed(42) 9 10 # === 模拟 4 条 MCMC 链,2 个参数 === 11 n_chains = 4; n_iter = 2000 12 params = ['μ', 'σ'] 13 true_vals = [1.5, 0.7] 14 # 每条链有点初始偏移然后收敛 15 chains = np.zeros((2, n_chains, n_iter)) 16 for p in range(2): 17 for c in range(n_chains): 18 init = true_vals[p] + np.random.normal(0, 0.6) * (1 if c < 2 else 0.4) 19 for i in range(n_iter): 20 init = init + 0.95 * (true_vals[p] - init) * 0.05 + np.random.normal(0, 0.08) 21 chains[p, c, i] = init 22 23 # === 2 行 2 列:每行一个参数 === 24 fig = plt.figure(figsize=(9, 5)) 25 gs = GridSpec(2, 2, width_ratios=[3, 1.5], hspace=0.35, wspace=0.1) 26 27 burnin = 200 28 for p in range(2): 29 # 左:trace plot 30 ax_trace = fig.add_subplot(gs[p, 0]) 31 for c in range(n_chains): 32 ax_trace.plot(np.arange(n_iter), chains[p, c], 33 color=PALETTE[c % len(PALETTE)], linewidth=0.5, alpha=0.75, 34 label=f'链 {c+1}' if p == 0 else None) 35 ax_trace.axvline(burnin, color=COLORS['ref_line'], linestyle=':', linewidth=1, alpha=0.6) 36 ax_trace.text(burnin + 20, ax_trace.get_ylim()[0] + (ax_trace.get_ylim()[1] - ax_trace.get_ylim()[0]) * 0.05, 37 f'burn-in={burnin}', fontsize=7, color=COLORS['ref_line'], style='italic') 38 ax_trace.axhline(true_vals[p], color=COLORS['highlight'], linestyle='--', linewidth=1, alpha=0.7) 39 ax_trace.set_ylabel(params[p], fontsize=11, fontweight='bold') 40 if p == 1: 41 ax_trace.set_xlabel('迭代步数', fontsize=10) 42 ax_trace.spines['top'].set_visible(False) 43 ax_trace.spines['right'].set_visible(False) 44 ax_trace.grid(axis='y', alpha=0.1, linestyle='--', color=COLORS['grid']) 45 if p == 0: 46 ax_trace.legend(loc='upper right', frameon=False, labelspacing=0.35, handlelength=1.6, fontsize=7, ncol=4, columnspacing=1) 47 48 # 右:边际密度(合并所有链,去除 burn-in) 49 ax_dens = fig.add_subplot(gs[p, 1], sharey=ax_trace) 50 pooled = chains[p, :, burnin:].flatten() 51 yg = np.linspace(pooled.min(), pooled.max(), 200) 52 density = gaussian_kde(pooled)(yg) 53 ax_dens.fill_betweenx(yg, 0, density, color=_lighten(PALETTE[0], 0.4), 54 alpha=0.7, linewidth=0) 55 ax_dens.plot(density, yg, color=PALETTE[0], linewidth=1.5) 56 # 95% HPDI 57 sorted_x = np.sort(pooled) 58 ci_lo, ci_hi = np.percentile(sorted_x, [2.5, 97.5]) 59 ax_dens.axhline(ci_lo, color=COLORS['ref_line'], linestyle=':', linewidth=0.8, alpha=0.6) 60 ax_dens.axhline(ci_hi, color=COLORS['ref_line'], linestyle=':', linewidth=0.8, alpha=0.6) 61 ax_dens.axhline(pooled.mean(), color=COLORS['highlight'], linestyle='--', linewidth=1.1, alpha=0.8) 62 63 # 假装计算 Rhat(实际 Rhat 需要严谨实现,这里展示标注样式) 64 rhat_value = 1.005 + np.random.uniform(-0.001, 0.003) 65 info_text = f'$\\hat{{\\theta}}$ = {pooled.mean():.3f}\n95% HPDI: [{ci_lo:.2f}, {ci_hi:.2f}]\n$\\hat{{R}}$ = {rhat_value:.3f}' 66 ax_dens.text(0.95, 0.95, info_text, transform=ax_dens.transAxes, 67 fontsize=7.5, va='top', ha='right', 68 bbox=dict(boxstyle='round,pad=0.3', facecolor='white', 69 edgecolor=COLORS['grid'], alpha=0.95, linewidth=0.4)) 70 71 ax_dens.set_xticks([]) 72 ax_dens.tick_params(axis='y', labelleft=False) 73 for sp in ['top', 'right', 'bottom']: ax_dens.spines[sp].set_visible(False) 74 75 save_fig(fig, 'figures/fig_posterior_trace.pdf')