"""固定初温和随机序列,只比较两种几何冷却速度。""" import json import math # math 用于标量目标与接受准则;NumPy 和 Matplotlib 保存并绘制温度与位置轨迹。 import matplotlib.pyplot as plt import numpy as np def objective(x): return math.sin(x) + 0.5 * math.sin(3 * x) def anneal(alpha, steps=700): # 两组从相同起点、初温和种子出发,当前状态负责提出邻居,历史最优单独记录。 x, temperature, seed = 4.0, 0.5, 9 current = objective(x) best_x, best_f = x, current counts = [0, 0] # 已接受总数、其中严格更差的次数 # 轨迹列依次为位置、当前目标、历史最优和温度;首行是第 0 步。 trace = [(x, current, best_f, temperature)] for _ in range(steps): # 无论分支如何,每轮消耗固定两个随机数,让两种冷却共享抽样。 seed = 48271 * seed % 2147483647 u_step = seed / 2147483647 seed = 48271 * seed % 2147483647 u_accept = seed / 2147483647 # 均匀扰动最大幅度为 0.25,再把候选裁剪到定义域 [0,2π]。 candidate = min(max(x + 0.25 * (2 * u_step - 1), 0), 2 * math.pi) candidate_f = objective(candidate) delta = candidate_f - current # 最大化时劣解的 delta < 0。用 log u < delta/T,不必计算极小的指数。 if delta >= 0 or math.log(u_accept) < delta / temperature: x, current = candidate, candidate_f counts[0] += 1 # 布尔条件作为 0 或 1,只统计已接受且严格变差的迭代。 counts[1] += int(delta < 0) if current > best_f: best_x, best_f = x, current # 每步都降温;alpha 越接近 1,高温保留越久。 temperature *= alpha trace.append((x, current, best_f, temperature)) return np.array(trace), counts, best_x def run(): alphas = [0.995, 0.92] records = [anneal(alpha) for alpha in alphas] grid = np.linspace(0, 2 * math.pi, 10001) # 网格最大值是有限分辨率的独立参考;退火位置可以在格点之间。 grid_best = float(np.max(np.sin(grid) + 0.5 * np.sin(3 * grid))) fig, (terrain_ax, trace_ax, temp_ax) = plt.subplots(1, 3, figsize=(11, 3.8), layout="constrained") terrain_ax.plot(grid, np.sin(grid) + 0.5 * np.sin(3 * grid), color="gray") # 同组同色,星号标实际最高点。中图浅线为当前值,深线为历史最大值。 for i, (alpha, (trace, _, best_x)) in enumerate(zip(alphas, records)): color = f"C{i}" label = f"alpha={alpha:g}" terrain_ax.scatter(best_x, trace[-1, 2], color=color, marker="*", s=100, label=label) trace_ax.plot(trace[:, 2], color=color, label=label) trace_ax.plot(trace[:, 1], color=color, alpha=0.26) # 几何降温在对数纵轴上呈直线,斜率由 log(alpha) 决定。 temp_ax.semilogy(trace[:, 3], color=color, label=label) terrain_ax.scatter(4, objective(4), color="black", marker="x", label="Start") terrain_ax.set(xlabel="x", ylabel="f(x)", title="Landscape and best points") terrain_ax.legend(fontsize=8) trace_ax.axhline(grid_best, linestyle=":", color="gray", label="Grid reference") trace_ax.set(xlabel="Iteration", ylabel="Objective", title="Current and best-so-far") trace_ax.legend(fontsize=8) temp_ax.set(xlabel="Iteration", ylabel="Temperature", title="Geometric cooling") temp_ax.legend(fontsize=8) return { "alphas": alphas, "grid_reference": grid_best, "best_positions": [record[2] for record in records], "best_objectives": [float(trace[-1, 2]) for trace, _, _ in records], "final_positions": [float(trace[-1, 0]) for trace, _, _ in records], "accepted_count": [counts[0] for _, counts, _ in records], "worse_accepted_count": [counts[1] for _, counts, _ in records], "final_temperatures": [float(trace[-1, 3]) for trace, _, _ in records], } if __name__ == "__main__": print("LAB_RESULT " + json.dumps(run(), allow_nan=False)) plt.show()