simulatedAnnealing.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. """Plots the evolution of the simulated annealing algorithm from a log file"""
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import pickle
  5. import pandas
  6. from scipy.signal import savgol_filter
  7. from analysis import utils
  8. def deroll(arr, limits, start=0):
  9. """Derolls a log array. It returns a likely guess of what an array would
  10. have been before applying a mod operator to bring it into the limits
  11. region. Example, for limits = [0, 1] the array [0.5, 0.7, 0.9, 0.1] would
  12. return [0.5, 0.7, 0.9, 1.1].
  13. Parameters:
  14. arr (array): array to deroll
  15. limit (tuple): (lower limit, upper limit)
  16. start (int): the first start values of the array will not be derolled
  17. Returns:
  18. The derolled array.
  19. """
  20. for i in range(start,len(arr)-1): # Do not deroll before start
  21. if np.abs(arr[i+1]-arr[i]) > (limits[1]-limits[0])/2:
  22. # Continue the array in the closest possible way
  23. if arr[i+1]>arr[i]: arr[i+1:] -= (limits[1]-limits[0])
  24. else: arr[i+1:] += (limits[1]-limits[0])
  25. return arr
  26. def returnBars(arr, n):
  27. """Calculates the 10th-90th percentile running confidence interval
  28. Parameters:
  29. arr (arr): The array to calculate error bars for
  30. n (int): The smoothing of the confidence interval
  31. Returns:
  32. The smoothed running confidence interval
  33. """
  34. r = pandas.Series(arr).rolling(window = n, center = False)
  35. s1, s2 = r.quantile(.90), r.quantile(.1)
  36. return savgol_filter(s1[n:], 101, 3), savgol_filter(s2[n:], 101, 3)
  37. # Load the data saved by the simulating annealing algorithm
  38. log = pickle.load(open('data/logs/log.pickle', "rb" ) )[:1400]
  39. # Define the parameters we wish to plot
  40. mask = [0,1,2,3,5,7,8] #Non-fixed parameters
  41. limits = np.array([[0, np.pi], [-np.pi, np.pi],
  42. [0, np.pi], [-np.pi, np.pi],
  43. [.5,1.0], [.55,.8], [.55,.8]])
  44. labels = [r'$i_1$ / rad', r'$\omega_1$ / rad',
  45. r'$i_2$ / rad', r'$\omega_2$ / rad',
  46. 'e', r'$R_1$', r'$R_2$', r'$\mu$']
  47. ticks = [[0, np.pi], [-np.pi,0, np.pi],
  48. [0, np.pi],[-np.pi, 0, np.pi],
  49. [.5, 1.0], [.55, .8], [.55, .8]]
  50. ticklabels = [[0,r'$\pi$'],[r'$-\pi$',0,r'$\pi$'],
  51. [0,r'$\pi$'],[r'$-\pi$',0,r'$\pi$'],
  52. ['.5','1.0'], ['.55','.8'], ['.55','.8']]
  53. # Mask away the parameters we don't want to plot
  54. scores = np.array([l[0] for l in log])
  55. paramss = np.array([l[1] for l in log])[:,mask]
  56. # Fix conventions for inclination
  57. paramss[:,0] = paramss[:,0] - np.pi
  58. paramss[:,2] = np.pi - paramss[:,2]
  59. # Start plotting
  60. i = np.arange(len(log))
  61. f, axs = plt.subplots(1+len(paramss[0]), 1, figsize=(10, 10),
  62. sharex=True, gridspec_kw = {'height_ratios':[2., 1., 1, 1, 1, 1, 1, 1]})
  63. plt.tight_layout()
  64. utils.stylizePlot(axs)
  65. # Plot metric
  66. axs[0].scatter(i, scores, marker='x', c='black', s=5, linewidth=.5)
  67. axs[0].fill_between(i[20:], *returnBars(scores, 20), color='r', alpha=.2)
  68. utils.setSize(axs[0], x=(0, None), y=(0.8, None))
  69. utils.setAxes(axs[0], y='Metric')
  70. # Get twin axis to mark temperature in it
  71. ax2 = axs[0].twiny()
  72. ax2.set_xscale('log')
  73. ax2.set_xlabel('Temperature', fontsize=14)
  74. ax2.invert_xaxis()
  75. ax2.set_xlim((.25, 0.015129))
  76. ax2.set_xticks([.2, .1, .09, .08, .07, .06, .05, .04, .03, .02, .01])
  77. ax2.set_xticklabels([str(i)
  78. for i in [.2, .1, .09, .08, .07, .06, .05, .04, .03, .02, .01]])
  79. # Plot parameters one by one
  80. for j in range(0, len(paramss[0])):
  81. utils.setSize(axs[j+1], x=(0, len(log)), y=limits[j])
  82. axs[j+1].set_ylabel(labels[j], fontsize=14)
  83. axs[j+1].set_yticks(ticks[j])
  84. axs[j+1].set_yticklabels(ticklabels[j])
  85. # Be careful plotting cyclic parameters
  86. derolled = deroll(paramss[:,j], limits[j], start=500)
  87. bar1, bar2 = returnBars(paramss[:,j], 20)
  88. for k in range(-3, 3): #
  89. # Plot the confidence intervals an data multiple times
  90. # to deal with cyclic parameters
  91. axs[j+1].scatter(i, derolled + k*(limits[j][1]-limits[j][0]),
  92. marker='x', c='black', s=5, linewidth=.5)
  93. axs[j+1].fill_between(i[20:], bar1 + k*(limits[j][1]-limits[j][0]),
  94. bar2 + k*(limits[j][1]-limits[j][0]), color='r', alpha=.2)
  95. f.align_ylabels(axs[:])
  96. axs[-1].set_xlabel('Iteration', fontsize=14)
  97. plt.show()