| import numpy as np
|
| import time
|
| import threading
|
|
|
|
|
| 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_lock = threading.Lock()
|
| trial_lock = threading.Lock()
|
| cyc_lock = threading.Lock()
|
| start_time_lock = threading.Lock()
|
|
|
| food_sources = np.random.uniform(-5.12, 5.12, size=(SN, dimensionality))
|
| trial = np.zeros(SN)
|
| cyc = 1
|
| start_time = None
|
|
|
|
|
| def employed_bees_phase():
|
| global food_sources, trial
|
| 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]):
|
| with food_sources_lock:
|
| food_sources[i] = x_hat
|
| trial[i] = 0
|
| else:
|
| with trial_lock:
|
| trial[i] += 1
|
|
|
|
|
| def onlooker_bees_phase():
|
| global food_sources, trial
|
| 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]):
|
| with food_sources_lock:
|
| food_sources[i] = x_hat
|
| trial[i] = 0
|
| else:
|
| with trial_lock:
|
| trial[i] += 1
|
|
|
|
|
| def scout_bee_phase():
|
| global food_sources, trial
|
| max_trial_index = np.argmax(trial)
|
| if trial[max_trial_index] > limit:
|
| with food_sources_lock:
|
| food_sources[max_trial_index] = np.random.uniform(-5.12, 5.12, size=(dimensionality,))
|
| trial[max_trial_index] = 0
|
|
|
|
|
| with start_time_lock:
|
| start_time = time.time()
|
|
|
|
|
| employed_thread = threading.Thread(target=employed_bees_phase)
|
|
|
|
|
| onlooker_thread = threading.Thread(target=onlooker_bees_phase)
|
|
|
|
|
| scout_thread = threading.Thread(target=scout_bee_phase)
|
|
|
|
|
| employed_thread.start()
|
| onlooker_thread.start()
|
| scout_thread.start()
|
|
|
|
|
| employed_thread.join()
|
| onlooker_thread.join()
|
| scout_thread.join()
|
|
|
|
|
| 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")
|
|
|