Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.39 KB | None | 0 0
  1. import random
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. HMCR = 0.7  # вероятность выбора из гармоник в памяти
  6. PAR = 0.5  # вероятность модификации
  7. BW = 0.04
  8. counter = 0
  9.  
  10. harmony = [[-37.5, 23],
  11.            [-41, -36],
  12.            [47, -31],
  13.            [49, 11],
  14.            [17, 25]]
  15.  
  16. n = int(input("Iteration number = "))
  17. dimensions = [[-100, 100],
  18.               [-100, 100]]
  19.  
  20. res_plot = []
  21.  
  22. def fitness_function(v):
  23.     return v[0] * v[0] + v[1] * v[1]
  24.  
  25.  
  26. while counter < n:
  27.     worst_i = 0  # индекс максимального элемента в старой гармонии (для редактирования элемента списка)
  28.     best_i = 0  # индекс минимального элемента в новой гармонии (для считывания конкретного элемента в списке)
  29.     # т.к. в противном случае будет создаваться ссылка на существующий список
  30.  
  31.     i1 = np.random.randint(0, len(harmony), size=1)[0]
  32.     X1 = [None] * len(harmony[i1])
  33.     X1_flags = [False] * len(X1)
  34.     for j in range(len(harmony[i1])):
  35.         if random.random() < HMCR:
  36.             X1[j] = harmony[i1][j]
  37.             X1_flags[j] = True
  38.         else:
  39.             U1 = random.random()
  40.             X1[j] = dimensions[j][0] + U1 * (dimensions[j][1] - dimensions[j][0])
  41.  
  42.     for j in range(len(X1)):
  43.         if X1_flags[j] and random.random() < PAR:
  44.             N1 = np.random.normal()
  45.             u_sign = random.choice([-1, 1])
  46.             X1[j] = X1[j] + u_sign * BW * N1
  47.  
  48.     # нахождение худшего элемента в старой гармонии
  49.     worst_result = -65000
  50.     for i in range(len(harmony)):
  51.         res = fitness_function(harmony[i])
  52.         if res > worst_result:
  53.             worst_result = res
  54.             worst_i = i
  55.  
  56.     if fitness_function(X1) < worst_result:
  57.         harmony[worst_i] = X1
  58.  
  59.     counter += 1
  60.     min_i = -1
  61.     min_result = 65000
  62.     for i in range(len(harmony)):
  63.         res = fitness_function(harmony[i])
  64.         if res < min_result:
  65.             min_result = res
  66.             min_i = i
  67.  
  68.     print(harmony[min_i])
  69.     res_plot.append(harmony[min_i])
  70.     print(min_result)
  71.  
  72. plt.plot(res_plot)
  73. plt.ylabel('Best results:')
  74. plt.savefig("harmony.png")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement