"""
生成论文用的完成时间分布图 - 改进版
"""

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import rcParams
import pandas as pd

# 设置字体
rcParams['font.sans-serif'] = ['Arial', 'DejaVu Sans', 'Helvetica']
rcParams['axes.unicode_minus'] = False
rcParams['font.size'] = 11

# 读取模拟结果数据
df = pd.read_csv('/Volumes/Files/code/mm/20260130_b/p2/simulation_results.csv')

# 中低饱和度配色方案 - 柔和学术风格
colors = ['#7BAE7F', '#6A9ECF', '#9B8EC2']  # 柔和的绿、蓝、紫

# 方案名称
scenario_labels = {
    'Scenario_A': 'Cost Priority',
    'Scenario_B': 'Time Priority', 
    'Scenario_C': 'Balanced'
}

# 创建图表 - 缩小尺寸以放大字体效果
fig, axes = plt.subplots(1, 3, figsize=(10, 3.2))

for idx, (scenario_key, label) in enumerate(scenario_labels.items()):
    ax = axes[idx]
    
    # 获取该方案的数据
    data = df[df['scenario'] == scenario_key]['completion_years']
    
    # 计算统计量
    mean_val = np.mean(data)
    p5 = np.percentile(data, 5)
    p95 = np.percentile(data, 95)
    
    # 绘制柱状图 - 实心柱状图，增粗柱子
    ax.hist(data, bins=15, color=colors[idx], alpha=0.9, 
            edgecolor='white', linewidth=0.8, rwidth=0.9)
    
    # 设置子图标题 - 简洁的 (a) (b) (c) 标签
    ax.set_title(f'({chr(97+idx)}) {label}', fontsize=12, fontweight='normal', pad=8)
    
    # 设置坐标轴标签
    ax.set_xlabel('Completion Years', fontsize=11)
    if idx == 0:
        ax.set_ylabel('Frequency', fontsize=11)
    
    # 在图内右上角添加纯文本统计信息（无边框）
    text_str = f'Mean: {mean_val:.1f}\n5%: {p5:.1f}\n95%: {p95:.1f}'
    ax.text(0.97, 0.97, text_str, transform=ax.transAxes, fontsize=9,
            verticalalignment='top', horizontalalignment='right',
            bbox=dict(boxstyle='round,pad=0.3', facecolor='white', 
                     edgecolor='none', alpha=0.85))
    
    # 网格线 - 非常淡
    ax.grid(True, alpha=0.15, linestyle='-', linewidth=0.5)
    
    # 设置刻度字体大小
    ax.tick_params(axis='both', labelsize=10)
    
    # 中间图 (b) 的 x 轴使用整数刻度
    if idx == 1:
        from matplotlib.ticker import MaxNLocator
        ax.xaxis.set_major_locator(MaxNLocator(integer=True))
    
    # 简化边框
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)

# 调整布局
plt.tight_layout()

# 保存图片
plt.savefig('/Volumes/Files/code/mm/20260130_b/p2/completion_time_distribution_paper.png', 
            dpi=200, bbox_inches='tight', facecolor='white')
plt.savefig('/Volumes/Files/code/mm/20260130_b/p2/completion_time_distribution_paper.pdf', 
            dpi=200, bbox_inches='tight', facecolor='white')

print("图表已保存:")
print("  - completion_time_distribution_paper.png")
print("  - completion_time_distribution_paper.pdf")
