def init_trace(n_particles): """ Constructs the tracing log which tracks the movement of particles in 2 dimensions only.. --We build these dimensions as ("objective(particle)", "-20") """ for i in range(n_particles): vals_ = particles[i].get_vals() movement_trace.append({"id": i, "x": objective(vals_), "y": -100, "new_x": objective(vals_), "new_y": -100})
def init_particles(n_particles, min_, max_, dimensions): """ Declaring the particles. """ for _ in range(n_particles): new_particle = Particle() val_ = random.sample(range(min_, max_), dimensions) p_best = objective(val_) new_particle.set_vals(val_) new_particle.set_pbest(p_best) particles.append(new_particle)
def set_trace(i, old, new): """ Updates the location trace for the particle """ movement_trace.append({"id": i, "x": objective(old), "y": -100, "new_x": objective(new), "new_y": -100})
def optimize(self): """ trains/fits the particles to catch the target under the given number of pre-fixed iterations """ victor = 0 found = False while not self.done: if self.epoch < self.max_epochs: for i in range(self.max_particles): if self.objective(particles[i].get_vals()) == self.target: victor = i self.done = True found = True print "FOUND!", self.objective(particles[i].get_vals()), self.target break new_best = self.get_nearest() a_particle = particles[self.g_best] if math.fabs(self.target - self.objective(particles[new_best].get_vals())) < math.fabs( self.target - self.objective(a_particle.get_vals()) ): self.g_best = new_best self.set_velocity(self.g_best) self.update_particles(self.g_best) self.epoch += 1 else: self.done = True if found: print "particle %d is the victor: %s" % (victor, str(particles[victor].get_vals())) else: print "exact match not found. %d is the nearest: %s" % (victor, str(particles[victor].get_vals())) print "epochs: %d out of %d completed" % (self.epoch, self.max_epochs) # --add the achieved movement_trace.append( { "id": -1, "x": objective(particles[victor].get_vals()), "y": -100, "new_x": objective(particles[victor].get_vals()), "new_y": -100, } ) # --add the target movement_trace.append({"id": -2, "x": self.target, "y": -100, "new_x": self.target, "new_y": -100}) results = { "victor": particles[victor].get_vals(), "index": victor, "value": objective(particles[victor].get_vals()), "target_value": self.target, "max_epochs": self.epoch, "v_max": self.v_max, "n_particles": self.max_particles, } # --visualize if demanded.. if self.visualize: write_trace(movement_trace, results) print "visual trace created..please check viz/pso_index.html" return results