"""用同步粒子群更新最大化 peaks,并观察历史最优与种群半径。""" import json # NumPy 批量更新所有粒子及其记忆;Matplotlib 叠放地形与迭代轨迹。 import matplotlib.pyplot as plt import numpy as np # 目标既接收粒子坐标,也接收绘图网格;各项运算都逐元素进行。 def peaks(x, y): return ( 3 * (1 - x) ** 2 * np.exp(-x**2 - (y + 1) ** 2) - 10 * (x / 5 - x**3 - y**5) * np.exp(-x**2 - y**2) - np.exp(-(x + 1) ** 2 - y**2) / 3 ) def draws(seed, shape): # 顺序是「粒子 1 的两维,粒子 2 的两维……」。 # MATLAB 先重排为 2 行再转置,可取得完全相同的位置和随机系数。 # 不同语言以相同顺序读取随机流;返回新种子以便下一组样本接着抽取。 values = np.empty(np.prod(shape)) for i in range(len(values)): seed = (48271 * seed) % 2147483647 values[i] = seed / 2147483647 return seed, values.reshape(shape) def swarm(weight, particles=12, steps=60): # 每行是一粒子的两个坐标;两组惯性权重从相同种子和零速度出发。 seed, unit = draws(42, (particles, 2)) position = 6 * unit - 3 start = position.copy() velocity = np.zeros_like(position) personal = position.copy() personal_values = peaks(*position.T) best_path, best_values, radius = [], [], [] wall_hits = 0 for t in range(steps + 1): # 全局历史最优来自所有个体历史最优;第 0 轮记录还未移动的种群。 best_row = personal_values.argmax() leader = personal[best_row].copy() best_path.append(leader) best_values.append(float(personal_values[best_row])) # 粒子到当前质心的平均欧氏距离,用来衡量群体聚集程度。 radius.append(float(np.linalg.norm(position - position.mean(axis=0), axis=1).mean())) if t == steps: break # 同一代所有粒子共享上一代的 leader。整批移动后才更新记忆。 seed, r1 = draws(seed, position.shape) seed, r2 = draws(seed, position.shape) # 三项依次是惯性、个体历史最优吸引、群体历史最优吸引,随机系数按坐标相乘。 velocity = weight * velocity + 1.49 * r1 * (personal - position) + 1.49 * r2 * (leader - position) velocity = np.clip(velocity, -1.2, 1.2) # 限步后尝试移动,越界的坐标夹回边界并清零对应速度;碰壁按坐标分量计数。 trial = position + velocity hits = (trial < -3) | (trial > 3) wall_hits += int(np.count_nonzero(hits)) position = np.clip(trial, -3, 3) velocity[hits] = 0 scores = peaks(*position.T) # 只在严格改善时改写个体记忆,历轮最佳目标不会下降。 improved = scores > personal_values personal[improved] = position[improved] personal_values[improved] = scores[improved] return start, position, np.array(best_path), best_values, radius, wall_hits def run(): weights = [0.72, 0.3] records = [swarm(weight) for weight in weights] grid = np.linspace(-3, 3, 201) gx, gy = np.meshgrid(grid, grid) values = peaks(gx, gy) # 有限网格的最大值是独立参考,粒子在格点间仍可能发现更高值。 grid_best = float(values.max()) fig, (ax, trend) = plt.subplots(1, 2, figsize=(9.5, 4.0), layout="constrained") contour = ax.contourf(gx, gy, values, levels=22, cmap="viridis") fig.colorbar(contour, ax=ax, label="peaks(x, y)") start, final, path, *_ = records[0] ax.scatter(*start.T, marker="x", color="white", label="Initial particles") ax.scatter(*final.T, facecolors="none", edgecolors="orange", label="Final particles") ax.plot(*path.T, color="#ef6b55", marker=".", markersize=4, label="Global best path") ax.set(xlabel="x", ylabel="y", aspect="equal", title="Swarm path with w = 0.72") ax.legend(fontsize=8) # 右图同色表示同一惯性权重;实线读目标纵轴,虚线读半径纵轴。 radius_ax = trend.twinx() for i, (weight, record) in enumerate(zip(weights, records)): color = f"C{i}" steps = range(len(record[3])) trend.plot(steps, record[3], color=color, label=f"Best, w={weight:g}") radius_ax.plot(steps, record[4], color=color, linestyle="--") trend.axhline(grid_best, linestyle=":", color="gray", label="Grid reference") trend.set(xlabel="Iteration", ylabel="Best objective") radius_ax.set_ylabel("Swarm radius (dashed)") trend.legend(loc="lower right", fontsize=8) return { "weights": weights, "grid_reference": grid_best, "best_positions": [record[2][-1].tolist() for record in records], "best_objectives": [record[3][-1] for record in records], "best_traces": [record[3] for record in records], "number_of_wall_hits": [record[5] for record in records], "final_radius": [record[4][-1] for record in records], } if __name__ == "__main__": print("LAB_RESULT " + json.dumps(run(), allow_nan=False)) plt.show()