gpt-4-0314· OpenAI
WildChat-4.8M (AI2)
import random import math import numpy as np import matplotlib.pyplot as plt class…
- User
import random import math import numpy as np import matplotlib.pyplot as plt
class SSA(): def init(self, function, lb, ub, dim, colony_size, iterations): self.function = function self.lb = lb self.ub = ub self.dim = dim self.colony_size = colony_size self.iterations = iterations
def init_spiders(self): spiders = np.zeros((self.colony_size, self.dim)) for i in range(self.colony_size): for j in range(self.dim): spiders[i][j] = random.uniform(self.lb[j], self.ub[j]) return spiders def move_spiders(self, spiders, better_spider): for i in range(self.colony_size): r = np.random.rand(1, self.dim) q = np.random.rand(1, self.dim) x_new = spiders[i, :] + r * (better_spider - spiders[i, :]) + q * (spiders[i, :] - np.mean(spiders, axis=0)) spiders[i, :] = np.clip(x_new, self.lb, self.ub) return spiders def run(self): spiders = self.init_spiders() plt.ion() plt.show() fig = plt.figure() ax = fig.add_subplot(1, 1, 1) line1, = ax.plot([], [], 'b-') ax.set_xlim(self.lb[0], self.ub[0]) ax.set_ylim(self.lb[1], self.ub[1]) ax.set_xlabel('x1') ax.set_ylabel('x2') ax.set_title('Objective Function') f_best = float('inf') x_best = np.zeros(self.dim) x_history = np.zeros((self.iterations, self.dim)) for it in range(self.iterations): for i in range(self.colony_size): fitness = self.function(spiders[i, :]) if fitness < f_best: f_best = fitness x_best = spiders[i, :] x_history[it, :] = x_best better_spider = x_best spiders = self.move_spiders(spiders, better_spider) line1.set_xdata(x_history[:it, 0]) line1.set_ydata(x_history[:it, 1]) - Assistant
plt.draw() plt.pause(0.01)
plt.ioff() plt.show() return x_best, f_bestObjective function to minimize
def objective_function(x): return math.sin(x[0]) * math.sin(x[1]) / (x[0] * x[1])
Search space bounds
lb = [0.1, 0.1] ub = [10, 10]
SSA parameters
dim = 2 colony_size = 20 iterations = 100
Run SSA
ssa = SSA(objective_function, lb, ub, dim, colony_size, iterations) x_best, f_best = ssa.run()
print("Best solution found by SSA:") print("x =", x_best) print("f(x) =", f_best)