Advertisement
Guest User

Untitled

a guest
Apr 16th, 2021
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import random
  4. import math
  5.  
  6. DIM = 80 # dimensionality of problem
  7. ME = 100 # number of epochs
  8. AXIS = 500 # -AXIS, AXIS is range for search space
  9.  
  10. class Molecule:
  11.     def __init__(self):
  12.         self.pos = [random.uniform(-AXIS, AXIS) for _ in range(DIM)]
  13.         self.fit = self.get_fit()
  14.         self.vel = [0.00 for _ in range(DIM)]
  15.         self.mass = 0.00
  16.  
  17.     def get_fit(self):
  18.         # schwefel function, minimum is 0
  19.         summ = 0
  20.         for d in self.pos:
  21.             summ += (d * math.sin(math.sqrt(abs(d))))
  22.         return (418.9829 * DIM) - summ
  23.    
  24.     def __lt__(self, other):
  25.         return self.fit < other.fit
  26.  
  27. def fun():
  28.     eps = 0.001 # epsilon
  29.     pop = []
  30.    
  31.     for i in range(1000):
  32.         new_molecule = Molecule()
  33.         pop.append(new_molecule)
  34.     temp = 1000 # temperature of the system initially
  35.     k = 1000 # boltzman constant
  36.     a, b = 0.5, 0.2
  37.     for e in range(ME):
  38.         pop.sort() # sort molecules by fitness
  39.        
  40.         avg_fit = sum(a.fit for a in pop)/len(pop) # get avg fitness
  41.        
  42.         best = pop[0].fit # best fitness is top of pop
  43.         worst = pop[-1].fit # worst is bottom
  44.        
  45.         print(f'{best:.4}')
  46.        
  47.         temp = temp - (1 / avg_fit)
  48.        
  49.         for agent in pop:
  50.             # for each agent, init its mass
  51.             agent.mass = (agent.fit - worst) / (best - worst)
  52.             for d in range(DIM):
  53.                 # for each dimension, calculate new velocity and position
  54.                 agent.vel[d] += math.sqrt((3*k*temp)/(agent.mass + eps))
  55.                 agent.pos[d] += agent.vel[d]
  56.                 agent.pos[d] += (b - (a / (2*math.pi)) * \
  57.                     math.sin(2*math.pi * agent.pos[d])) % 1
  58.                 if agent.pos[d] < -AXIS or agent.pos[d] > AXIS:
  59.                     # if molecule outside of range, place randomly
  60.                     agent.pos[d] = random.uniform(-AXIS, AXIS)
  61.             agent.fit = agent.get_fit() # update molecule's fitness
  62.  
  63. if __name__ == '__main__':
  64.     fun()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement