Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.89 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4. t = np.loadtxt('f2.txt')
  5.  
  6.  
  7. def random_result(dim):
  8. res = np.zeros(t.size, dtype=np.int8)
  9. y = np.random.randint(0, dim[0], dim[1])
  10. x = np.arange(0, dim[1], dtype=np.int8)
  11. res2 = res.reshape(dim)
  12. res2[y, x] = 1
  13. return res2
  14.  
  15.  
  16. def wage(res):
  17. return np.max(np.sum(t * res, 1))
  18.  
  19.  
  20. def mutate(res):
  21. new = res.copy()
  22. np.random.shuffle(new[:, np.random.randint(0, res.shape[1])])
  23. return new
  24.  
  25.  
  26. def start_temperature(res, prob):
  27. sum_wage = 0.0
  28. res_wage = wage(res)
  29. ind = 0
  30. while ind < 10:
  31. mod_wage = wage(mutate(res))
  32. if mod_wage > res_wage:
  33. sum_wage += (res_wage - mod_wage)
  34. ind += 1
  35. return (sum_wage/10.)/np.log(prob)
  36.  
  37.  
  38. def next_temperature(step, start):
  39. return start/(step + 1)
  40.  
  41.  
  42. def simulated_annealing(plot, temp_prob):
  43. result = random_result(t.shape)
  44. result_wage = wage(result)
  45.  
  46. max_iteration = 1000
  47. start_temp = start_temperature(result, temp_prob)
  48.  
  49. iteration_array = np.arange(max_iteration)
  50. temperature_array = np.zeros(max_iteration)
  51. result_wage_array = np.zeros(max_iteration)
  52.  
  53. for i in range(0, max_iteration):
  54. temperature = next_temperature(i, start_temp)
  55. new = mutate(result)
  56. new_wage = wage(new)
  57. delta = new_wage - result_wage
  58. if delta < 0:
  59. result = new
  60. result_wage = new_wage
  61. elif np.random.sample() < np.exp(-delta / temperature):
  62. result = new
  63. result_wage = new_wage
  64.  
  65. temperature_array[i] = temperature
  66. result_wage_array[i] = result_wage
  67.  
  68. if plot:
  69. plt.subplot(2, 1, 1)
  70. plt.plot(iteration_array, result_wage_array)
  71. plt.subplot(2, 1, 2)
  72. plt.plot(iteration_array, temperature_array)
  73. plt.show()
  74.  
  75. return result_wage
  76.  
  77. if __name__ == "__main__":
  78. print simulated_annealing(True, 0.8)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement