Skip to content

Instantly share code, notes, and snippets.

@s4nyam
Created August 21, 2023 14:12
Show Gist options
  • Save s4nyam/0194856bcc56f1ad1f9875b472f62936 to your computer and use it in GitHub Desktop.
Save s4nyam/0194856bcc56f1ad1f9875b472f62936 to your computer and use it in GitHub Desktop.
A simple EC based optimisation for maximising sin(x)cos(y) with fitness landscape
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def fitness(x, y):
return np.sin(x) * np.cos(y)
mutation_range = 0.02
population = np.array([[np.random.uniform(-5, 5), np.random.uniform(-5, 5)]])
best_fitness = -np.inf
best_solution = None
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
def animate(i):
global population, best_fitness, best_solution
ax.cla()
x_vals = np.linspace(-5, 5, 100)
y_vals = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x_vals, y_vals)
Z = fitness(X, Y)
ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.8)
ax.scatter(population[:, 0], population[:, 1], fitness(population[:, 0], population[:, 1]), color='red', s=50)
for ind in population:
fit = fitness(ind[0], ind[1])
if fit > best_fitness:
best_fitness = fit
best_solution = ind
mutated_individual = best_solution + mutation_range * (np.random.rand(2) - 0.5)
population = np.array([mutated_individual])
ax.set_title(f'Generation {i+1}\nBest Fitness: {best_fitness:.3f}')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Fitness')
# Set view angle to track the individual
ax.view_init(elev=30, azim=30 + i * 2)
ani = FuncAnimation(fig, animate, frames=1000, interval=1000, repeat=False)
ani.save('evolution_animation.mp4', writer='ffmpeg', fps=30)
plt.close(fig)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment