|
import numpy as np
|
|
import time
|
|
|
|
|
|
def rastrigin_function(x):
|
|
A = 10
|
|
return A * len(x) + np.sum(x**2 - A * np.cos(2 * np.pi * x))
|
|
|
|
|
|
SN = 10000
|
|
MCN = 100000
|
|
limit = 50
|
|
dimensionality = 2
|
|
|
|
|
|
food_sources = np.random.uniform(-5.12, 5.12, size=(SN, dimensionality))
|
|
trial = np.zeros(SN)
|
|
|
|
|
|
start_time = time.time()
|
|
|
|
for cyc in range(1, MCN + 1):
|
|
|
|
for i in range(SN):
|
|
x_hat = food_sources[i] + np.random.uniform(-0.5, 0.5, size=(dimensionality,))
|
|
if rastrigin_function(x_hat) < rastrigin_function(food_sources[i]):
|
|
food_sources[i] = x_hat
|
|
trial[i] = 0
|
|
else:
|
|
trial[i] += 1
|
|
|
|
|
|
probabilities = 1 / (1 + np.exp(-trial))
|
|
onlooker_indices = np.random.choice(SN, size=SN, p=probabilities / probabilities.sum())
|
|
|
|
for i in onlooker_indices:
|
|
x_hat = food_sources[i] + np.random.uniform(-0.5, 0.5, size=(dimensionality,))
|
|
if rastrigin_function(x_hat) < rastrigin_function(food_sources[i]):
|
|
food_sources[i] = x_hat
|
|
trial[i] = 0
|
|
else:
|
|
trial[i] += 1
|
|
|
|
|
|
max_trial_index = np.argmax(trial)
|
|
if trial[max_trial_index] > limit:
|
|
food_sources[max_trial_index] = np.random.uniform(-5.12, 5.12, size=(dimensionality,))
|
|
trial[max_trial_index] = 0
|
|
|
|
end_time = time.time()
|
|
|
|
|
|
best_solution = food_sources[np.argmin([rastrigin_function(x) for x in food_sources])]
|
|
|
|
print("Best solution:", best_solution)
|
|
print("Objective function value at best solution:", rastrigin_function(best_solution))
|
|
print("Time taken:", end_time - start_time, "seconds")
|
|
|