import pandas as pd
import matplotlib.pyplot as plt

# # ==============================
# # 1️⃣ 读取 CSV
# # ==============================
# csv_file = "convergence0119_data.csv"
# df = pd.read_csv(csv_file)
#
# # ==============================
# # 2️⃣ 选择一次完整 GA 运行
# # ==============================
# target_ts = "2026-01-26 22:30:22"
# run_df = df[df["Timestamp"] == target_ts].copy()
#
# # 按代数排序，取前 50 代
# run_df = run_df.sort_values("Generation").head(100)

# 读取 CSV
csv_file = "convergence0119_data.csv"
df = pd.read_csv(csv_file)

# 按 Generation 排序
run_df = df.sort_values("Generation")
# ==============================
# 3️⃣ 提取数据
# ==============================
generations = run_df["Generation"].values
best_fitness = run_df["Best_Fitness_Percentage"].values

# ==============================
# 4️⃣ 计算滑动平均（窗口=5，可调）
# ==============================
window_size = 5
run_df["MA"] = run_df["Best_Fitness_Percentage"].rolling(
    window=window_size,
    min_periods=1
).mean()

# ==============================
# 5️⃣ 绘图：点 + 连线 + 滑动平均
# ==============================
plt.figure(figsize=(10, 6))

# 原始点
plt.scatter(generations, best_fitness, s=30, alpha=0.6, label="Best Error")

# 连线
plt.plot(generations, best_fitness, linewidth=1, alpha=0.6)

plt.xlabel("Generation")
plt.ylabel("Best Error")
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()

plt.savefig("ga_convergence_me_.png", dpi=300)
plt.show()
