def search(self): # ## main loop while True: # for each time step (generation) for i in xrange(self.n): # #for each climber i yield # ## peek: take a look to a close to this position: xtmp xtmp = self.x[i] + pm.randin(-self.maxstep, self.maxstep) xnew, fnew = self.f(xtmp) if self.isbetterORequal(fnew, self.fx[i]): self.updatex(xnew, fnew, i)
def search(self): v = np.array([randin(-self.maxstep, self.maxstep) for _ in xrange(self.n)]) # initial velocities of the particles p = self.x.copy() # best known position of each particle. make a hard copy of x fp = self.fx.copy() # ## main loop while True: for i in xrange(self.n): # #for each particle yield # give control to caller. It will log and decide whether to stop. # ## old values xo = self.x[i].copy() vo = v[i].copy() po = p[i].copy() rp = np.random.uniform(0, 1) # # produce a new position rg = np.random.uniform(0, 1) # new velocity # TODO: restart randomly when po-xo is very close to # xbest-xo. Or xnew is too close to xbest vtmp = self.conf * (vo * self.w + (po - xo) * rp * self.psip + (self.xbest - xo) * rg * self.psig) xtmp = xo + vtmp if np.array_equal(xtmp, xo): print('xo:{}, vtmp:{}, xtmp:{}, lb:{}, ub:{}'.format( xo, vtmp, xtmp, self.problem.lb, self.problem.ub)) assert(False) xnew, fnew = self.f(xtmp); yield if np.array_equal(xnew, xo): print('xo:{}, vtmp:{}, xtmp:{}, xnew:{}, lb:{}, ub:{}'.format( xo, vtmp, xtmp, xnew, self.problem.lb, self.problem.ub)) #raise Exception('baaad') self.updatex(xnew, fnew, i) v[i] = xnew - xo # correct velocity if fnew > fp[i]: # # update personal best #self.drawpersonalbestpath(p[i], xnew, i) # p[i] = xnew.copy() # fp[i] = fnew.copy() updatepersonalbest(xnew, fnew, i, p, fp)
def chemotaxis(self, c_best, cells, costc, healthc, j): for i in xrange(len(cells)): ### To-Do : Each bac. moves simultaneously #### sum_nutrients = 0.0 # # Cost,Fitness(Health) of cells before moving to another location inter = self.compute_inter(cells, i) # # interaction before tumbling. c = self.problem.height(cells[i]) # # cost before tumbling. costc[i] = c fitness = c + inter healthc[i] = fitness if c_best == None or costc[i] > self.problem.height(c_best): c_best = cells[i].copy() sum_nutrients += healthc[i] for m in xrange(self.Ns): step = randin(-self.maxstep, self.maxstep) # # Tumbled cells newcell = cells[i] + step if self.isdraw: self.problem.visualiser.drawpath() cells[i] = newcell inter = self.compute_inter(cells, i) # # interaction while swimming. c = self.problem.height(cells[i]) costc[i] = c newfitness = c + inter if costc[i] > self.problem.height(c_best): c_best = cells[i].copy() if newfitness < fitness: break else: '''The bacterium changes its position only if the modified objective function value is less than the previous one''' cells[i] = newcell fitness = newfitness healthc[i] += newfitness # # healthc = sum_nutrients costc[i] = c print 'chemotaxis ', j, ' f = ', min( healthc), 'cost = ', self.problem.height(c_best) return c_best, cells, costc, healthc
def search(self): v = np.array([randin(-self.maxstep, self.maxstep) for _ in xrange(self.n)]) # initial velocities of the particles p = self.x.copy() # best known position of each particle. make a hard copy of x fp = self.fx.copy() self.hcmaxstep = self.maxstep / 2 # ## main loop while True: for i in xrange(self.n): # #for each particle yield # give control to caller. It will log and decide whether to stop. # ## old values xo = self.x[i].copy() vo = v[i].copy() po = p[i].copy() rp = np.random.uniform(0, 1, xo.shape) # # produce a new position rg = np.random.uniform(0, 1, xo.shape) # new velocity # TODO: restart randomly when po-xo is very close to xbest-xo. Or xnew is too close to xbest vtmp = vo * self.w + (po - xo) * rp * self.psip + (self.xbest - xo) * rg * self.psig xtmp = xo + vtmp #produce a new temporary position xnew, fnew = self.f(xtmp);yield # correct position, compute its f, and update self.fbest and self.xbest self.updatex(xnew, fnew, i) #update self.x[i],self.fx[i], and animate xnew, fnew = self.hillclimb(i, self.d);yield # do a Hill Climb at this new position. v[i] = xnew - xo # correct velocity if fnew > fp[i]: # # update personal best self.drawpersonalbestpath(p[i], xnew, i) p[i] = xnew.copy() fp[i] = fnew
def search(self): vis = self.problem.visualiser cost = self.problem.cost cells = self.positions isdraw = self.isdraw rand = np.random.uniform Ned = self.Ned Nc = self.Nc Ns = self.Ns Nre = self.Nre Ped = self.Ped bestpos = self.bestpos ### Initialization #### self.maxstep = (self.problem.ub - self.problem.lb) / self.maxstepdivisor S = cells.shape[0] costc = np.array([cost(pos) for pos in cells]) # the cost of the positions healthc = costc.copy() idbest = costc.argmin() # the index of the more healthy position colors = [] bestcolor = (1, 1, 0) def drawbest(pos): vis.drawposition(pos, color=bestcolor, scale_factor=5) if self.isdraw: drawbest(cells[idbest]) for pos in cells: color = tuple(np.random.uniform(0, 1, (3, )).tolist()) print 'color', color colors.append(color) vis.drawposition(pos, color=color) bestpos = cells[idbest].copy() # print 'Best position of the cells is .....' , bestpos; maxhei = costc[idbest] # print 'Min cost of the position at the beginning is.... ', maxhei; iteration = 0 r = [] while True: yield ( bestpos, maxhei, iteration ) # give control to caller. It will log and decide whether to stop. if iteration > 3: z = range(iteration) # plt.plot( r, 'r-' ) # plt.title( 'Negative Rastrigin with Genetic Algorithm ' ) # plt.xlabel( 'Iterations' ) # plt.ylabel( 'Fitness' ) # plt.show() iteration = iteration + 1 print 'Iteration is : .............. : ', iteration for l in xrange(Ned): for k in xrange(Nre): c_best = None for j in xrange(Nc): c_best, cells, costc, healthc = self.chemotaxis( c_best, cells, costc, healthc, j) if bestpos == None or self.problem.height( c_best) > self.problem.height(bestpos): bestpos = c_best # # The best of each chemotaxis step print 'The best cost : ', cost(bestpos) # # Sort by Cell Health ascending order(Increasing) # #order = np.argsort(healthc) # #cells = cells[order] cells = [ x for (y, x) in sorted(zip(healthc, cells), reverse=False) ] # # healthc == sum_nutrients ### Selection : first best healthy doubled ### '''Reproduction: The least healthy bacteria eventually die while each of the healthier bacteria (those yielding lower value of the objective function) asexually split into two bacteria, which are then placed in the same location. This keeps the swarm size constant.''' cells = cells[:S / 2] + cells[:S / 2] # ## Create cell at random Location '''Eliminate and disperse each bacterium, which results in in keeping the number of bacteria in the population constant.''' for i in xrange(len(cells)): if rand() <= Ped: cells[i] = randin(-self.maxstep, self.maxstep)
def search(self): ## if we want to do our own custom drawing: if self.customdraw == True: # shut down default automatic drawing. So that we can do our own self.isdraw = False # we will use self.problem.visualiser methods directly. let us # give it an easier name. vis = self.problem.visualiser ## let the visualiser draw the surface: # framework requiers vis to have a title vis.title = 'PSO - ' + self.problem.name # init() draws the surface. It accepts mlab.figure() keyword # arguments as # mlab_figure_opt dictionary. In the same way, it accepts # mlab.surf(), mlab.axes(), mlab.view(), mlab.title(), # mlab.outline() keyword arguments. vis.init(mlab_figure_opt = {'bgcolor':(.5, .5, .5)}, mlab_title_opt = {'size':0.4} ) ## reset the assessment count. It was incremented while drawing ## the surface. self.problem._assessmentcnt = 0 v = np.array([randin(-self.maxstep, self.maxstep) for _ in xrange(self.n)]) # initial velocities of the particles p = self.x.copy() # best known position of each particle. make a hard copy of x fp = self.fx.copy() ## draw initial positions of the particles. drawposition() can take ## any keyword argument mlab.points3d() accepts. See its documentation ## on ## mayavi web site. for e in self.x: vis.drawposition(e, color = (1, 0, .5)) # ## main loop while True: for i in xrange(self.n): # #for each particle yield # give control to caller. It will log and decide whether to stop. # ## old values xo = self.x[i].copy() vo = v[i].copy() po = p[i].copy() rp = np.random.uniform(0, 1) # # produce a new position rg = np.random.uniform(0, 1) # new velocity # TODO: restart randomly when po-xo is very close to xbest-xo. Or xnew is too close to xbest vtmp = self.conf * (vo * self.w + (po - xo) * rp * self.psip + (self.xbest - xo) * rg * self.psig) #xtmp = xo + vtmp xtmp = self.problem.stepby(xo, vtmp) xnew, fnew = self.f(xtmp); yield # correct position, compute its f, and update self.fbest and self.xbest # just before updating the position, draw your path. # drawpath accepts any argument mlab.plot3d accepts. See its # documentation in mayavi web page. vis.drawpath(self.x[i], xnew, color = (0.1, 1, 1)) self.updatex(xnew, fnew, i) v[i] = xnew - xo # correct velocity if fnew > fp[i]: # # update personal best p[i] = xnew.copy() fp[i] = fnew