def write_grid(gi, p): G = nx.read_gpickle('../benchmarks/atlas/' + str(gi) + '.gpickle') C = common.create_C(G) M = common.create_complete_M(len(G.nodes)) k = int(len(G.nodes) / 2) num_steps = 50 gamma, beta = 0, 0 grid, g_list = [], [] grid_max = 0 fig, ax = plt.subplots() print('0/' + str(num_steps) + '\t' + str(datetime.datetime.now().time())) for i in range(0, num_steps): for j in range(0, num_steps): state = dicke_ps_complete.qaoa([G, C, M, k, p], [gamma, beta]) exp = common.expectation(G, state) g_list.append(exp) if grid_max < exp: grid_max = exp #print('g: ' + str(gamma) + ', b: ' + str(beta) + ', exp: ' + str(exp)) gamma += pi / (2 * (num_steps - 1)) beta += pi / (num_steps - 1) gamma = 0 grid.append(g_list) g_list = [] print( str(i + 1) + '/' + str(num_steps) + '\t' + str(datetime.datetime.now().time())) grid = list(reversed(grid)) print('-------------- max grid <C>: ' + str(grid_max)) im = ax.imshow(grid, aspect='auto', extent=(0, pi / 2, 0, pi), interpolation='gaussian', cmap=cm.inferno_r) cbar = ax.figure.colorbar(im, ax=ax) cbar.ax.set_ylabel('$\\langle C \\rangle$', rotation=-90, va="bottom") plt.xlabel('$\\gamma$') plt.ylabel('$\\beta$') plt.title('$\\beta \\ vs \\ \\gamma$\nn=' + str(len(G.nodes)) + ', k=' + str(k) + \ ', p=' + str(p) + ', grid_size=' + str(num_steps) + 'x' + str(num_steps) + ', gi=' + str(gi)) #plt.scatter(opt[0], opt[1], s=50, c='yellow', marker='o') folder = 'grid/' if not os.path.exists(folder): os.mkdir(folder) pickle.dump([[len(G.nodes), k, p, num_steps, gi], grid], open(folder + str(gi) + '.grid', 'wb')) plt.show()
def temp_map(G, k, p, gi, exp_opt, prev, angles): num_steps = 30 gamma = 0 beta = 0 g_list, grid, graph_angles = [], [], [] grid_max = 0 fig, ax = plt.subplots() C = common.create_C(G) M = common.create_complete_M(len(G.nodes)) print('0/' + str(num_steps) + '\t' + str(datetime.datetime.now().time())) for i in range(0, num_steps): for j in range(0, num_steps): if p > 1: graph_angles.extend(prev[0]) graph_angles.append(gamma) if p > 1: graph_angles.extend(prev[1]) graph_angles.append(beta) state = dicke_ps_complete.qaoa([G, C, M, k, p], graph_angles) exp = common.expectation(G, state) g_list.append(exp) if grid_max < exp: grid_max = exp gamma += pi/(2*(num_steps-1)) graph_angles = [] beta += pi/(num_steps-1) gamma = 0 grid.append(g_list) g_list = [] print(str(i+1) + '/' + str(num_steps) + '\t' + str(datetime.datetime.now().time())) grid = list(reversed(grid)) print('-------------- max grid <C>: ' + str(grid_max)) print('-------------- max optm <C>: ' + str(exp_opt)) im = ax.imshow(grid, aspect='auto', extent=(0, pi/2, 0, pi), interpolation='gaussian', cmap=cm.inferno_r) cbar = ax.figure.colorbar(im, ax=ax) cbar.ax.set_ylabel('$\\langle C \\rangle$', rotation=-90, va="bottom") axes = plt.gca() axes.set_ylim([0, pi]) axes.set_xlim([0, pi/2]) plt.xlabel('$\\gamma$') plt.ylabel('$\\beta$') plt.title('$\\beta \\ vs \\ \\gamma$, opt_exp=' + str(exp_opt) + '\nn=' + str(len(G.nodes)) + ', k=' + str(k) + \ ', p=' + str(p) + ', grid_size=' + str(num_steps) + 'x' + str(num_steps) + ', gi=' + str(gi)) plt.scatter(angles[0], angles[1], s=50, c='yellow', marker='o') #plt.show() path = '3-reg/' + str(gi) + '/' if not os.path.exists(path): os.mkdir(path) plt.savefig(path + str(p) + '.png') plt.cla()
def main(G, k, p, num_steps): C = common.create_C(G) M = common.create_complete_M(len(G.nodes)) init = [[0, pi / 2] if i < p else [0, pi] for i in range(2 * p)] guess = [pi / 4 if i < p else pi / 2 for i in range(2 * p)] kwargs = {'method': 'L-BFGS-B', 'args': (G, C, M, k, p), 'bounds': init} optimal = basinhopping(opt, guess, minimizer_kwargs=kwargs, niter=num_steps, disp=True) return -optimal.fun, optimal.x
def dicke_ps_ring(G, k, p, num_steps): C = common.create_C(G) M = common.create_ring_M(len(G.nodes)) kwargs = { 'method': 'L-BFGS-B', 'args': (G, C, M, k, p), 'bounds': [[0, pi / 2], [0, pi]] } optimal = basinhopping(opt, np.array([pi / 4, pi / 2]), minimizer_kwargs=kwargs, niter=num_steps) return -optimal.fun, optimal.x
def ring_ps_ring(G, k, p, num_steps): C = common.create_C(G) M = common.create_M(G) exp_arr = [] angle_arr = [] num_init = int(comb(len(G.nodes), k)) for m in range(0, num_init): kwargs = {'method': 'L-BFGS-B', 'args': (G, C, M, k, p, m), 'bounds': [[0,pi/2],[0,pi],[0,pi]]} optimal = basinhopping(opt, np.array([pi/4, pi/2, pi/2]), minimizer_kwargs=kwargs, niter=num_steps) angle_arr.append(optimal.x) exp_arr.append(-optimal.fun) avg = 0 for entry in exp_arr: avg += entry*(1/num_init) return avg, angle_arr
def work(gi, p, s): G = nx.read_gpickle('../benchmarks/atlas/' + str(gi) + '.gpickle') C = common.create_C(G) M = common.create_complete_M(len(G.nodes)) k = int(len(G.nodes) / 2) best_exp = -1 for j in range(s): angles = [ random.uniform(0, pi / 2) if i < p else random.uniform(0, pi) for i in range(2 * p) ] exp = common.expectation( G, dicke_ps_complete.qaoa([G, C, M, k, p], angles)) if exp > best_exp: best_exp = exp print('rank: ' + str(rank) + ', best_exp: ' + str(best_exp)) return best_exp
def monte_carlo(gi, p, s, num_samples): G = nx.read_gpickle('../benchmarks/atlas/' + str(gi) + '.gpickle') C = common.create_C(G) M = common.create_complete_M(len(G.nodes)) k = int(len(G.nodes) / 2) data = [] for i in range(num_samples): max_exp = -1 for j in range(s): angles = [ random.uniform(0, pi / 2) if i < p else random.uniform(0, pi) for i in range(2 * p) ] exp = common.expectation( G, dicke_ps_complete.qaoa([G, C, M, k, p], angles)) if exp > max_exp: max_exp = exp data.append(max_exp) return data
def restricted_MLHS(G, k, p, num_samples, prev): C = common.create_C(G) M = common.create_complete_M(len(G.nodes)) num_steps = 2 init = [[0, pi / 2], [0, pi]] sample_g, sample_b = LHS(1, num_samples) exp, angles = -1, [] for i in range(num_samples): kwargs = { 'method': 'L-BFGS-B', 'args': (G, C, M, k, p, prev), 'bounds': init } optimal = basinhopping(opt_restricted, [sample_g[i], sample_b[i]], minimizer_kwargs=kwargs, niter=num_steps, disp=True) if -optimal.fun > exp: exp = -optimal.fun angles = optimal.x return exp, angles
plt.bar([5, 6, 7, 8, 9, 10], data) plt.title('<C> histogram for p = ' + str(p) + ', gi=502, samples=' + str(num_samples)) plt.xlabel('Value of measured solution') plt.ylabel('Probability of measuring') axes = plt.gca() axes.set_ylim([0, 0.5]) if not os.path.exists('hist/fig/'): os.mkdir('hist/fig/') plt.savefig('hist/fig/p' + str(p) + '.png') #plt.show() plt.cla() if __name__ == '__main__': G = nx.read_gpickle('atlas/502.gpickle') C = common.create_C(G) M = common.create_ring_M(len(G.nodes)) k = int(len(G.nodes) / 2) num_samples = 1000 max_p = 10 best_g, best_b = [], [] for p in range(1, max_p + 1): found = False data = [0] * 6 print('--------- p = ' + str(p) + '----------') path = 'hist/' + str(p) + '.hist' if os.path.exists(path): with open(path, 'rb') as f: try:
def temp_map(): global G random.seed(4) num_nodes = 10 G = nx.fast_gnp_random_graph(num_nodes, 0.5) while not nx.is_connected(G): G = nx.fast_gnp_random_graph(num_nodes, 0.5) k = int(len(G.nodes) / 2) C = common.create_C(G, k) #M = common.create_complete_M(len(G.nodes), k) M = common.create_ring_M(len(G.nodes), k) p = Process(target=draw) p.start() num_steps = 50 gamma, beta = 0, 0 g_list, grid = [], [] grid_min = -1 grid_max = 0 fig, ax = plt.subplots() print('0/' + str(num_steps) + '\t' + str(datetime.datetime.now().time())) for i in range(0, num_steps): for j in range(0, num_steps): val = qaoa(gamma, beta, G, C, M, k) g_list.append(val) if grid_max < val: grid_max = val if grid_min == -1: grid_min = val if grid_min > val: grid_min = val gamma += 2 * pi / (num_steps - 1) beta += pi / (2 * (num_steps - 1)) gamma = 0 grid.append(g_list) g_list = [] print( str(i + 1) + '/' + str(num_steps) + '\t' + str(datetime.datetime.now().time())) grid = list(reversed(grid)) size = 15 axis_size = 17 im = ax.imshow(grid, aspect='auto', extent=(0, 2, 0, 0.5), interpolation='gaussian', cmap=cm.inferno_r) cbar = ax.figure.colorbar(im, ax=ax) #cbar = ax.figure.colorbar(im, ax=ax, ticks=[]) #cbar.ax.tick_params(labelsize=size) #cbar.ax.set_ylabel('$\\langle H_P \\rangle$', rotation=0, va="bottom") #cbar.ax.get_yaxis().labelpad = 28 #cbar.ax.set_ylabel('$\\langle H_P \\rangle$', rotation=0, fontsize=axis_size) plt.gca().set_xlabel('$\\gamma\,/\,\pi$', fontsize=axis_size) plt.gca().set_ylabel('$\\beta\,/\,\pi$', fontsize=axis_size) plt.xticks([0, 0.5, 1, 1.5, 2], size=size) plt.yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5], size=size) #plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.1f')) #plt.gca().set_xlim([0.8,6.2]) #plt.gca().set_ylim([1, 1.10]) extent = im.get_extent() ax.set_aspect(abs((extent[1] - extent[0]) / (extent[3] - extent[2])) / 1) #plt.title('$\\beta \\ vs \\ \\gamma$\nn=' + str(len(G.nodes)) + ', k=' + str(k) + \ #', p=' + str(1) + ', grid_size=' + str(num_steps) + 'x' + str(num_steps) + ', gi=' + str(gi)) plt.tight_layout() plt.show()
def get_opt(gi, p): G = nx.read_gpickle('../benchmarks/atlas/' + str(gi) + '.gpickle') C = common.create_C(G) M = common.create_complete_M(len(G.nodes)) k = int(len(G.nodes) / 2) num_steps = 0 num_samples = 50 lower_g, upper_g = 1.1, 1.55 lower_b, upper_b = 1.5, 1.8 #lower_g, upper_g = 0, pi/2 #lower_b, upper_b = 0, pi init = [[lower_g, upper_g] if i < p else [lower_b, upper_b] for i in range(2 * p)] sample_g, sample_b = LHS(p, num_samples, lower_g, upper_g, lower_b, upper_b) eps = 0.001 top_exps, top_angles = -1, [] for i in range(num_samples): print('i: ' + str(i)) print('top_exps: ' + str(top_exps)) print('top_angles: ' + str(top_angles)) kwargs = { 'method': 'L-BFGS-B', 'args': (G, C, M, k, p), 'bounds': init } optimal = basinhopping(dicke_ps_complete.opt, [sample_g[i], sample_b[i]], minimizer_kwargs=kwargs, niter=num_steps, disp=False) #optimal = minimize(dicke_ps_complete.opt, np.array([sample_g[i], sample_b[i]]), method='Nelder-Mead', tol=0.01, args=(G, C, M, k, p)) opt_exp = -optimal.fun opt_angles = list(optimal.x) if not top_angles: top_exps = opt_exp top_angles.append(opt_angles) elif abs(opt_exp - top_exps) < eps: # same value, check if angles are eps similar flag = False for j in range(len(top_angles)): t = 0 for l in range(len(opt_angles)): t += abs(top_angles[j][l] - opt_angles[l]) if t < eps: flag = True break if not flag: top_angles.append(opt_angles) elif opt_exp > (top_exps + eps): # new maximum top_exps, top_angles = opt_exp, [] top_angles.append(opt_angles) print('----------------------') print('top_exps: ' + str(top_exps)) print('top_angles: ' + str(top_angles)) return top_exps, top_angles
def temp_map(): global G total = [] #G = nx.gnp_random_graph(7, 0.6) for ii in range(1, 100): total = [] #gi = random.randint(163, 955) #print(gi) #G = nx.read_gpickle('../graphs/atlas/' + str(gi) + '.gpickle') num_nodes = random.randint(5, 10) G = nx.fast_gnp_random_graph(num_nodes, 0.5) while not nx.is_connected(G): G = nx.fast_gnp_random_graph(num_nodes, 0.5) k = int(len(G.nodes) / 2) C = common.create_C(G, k) M = common.create_complete_M(len(G.nodes), k) #M = common.create_ring_M(len(G.nodes), k) #p = Process(target=draw) #p.start() num_steps = 50 gamma, beta = 0, 0 g_list, grid = [], [] grid_min = -1 grid_max = 0 fig, ax = plt.subplots() print('0/' + str(num_steps) + '\t' + str(datetime.datetime.now().time())) for i in range(0, num_steps): for j in range(0, num_steps): val = qaoa(gamma, beta, G, C, M, k) g_list.append(val) if grid_max < val: grid_max = val if grid_min == -1: grid_min = val if grid_min > val: grid_min = val gamma += 2 * pi / (num_steps - 1) beta += pi / (2 * (num_steps - 1)) gamma = 0 grid.append(g_list) g_list = [] print( str(i + 1) + '/' + str(num_steps) + '\t' + str(datetime.datetime.now().time())) grid = list(reversed(grid)) print('-------------- max grid <C>: ' + str(grid_max)) for i in range(len(grid)): for j in range(len(grid[0])): grid[i][j] = (1 / (grid_max - grid_min)) * (grid[i][j] - grid_min) if not total: total = grid else: for i in range(len(total)): for j in range(len(total[0])): total[i][j] += grid[i][j] temp = total.copy() ''' temp = total.copy() temp_max = -1 temp_min = -1 for i in range(len(total)): for j in range(len(total[0])): if temp_max == -1: temp_max = temp[i][j] if temp[i][j] > temp_max: temp_max = temp[i][j] if temp_min == -1: temp_min = temp[i][j] if temp[i][j] < temp_min: temp_min = temp[i][j] #temp[i][j] = (1/ii)*temp[i][j] for i in range(len(total)): for j in range(len(total[0])): temp[i][j] = (1/(temp_max-temp_min))*(temp[i][j] - temp_min) ''' ''' SIZE = 13 plt.rc('font', size=SIZE) # controls default text sizes plt.rc('axes', titlesize=SIZE) # fontsize of the axes title plt.rc('axes', labelsize=SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=SIZE) # legend fontsize plt.rc('figure', titlesize=SIZE) # fontsize of the figure title ''' size = 15 axis_size = 17 im = ax.imshow(temp, aspect='auto', extent=(0, 2, 0, 0.5), interpolation='gaussian', cmap=cm.inferno_r) #cbar = ax.figure.colorbar(im, ax=ax, ticks=[]) #cbar.ax.tick_params(labelsize=size) #cbar.ax.set_ylabel('$\\langle H_P \\rangle$', rotation=0, va="bottom") #cbar.ax.get_yaxis().labelpad = 28 #cbar.ax.set_ylabel('$\\langle H_P \\rangle$', rotation=0, fontsize=axis_size) plt.gca().set_xlabel('$\\gamma\,/\,\pi$', fontsize=axis_size) plt.gca().set_ylabel('$\\beta\,/\,\pi$', fontsize=axis_size) plt.xticks([0, 0.5, 1, 1.5, 2], size=size) plt.yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5], size=size) #plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.1f')) #plt.gca().set_xlim([0.8,6.2]) #plt.gca().set_ylim([1, 1.10]) extent = im.get_extent() ax.set_aspect( abs((extent[1] - extent[0]) / (extent[3] - extent[2])) / 1) #plt.title('$\\beta \\ vs \\ \\gamma$\nn=' + str(len(G.nodes)) + ', k=' + str(k) + \ #', p=' + str(1) + ', grid_size=' + str(num_steps) + 'x' + str(num_steps) + ', gi=' + str(gi)) plt.tight_layout() #plt.show() plt.savefig('random/' + str(num_nodes) + '-' + str(random.randint(1, 10000)) + '.svg')
def temp_map(): total = [] for ii in range(1, 100): #gi = random.randint(143, 955) #print('gi = ' + str(gi)) #G, C, M, k = common.get_stuff(gi) G = nx.gnp_random_graph(7, random.uniform(0, 1)) while not nx.is_connected(G): G = nx.gnp_random_graph(7, random.uniform(0, 1)) k = int(len(G.nodes) / 2) C = common.create_C(G) M = common.create_ring_M(len(G.nodes)) num_steps = 50 gamma, beta = 0, 0 g_list, grid = [], [] grid_min = -1 grid_max = 0 fig, ax = plt.subplots() print('0/' + str(num_steps) + '\t' + str(datetime.datetime.now().time())) for i in range(0, num_steps): for j in range(0, num_steps): val = qaoa(gamma, beta, G, C, M, k, 1, 1) g_list.append(val) if grid_max < val: grid_max = val if grid_min == -1: grid_min = val if grid_min > val: grid_min = val gamma += pi / (2 * (num_steps - 1)) beta += pi / (2 * (num_steps - 1)) gamma = 0 grid.append(g_list) g_list = [] print( str(i + 1) + '/' + str(num_steps) + '\t' + str(datetime.datetime.now().time())) grid = list(reversed(grid)) print('-------------- max grid <C>: ' + str(grid_max)) for i in range(len(grid)): for j in range(len(grid[0])): grid[i][j] = (1 / (grid_max - grid_min)) * (grid[i][j] - grid_min) if not total: total = grid else: for i in range(len(total)): for j in range(len(total[0])): total[i][j] += grid[i][j] temp = total ''' temp_max = -1 temp_min = -1 for i in range(len(total)): for j in range(len(total[0])): if temp_max == -1: temp_max = temp[i][j] if temp[i][j] > temp_max: temp_max = temp[i][j] if temp_min == -1: temp_min = temp[i][j] if temp[i][j] < temp_min: temp_min = temp[i][j] #temp[i][j] = (1/ii)*temp[i][j] for i in range(len(total)): for j in range(len(total[0])): temp[i][j] = (1/(temp_max-temp_min))*(temp[i][j] - temp_min) ''' SIZE = 11 plt.rc('font', size=SIZE) # controls default text sizes plt.rc('axes', titlesize=SIZE) # fontsize of the axes title plt.rc('axes', labelsize=SIZE) # fontsize of the x and y labels plt.rc('xtick', labelsize=SIZE) # fontsize of the tick labels plt.rc('ytick', labelsize=SIZE) # fontsize of the tick labels plt.rc('legend', fontsize=SIZE) # legend fontsize plt.rc('figure', titlesize=SIZE) # fontsize of the figure title im = ax.imshow(temp, aspect='auto', extent=(0, 0.5, 0, 0.5), interpolation='gaussian', cmap=cm.inferno_r) cbar = ax.figure.colorbar(im, ax=ax, ticks=[]) #cbar.ax.set_ylabel('$\\langle H_P \\rangle$', rotation=0, va="bottom") cbar.ax.get_yaxis().labelpad = 25 cbar.ax.set_ylabel('average\n$\\langle H_P \\rangle$', rotation=0) plt.xlabel('$\\gamma\,/\,\pi$') plt.ylabel('$\\beta\,/\,\pi$') #plt.title('$\\beta \\ vs \\ \\gamma$\nn=' + str(len(G.nodes)) + ', k=' + str(k) + \ #', p=' + str(1) + ', grid_size=' + str(num_steps) + 'x' + str(num_steps) + ', gi=' + str(gi)) #plt.show() plt.savefig('overlay-ring-random/' + str(ii) + '.svg')