Currently I have this implementation:
import optproblems import optproblems.cec2005 from numpy import array import random class Particle: def __init__(self,initial): num_dimensions = len(initial) self.position_i=[] # particle position self.velocity_i=[] # particle velocity self.pos_best_i=[] # best position individual self.err_best_i=-1 # best error individual self.err_i=-1 # error individual for i in range(0,num_dimensions): self.velocity_i.append(random.uniform(-1,1)) self.position_i.append(initial[i]) # evaluate current fitness def evaluate(self,costFunc): self.err_i=costFunc(self.position_i) # check to see if the current position is an individual best if self.err_i<self.err_best_i or self.err_best_i==-1: self.pos_best_i=self.position_i self.err_best_i=self.err_i # update new particle velocity def update_velocity(self,pos_best_g): w=0.5 # constant inertia weight (how much to weigh the previous velocity) c1=1 # cognative constant c2=2 # social constant for i in range(0,num_dimensions): r1=random.random() r2=random.random() vel_cognitive=c1*r1*(self.pos_best_i[i]-self.position_i[i]) vel_social=c2*r2*(pos_best_g[i]-self.position_i[i]) self.velocity_i[i]=w*self.velocity_i[i]+vel_cognitive+vel_social # update the particle position based off new velocity updates def update_position(self,bounds): for i in range(0,num_dimensions): self.position_i[i]=self.position_i[i]+self.velocity_i[i] # adjust maximum position if necessary if self.position_i[i]>bounds[i][1]: self.position_i[i]=bounds[i][1] # adjust minimum position if neseccary if self.position_i[i]<bounds[i][0]: self.position_i[i]=bounds[i][0] class PSO_Class(): def __init__(self, test_function): self.testfunction = test_function def eval_fitness(self, individual): self.testfunction.evaluate(individual) return individual.objective_values def run(self,initial, bounds, num_particles, maxIterations): num_dimensions = len(initial) swarm=[] for i in range(0,num_particles): swarm.append(Particle(initial)) list = [] for i in range (0, len(swarm)): list.append(swarm[i].position_i) test_individual = optproblems.base.Individual([1,2,3,4,5,6,7,8,9,10]) fitness = self.eval_fitness(test_individual) print(fitness) #do some updates. test_individual = optproblems.base.Individual([11,12,13,14,15,90,17,18,19,20]) fitness = self.eval_fitness(test_individual) print(fitness) benchmark_f1 = optproblems.cec2005.F1(10) initial=[-10,10] # initial starting location [x1,x2...] bounds=[(-100,100),(-100,100)] algorithm1 = PSO_Class(benchmark_f1) algorithm1.run(initial, bounds, num_particles = 10, maxIterations=100)What I am trying to do is pass the values to the individual as a list and then use the PSO to iterate over the problem space till optimal or max iterations is reached. I am a bit lost now however and would really appreciate some help.