Advertisement
makispaiktis

PSO - Particle Swarm Optimization

May 31st, 2022 (edited)
754
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.83 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import networkx as nx
  4. from matplotlib.animation import FuncAnimation, PillowWriter
  5.  
  6.  
  7. def f(x, y):
  8.     "Objective function"
  9.     return (x - 3.14) ** 2 + (y - 2.72) ** 2 + np.sin(3 * x + 1.41) + np.sin(4 * y - 1.73)
  10.  
  11.  
  12. # Compute and plot the function in 3D within [0,5]x[0,5]
  13. x, y = np.array(np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100)))
  14. z = f(x, y)
  15.  
  16. # Find the global minimum
  17. x_min = x.ravel()[z.argmin()]
  18. y_min = y.ravel()[z.argmin()]
  19.  
  20. # Hyper-parameter of the algorithm
  21. c1 = c2 = 0.1
  22. w = 0.8
  23.  
  24. # Create particles
  25. n_particles = 20
  26. np.random.seed(100)
  27. X = np.random.rand(2, n_particles) * 5
  28. V = np.random.randn(2, n_particles) * 0.1
  29.  
  30. # Initialize data
  31. pbest = X
  32. pbest_obj = f(X[0], X[1])
  33. gbest = pbest[:, pbest_obj.argmin()]
  34. gbest_obj = pbest_obj.min()
  35.  
  36.  
  37. def update():
  38.     "Function to do one iteration of particle swarm optimization"
  39.     global V, X, pbest, pbest_obj, gbest, gbest_obj
  40.     # Update params
  41.     r1, r2 = np.random.rand(2)
  42.     V = w * V + c1 * r1 * (pbest - X) + c2 * r2 * (gbest.reshape(-1, 1) - X)
  43.     X = X + V
  44.     obj = f(X[0], X[1])
  45.     pbest[:, (pbest_obj >= obj)] = X[:, (pbest_obj >= obj)]
  46.     pbest_obj = np.array([pbest_obj, obj]).min(axis=0)
  47.     gbest = pbest[:, pbest_obj.argmin()]
  48.     gbest_obj = pbest_obj.min()
  49.  
  50.  
  51. # Set up base figure: The contour map
  52. fig, ax = plt.subplots(figsize=(8, 6))
  53. fig.set_tight_layout(True)
  54. img = ax.imshow(z, extent=[0, 5, 0, 5], origin='lower', cmap='viridis', alpha=0.5)
  55. fig.colorbar(img, ax=ax)
  56. ax.plot([x_min], [y_min], marker='x', markersize=5, color="white")
  57. contours = ax.contour(x, y, z, 10, colors='black', alpha=0.4)
  58. ax.clabel(contours, inline=True, fontsize=8, fmt="%.0f")
  59. pbest_plot = ax.scatter(pbest[0], pbest[1], marker='o', color='black', alpha=0.5)
  60. p_plot = ax.scatter(X[0], X[1], marker='o', color='blue', alpha=0.5)
  61. p_arrow = ax.quiver(X[0], X[1], V[0], V[1], color='blue', width=0.005, angles='xy', scale_units='xy', scale=1)
  62. gbest_plot = plt.scatter([gbest[0]], [gbest[1]], marker='*', s=100, color='black', alpha=0.4)
  63. ax.set_xlim([0, 5])
  64. ax.set_ylim([0, 5])
  65.  
  66.  
  67. def animate(i):
  68.     "Steps of PSO: algorithm update and show in plot"
  69.     title = 'Iteration {:02d}'.format(i)
  70.     # Update params
  71.     update()
  72.     # Set picture
  73.     ax.set_title(title)
  74.     pbest_plot.set_offsets(pbest.T)
  75.     p_plot.set_offsets(X.T)
  76.     p_arrow.set_offsets(X.T)
  77.     p_arrow.set_UVC(V[0], V[1])
  78.     gbest_plot.set_offsets(gbest.reshape(1, -1))
  79.     return ax, pbest_plot, p_plot, p_arrow, gbest_plot
  80.  
  81.  
  82. anim = FuncAnimation(fig, animate, frames=30, interval=100, blit=False, repeat=True)
  83. anim.save("PSO.gif", dpi=120, writer="imagemagick")
  84. plt.show()
  85.  
  86. print("PSO found best solution at f({})={}".format(gbest, gbest_obj))
  87. print("Global optimal at f({})={}".format([x_min, y_min], f(x_min, y_min)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement