Advertisement
11eimilia11

leo stuff

Dec 6th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. import numpy as np
  2. from SwarmPackagePy.intelligence import sw
  3.  
  4.  
  5. class pso(sw):
  6.  
  7.     def __init__(self, n, function, lb, ub, dimension, iteration, init=None, w=0.5, c1=1,
  8.                  c2=1):
  9.  
  10.         super(pso, self).__init__()
  11.  
  12.         if init is None:
  13.             self.__agents = np.random.uniform(lb, ub, (n, dimension))
  14.         else:
  15.             self.__agents = np.array(init)
  16.  
  17.         velocity = np.zeros((n, dimension))
  18.         self._points(self.__agents)
  19.  
  20.         Pbest = self.__agents[np.array([function(x)
  21.                                         for x in self.__agents]).argmin()]
  22.         Gbest = Pbest
  23.  
  24.         for t in range(iteration):
  25.  
  26.             r1 = np.random.random((n, dimension))
  27.             r2 = np.random.random((n, dimension))
  28.             velocity = w * velocity + c1 * r1 * (
  29.                 Pbest - self.__agents) + c2 * r2 * (
  30.                 Gbest - self.__agents)
  31.             self.__agents += velocity
  32.             self.__agents = np.clip(self.__agents, lb, ub)
  33.             self._points(self.__agents)
  34.  
  35.             Pbest = self.__agents[
  36.                 np.array([function(x) for x in self.__agents]).argmin()]
  37.             if function(Pbest) < function(Gbest):
  38.                 Gbest = Pbest
  39.  
  40.  
  41.         self._set_Gbest(Gbest)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement