def get_angles(self): """ Finds optimal angles with the quantum variational eigensolver method. It's direct copy of the function `get_angles` from Grove. I decided to copy it here to access to the optimization trajectory (`angles_history`). Returns: best_betas, best_gammas (np.arrays): best values of the betas and gammas found. """ stacked_params = np.hstack( (self.qaoa_inst.betas, self.qaoa_inst.gammas)) vqe = VQE(self.qaoa_inst.minimizer, minimizer_args=self.qaoa_inst.minimizer_args, minimizer_kwargs=self.qaoa_inst.minimizer_kwargs) cost_ham = reduce(lambda x, y: x + y, self.qaoa_inst.cost_ham) # maximizing the cost function! param_prog = self.qaoa_inst.get_parameterized_program() result = vqe.vqe_run(param_prog, cost_ham, stacked_params, qc=self.qaoa_inst.qc, **self.qaoa_inst.vqe_options) best_betas = result.x[:self.qaoa_inst.steps] best_gammas = result.x[self.qaoa_inst.steps:] optimization_trajectory = result.iteration_params energy_history = result.expectation_vals if self.ax is not None and self.visualize and self.qaoa_inst.steps == 1: plot_optimization_trajectory(self.ax, optimization_trajectory) return best_betas, best_gammas
def get_angles(self): """ Finds optimal angles with the quantum variational eigensolver method. Stored VQE result :returns: ([list], [list]) A tuple of the beta angles and the gamma angles for the optimal solution. """ stacked_params = np.hstack((self.betas, self.gammas)) vqe = VQE(self.minimizer, minimizer_args=self.minimizer_args, minimizer_kwargs=self.minimizer_kwargs) cost_ham = reduce(lambda x, y: x + y, self.cost_ham) # maximizing the cost function! param_prog = self.get_parameterized_program() result = vqe.vqe_run(param_prog, cost_ham, stacked_params, qvm=self.qvm, **self.vqe_options) self.result = result betas = result.x[:self.steps] gammas = result.x[self.steps:] return betas, gammas
def one_step_grid_search(self, current_step): """ Grid search on n-th pair of QAOA angles, where n=current_step. Args: current_step (int): specify on which layer do we perform search. Returns: best_beta, best_gamma (floats): best values of the beta and gamma found. """ self.qaoa_inst.steps = current_step best_beta = None best_gamma = None best_energy = np.inf fixed_betas = self.qaoa_inst.betas fixed_gammas = self.qaoa_inst.gammas beta_range = np.linspace(0, np.pi, self.grid_size) gamma_range = np.linspace(0, 2 * np.pi, self.grid_size) vqe = VQE(self.qaoa_inst.minimizer, minimizer_args=self.qaoa_inst.minimizer_args, minimizer_kwargs=self.qaoa_inst.minimizer_kwargs) cost_hamiltonian = reduce(lambda x, y: x + y, self.qaoa_inst.cost_ham) for beta in beta_range: for gamma in gamma_range: betas = np.append(fixed_betas, beta) gammas = np.append(fixed_gammas, gamma) stacked_params = np.hstack((betas, gammas)) program = self.qaoa_inst.get_parameterized_program() energy = vqe.expectation(program(stacked_params), cost_hamiltonian, self.samples, self.qaoa_inst.qc) print(beta, gamma, end="\r") if energy < best_energy: best_energy = energy best_beta = beta best_gamma = gamma return best_beta, best_gamma
Pairing.set_integrals(h_pq, h_pqrs) Pairing.get_circuit() circuit_list = Pairing.to_circuit_list(ptype='vqe') #print('new') for i in circuit_list: print(i) #p2 = hamil(l) #cir = p2.get_circuits(h_pq,h_pqrs) #print('old') #for i in cir: print(i) model = VQE(n_qubits=l, ansatz=UCCD, circuit_list=circuit_list, shots=500, ancilla=0, prnt=True, max_energy=False) #model.optimize_classical(new_theta,method='Cobyla') #model.optimize_gradient(new_theta) #options = {'feedback':1,'grad_avg':5} #optimization = SPSA(model.expval, # new_theta, # min_change=0.1, # noise_var = 0.01, # options=options) #optimization() #method = 'SPSA' #np.save('data/'+method+'.npy', model.energies)
i = 0 for R in tqdm(Rs): h, v, Enuc, E = get_H2(R) #fci_coeffs[i] = FCI(h,v) FCIs[i] = E['fci'] HFs[i] = E['hf'] h2 = SecondQuantizedHamiltonian(n, l, h, v, nuclear_repulsion=Enuc, add_spin=True) h2.group_paulis(qwc=True, gc=True) model = VQE(h2, Minimizer('Cobyla', tol=1 / (10 * shots), disp=False), 'RYRZ', options=options) theta = model.optimize() Es[i], VARs[i] = model.get_mean(theta, N=10000, M=10) #vqe_coeffs[i] = model.get_state_coeffs(theta) i += 1 np.save('RYRZ/bonds.npy', Rs) np.save('RYRZ/fci.npy', FCIs) np.save('RYRZ/hf.npy', HFs) np.save('RYRZ/E.npy', Es) np.save('RYRZ/var.npy', VARs)
'noise_model': True, 'basis_gates': True, 'coupling_map': True, 'print': False } #model = VQE(pairing,Minimizer('Powell'),'RYRZ',ansatz_depth=10,options=options) # Get grid grid_points = 50 x = np.linspace(0, 2 * np.pi, grid_points) y = np.linspace(0, 2 * np.pi, grid_points) params = [] for i, xi in enumerate(x): for j, yi in enumerate(y): params.append([xi, yi]) Es = np.zeros(grid_points * grid_points) vqe = VQE(pairing, Minimizer('Powell'), 'RYRZ', options=options) og_params = vqe.theta assert len(params) == grid_points * grid_points i = 0 for theta in tqdm(params): #print('{} / {}'.format(i+1,grid_points*grid_points)) Es[i] = vqe.expval(theta) i += 1 np.save('data/brute/ryrz/grid.npy', x) np.save('data/brute/ryrz/parameters.npy', np.asarray(params)) np.save('data/brute/ryrz/values1000.npy', Es)
nuclear_repulsion=Enuc, add_spin=True) t2 = time.time() print('Time:', t2 - t1) h2.group_paulis(qwc=True, gc=True) #options = {'count_states':False,'shots':1000,'print':True} #options = {'shots':10000,'print':True} options = { 'shots': 10000, #'seed':3, #'optimization_level':1, #'device':'ibmq_essex', #'meas_fit':True, #'layout':[0,1,2,3], #'noise_model':True, #'basis_gates':True, #'coupling_map':True, 'print': True } model = VQE(h2, Minimizer('Cobyla'), 'RYPAIRING', ansatz_depth=1, options=options) theta = model.optimize() print(model.get_state_coeff(theta)) print(model.get_mean(theta))
pairing.group_paulis(qwc=True,gc=True) #theta = [5.829889373194686] # Hardcode good parameter #theta = [-0.4] #options = {'count_states':False,'shots':1000,'print':True} #options = {'shots':10000,'print':True} options = {'shots':1000, #'seed':1, 'optimization_level':3, 'backend':qcomp, 'ibmq':True, #'device':'ibmq_london', #'meas_fit':True, #'layout':[0,3,2,1], #'layout':[1,0,2,3], #'noise_model':True, 'basis_gates':True, #'coupling_map':True, 'print':True} model = VQE(pairing,Minimizer('Cobyla',tol=1e-05),'UCCD',options=options) #print(len(model.circuit_list)) #theta = model.optimize(theta) #print(theta) #print(model.get_mean(theta)) print(model.expval(theta))
l, h_pq, h_pqrs, nuclear_repulsion=Enuc, add_spin=True) grid_points = 60 x = np.linspace(-0.1, 0.05, grid_points) #params = [[i] for i in x] params = [] for i in x: for j in x: params.append(np.array([i, j])) Es = np.zeros(grid_points * grid_points) shots = 1000 options = {'shots': shots} i = 0 for theta in tqdm(params): vqe = VQE(H2, QuantumGradientDescent('RMSprop'), ansatz='RY', options=options) #print('{} / {}'.format(i+1,grid_points)) Es[i] = vqe.expval(theta) i += 1 np.save('data/brute/grid.npy', x) np.save('data/brute/parameters.npy', np.asarray(params)) np.save('data/brute/values{}.npy'.format(shots), Es)
'print': True } options_q = { 'shots': 2000, #'seed':1, 'optimization_level': 1, 'backend': qcomp, 'ibmq': True, #'device':'ibmq_london', #'meas_fit':True, #'layout':[0,3,2,1], 'layout': [0, 1, 2, 3], #'layout':[1,0,2,3], #'noise_model':True, 'basis_gates': True, #'coupling_map':True, 'print': True } #model = VQE(h2,Minimizer('Cobyla',tol=1e-05),'RYPAIRING',options=options_i) modelq = VQE(h2, Minimizer('Cobyla', tol=1e-06, max_iter=70), 'RYPAIRING', options=options_q) theta = modelq.optimize() save_str = '0' if R < 1 else '' save_str += str(int(R * 100)) np.save('E_{}.npy'.format(save_str), np.load('.ibmq_energies.npy')) np.save('t_{}.npy'.format(save_str), np.load('.ibmq_theta.npy'))
options = { 'shots': 1000, 'optimization_level': 1, 'device': 'ibmq_london', 'layout': [1, 0, 2, 3], 'noise_model': True, 'basis_gates': True, 'coupling_map': True, #'seed':1, 'print': False } methods = ['', 'adam', 'adagrad', 'rmsprop'] maxit = 60 avg_nums = [0, 2, 5, 10] theta = np.array([-9.31816914]) # Bad theta value for method in methods: data = np.zeros((len(avg_nums), maxit)) for j, avg_num in enumerate(avg_nums): vqe = VQE(pairing, QuantumGradientDescent(method, max_iter=maxit, avg_num=avg_num), 'RY', options=options) vqe.optimize(theta.copy()) data[j] = vqe.optimizer.energies if method == '': method = 'GD' np.save('data/optimization/avg_grad/{}.npy'.format(method), data)
'noise_model': True, 'basis_gates': True, 'coupling_map': True, #'seed':1, 'meas_fit': False, 'print': False } option3 = { 'shots': shots, 'optimization_level': 1, 'device': 'ibmq_{}'.format(device), 'layout': [1, 0, 2, 3], 'noise_model': True, 'basis_gates': True, 'coupling_map': True, #'seed':1, 'print': False } optionz = [option1, option2, option3] for o, options in enumerate(optionz): model = VQE(pairing, Minimizer('Cobyla', tol=1e-04, disp=False), ansatz, options=options) theta = model.optimize() data[i, o], _ = model.get_mean(theta) fci[i] = FCI(n, l, h_pq, h_pqrs) i += 1 np.save('{}_{}_{}shots.npy'.format(device, ansatz, shots), data) np.save('fci.npy', fci)
print('FCI energy :', Efci) pairing = PairingHamiltonian(n, l, h_pq, h_pqrs) #for i,circ in enumerate(pairing.circuit_list('vqe')): print(i,'\n',circ) #options = {'count_states':False,'shots':1000,'print':False} options = { 'shots': 1000, 'optimization_level': 1, 'device': 'ibmq_london', 'layout': [1, 0, 2, 3], 'noise_model': True, 'basis_gates': True, 'coupling_map': True, 'print': False } #methods = ['','adam','adagrad','rmsprop'] methods = ['Powell', 'Nelder-Mead'] maxit = 100 #data = np.zeros((len(methods),maxit)) #theta = 2*np.pi*np.random.randn(1) theta = np.array([-9.31816914]) for i, method in enumerate(methods): vqe = VQE(pairing, Minimizer(method, max_evals=200), 'RY', options=options) #vqe = VQE(pairing,QuantumGradientDescent(method,max_iter=maxit),'RY',options=options) vqe.optimize(theta.copy()) #data[i] = vqe.optimizer.energies np.save('data/optimization/{}_n.npy'.format(method), np.array(vqe.energies)) #np.save('data/optimization/QGD.npy',data)
def simple_grid_search_angles(self, save_data=False): """ Finds optimal angles for QAOA by performing grid search on all the angles. This is not recommended for higher values of steps parameter, since it results in grid_size**(2*steps) evaluations. Returns: best_betas, best_gammas (np.arrays): best values of the betas and gammas found. """ best_betas = None best_gammas = None best_energy = np.inf # For some reasons np.meshgrid returns columns in order, where values in second # grow slower than in the first one. This a fix to it. if self.qaoa_inst.steps == 1: column_order = [0] else: column_order = [1, 0] + list(range(2, self.qaoa_inst.steps)) new_indices = np.argsort(column_order) beta_ranges = [np.linspace(0, np.pi, self.grid_size) ] * self.qaoa_inst.steps all_betas = np.vstack(np.meshgrid(*beta_ranges)).reshape( self.qaoa_inst.steps, -1).T all_betas = all_betas[:, column_order] gamma_ranges = [np.linspace(0, 2 * np.pi, self.grid_size) ] * self.qaoa_inst.steps all_gammas = np.vstack(np.meshgrid(*gamma_ranges)).reshape( self.qaoa_inst.steps, -1).T all_gammas = all_gammas[:, column_order] vqe = VQE(self.qaoa_inst.minimizer, minimizer_args=self.qaoa_inst.minimizer_args, minimizer_kwargs=self.qaoa_inst.minimizer_kwargs) cost_hamiltonian = reduce(lambda x, y: x + y, self.qaoa_inst.cost_ham) all_energies = [] data_to_save = [] if save_data: file_name = "_".join( [str(self.m), "grid", str(self.grid_size), str(time.time())]) + ".csv" for betas in all_betas: for gammas in all_gammas: stacked_params = np.hstack((betas, gammas)) program = self.qaoa_inst.get_parameterized_program() energy = vqe.expectation(program(stacked_params), cost_hamiltonian, self.samples, self.qaoa_inst.qc) all_energies.append(energy) if self.verbose: print(betas, gammas, energy, end="\r") if save_data: data_to_save.append(np.hstack([betas, gammas, energy])) if energy < best_energy: best_energy = energy best_betas = betas best_gammas = gammas if self.verbose: print("Lowest energy:", best_energy) print("Angles:", best_betas, best_gammas) if save_data: np.savetxt(file_name, np.array(data_to_save), delimiter=",") if self.visualize: if self.qaoa_inst.steps == 1: self.ax = plot_energy_landscape(all_betas, all_gammas, np.array(all_energies), log_legend=True) else: plot_variance_landscape(all_betas, all_gammas, np.array(all_energies)) return best_betas, best_gammas
h, v, Enuc, E = get_H2_info(0.7) fci = E['fci'] hf = E['hf'] print('HF energy:', hf) print('FCI energy:', fci) mol = SecondQuantizedHamiltonian(2, 4, h, v, nuclear_repulsion=Enuc, add_spin=True) options = { 'shots': 1000, 'optimization_level': 1, #'device':'ibmq_london', #'layout':[1,0,2,3], #'noise_model':True, #'basis_gates':True, #'coupling_map':True, #'seed':1, 'print': True } #options = {'shots':10000,'print':True} alg = VQE(mol, Minimizer('Cobyla'), 'RY', options=options) alg.optimize() #alg.expval([0,0,0,0,0])
for p in range(0, l - 1, 2): for r in range(0, l - 1, 2): h_pqrs[p, p + 1, r, r + 1] = -0.5 * g Efci = FCI(n, l, h_pq, h_pqrs) print('FCI energy :', Efci) pairing = PairingHamiltonian(n, l, h_pq, h_pqrs) options = {'shots': 1000, 'print': True} #options = {'shots':1000, # 'optimization_level':1, # 'device':'ibmq_london', # 'layout':[0,3,2,1], # #'noise_model':True, # 'basis_gates':True, # 'coupling_map':True, # 'print':True} model = VQE(pairing, Minimizer('Cobyla', tol=1e-04), 'RYPAIRING', options=options) param = model.optimize() param = [param] print(param) num = 10 Es = np.zeros(num) for i in range(num): Es[i] = model.expval(param) print('E =', np.mean(Es), '+-', np.std(Es))
qk_cb = qk.ClassicalRegister(l) qk_qc = qk.QuantumCircuit(qk_qb,qk_cb) my_qc = my_ucc(theta,my_qc,my_qb) qk_qc = qk_ucc.construct_circuit(theta,qk_qb) def qk_ucc_func(theta,qc,qb): return qk_ucc.construct_circuit(theta,q=qk_qb) my_vqe = VQE(n_qubits = l, n_fermi = n, ansatz = my_ucc, circuit_list = circuit_list, shots = 1000, seed=1, count_states=True) qk_vqe = VQE(n_qubits = l, n_fermi = n, ansatz = qk_ucc_func, circuit_list = circuit_list, shots = 1000, seed=1, count_states=True) my_E = my_vqe.expval(theta) qk_E = qk_vqe.expval(theta)
Pairing.set_integrals(h_pq, h_pqrs) Pairing.get_circuit() circuit_list = Pairing.to_circuit_list(ptype='vqe') all_shots = np.linspace(1000, 100000, 100) Es = np.zeros(100) legal = np.zeros(100) illegal = np.zeros(100) i = 0 for shot in tqdm(all_shots): model = VQE( n_qubits=l, ansatz=UCCD, circuit_list=circuit_list, shots=500, #int(shot), ancilla=0, seed=None, prnt=False, max_energy=False, count_states=True) Es[i] = model.expval(theta) legal[i] = model.legal illegal[i] = model.illegal i += 1 np.save('data/shots/shots.npy', all_shots) np.save('data/shots/values.npy', Es) np.save('data/shots/legal.npy', legal) np.save('data/shots/illegal.npy', illegal)
options_q = { 'shots': 1000, #'seed':1, 'optimization_level': 1, 'backend': qcomp, 'ibmq': True, #'device':'ibmq_london', #'meas_fit':True, #'layout':[0,3,2,1], 'layout': [0, 1, 2, 3], #'layout':[1,0,2,3], #'noise_model':True, 'basis_gates': True, #'coupling_map':True, 'print': True } #model = VQE(pairing,Minimizer('Cobyla',tol=1e-05),'UCCD',options=options_i) #modelq = VQE(pairing,Minimizer('Cobyla',tol=1e-05),'UCCD',options=options_q) #model = VQE(pairing,Minimizer('Cobyla',tol=1e-05),'RYPAIRING',options=options_i) modelq = VQE(pairing, Minimizer('Cobyla', tol=1e-05, max_iter=70), 'RYPAIRING', options=options_q) theta = modelq.optimize() print(theta) #print(model.get_mean(theta)) #print('simulation') #print(model.expval(theta)) #print('Real quantum') #print(modelq.expval(theta))
'layout': layout, 'noise_model': True, 'basis_gates': True, 'coupling_map': True, #'seed':1, 'meas_fitter': False, 'print': False } option3 = { 'shots': 1000, 'optimization_level': 1, 'device': 'ibmq_london', 'layout': layout, 'noise_model': True, 'basis_gates': True, 'coupling_map': True, #'seed':1, 'print': False } options = [option1, option2, option3] data = np.zeros((3, points)) for j in range(3): i = 0 for theta in tqdm(thetas): vqe = VQE(pairing, SPSA(), 'UCCD', options=options[j]) data[j, i] = vqe.expval(theta) i += 1 np.save('UCCD/LONDON_GC_normal.npy', data[0]) np.save('UCCD/LONDON_GC_noisy_n.npy', data[1]) np.save('UCCD/LONDON_GC_noisy_w.npy', data[2])
h_pqrs = np.zeros((l,l,l,l)) for p in range(0,l-1,2): for r in range(0,l-1,2): h_pqrs[p,p+1,r,r+1] = -0.5*g Efci = FCI(n,l,h_pq,h_pqrs) print('FCI energy :',Efci) pairing = PairingHamiltonian(n,l,h_pq,h_pqrs) options = {'shots':1000,'print':True} #options = {'shots':1000, # 'optimization_level':1, # 'device':'ibmq_london', # 'layout':[0,3,2,1], # #'noise_model':True, # 'basis_gates':True, # 'coupling_map':True, # 'print':True} model = VQE(pairing,Minimizer('Nelder-Mead',tol=1e-04),'RYPAIRING',options=options) param = model.optimize() param = [param] num = 10 Es = np.zeros(num) for i in range(num): Es[i] = model.expval(param) print('E =',np.mean(Es),'+-',np.std(Es))
#'noise_model':True, #'basis_gates':True, #'coupling_map':True, #'seed':1, 'print': False } method = 'rmsprop' maxit = 100 tols = [1e-04, 1e-05] avgs = [2, 5, 10, 20] theta = np.array([-9.31816914]) # Bad theta value for j, tol in enumerate(tols): print('For tolerance', tol) vqe = VQE(pairing, QuantumGradientDescent(method, max_iter=maxit, tol=tol), 'RY', options=options) vqe.optimize(theta.copy()) Es = vqe.optimizer.energies mean = [np.mean(Es[-i:]) for i in avgs] var = [np.var(Es[-i:]) for i in avgs] print('Num Mean Var') for i, a in enumerate(avgs): print('{:<8}{:<12.8f}{:.8f}'.format(a, mean[i], var[i])) #plt.figure(j) plt.plot(vqe.optimizer.thetas, label='tol {}'.format(tol)) plt.legend() plt.show()
for g in tqdm(gs): h_pq, h_pqrs, Efci, Ehf = get_pairing_matrix(n, l, delta, g, w_E=True) fci[i] = Efci hf[i] = Ehf #print('FCI:',fci[i]) #print('HF:',Ehf) pairing = PairingHamiltonian(n, l, h_pq, h_pqrs) #pairing = SecondQuantizedHamiltonian(n,l,h_pq,h_pqrs) pairing.group_paulis() #print('Num measures:',len(pairing.circuit_list('vqe'))) options = { 'shots': shots, #'optimization_level':1, #'seed':1, 'print': False } model = VQE(pairing, Minimizer('Cobyla', tol=1e-06, disp=False), ansatz, ansatz_depth=depth, options=options) theta = model.optimize() data[i], _ = model.get_mean(theta) print(data[i]) coeff[i] = model.get_state_coeff(theta) i += 1 np.save('E_{}_{}shots_5g_10g.npy'.format(ansatz, shots), data) np.save('coeff_{}_{}shots_5g_10g.npy'.format(ansatz, shots), coeff) #np.save('fci.npy',fci) #np.save('hf.npy',hf)
'layout':[1,0,2,3], 'noise_model':True, 'basis_gates':True, 'coupling_map':True, #'seed':1, 'meas_fitter':False, 'print':False} option3 = {'shots':1000, 'optimization_level':1, 'device':'ibmq_essex', 'layout':[1,0,2,3], 'noise_model':True, 'basis_gates':True, 'coupling_map':True, #'seed':1, 'print':False} options = [option1,option2,option3] data = np.zeros((3,points)) for j in range(1,3): i = 0 for theta in tqdm(thetas): vqe = VQE(pairing, SPSA(), 'RYPAIRING', options=options[j]) data[j,i] = vqe.expval(theta) i += 1 #np.save('RY/ESSEX_GC_normal.npy',data[0]) np.save('RY/ESSEX_GC_noisy_n.npy',data[1]) np.save('RY/ESSEX_GC_noisy_w.npy',data[2])
VARs_noisy = np.zeros_like(omegas) vqe_coeffs_noisy = np.zeros((len(omegas), 6)) i = 0 for omega in tqdm(omegas): h, v, E = get_qdot_matrix(n, l, omega) ev, vv = FCI(n, l, h, v, ret_all=True) FCIs[i] = ev[0] HFs[i] = E[0].real fci_coeffs[i] = vv[:, 0].real h2 = SecondQuantizedHamiltonian(n, l, h, v, anti_symmetric=True) h2.group_paulis(qwc=True, gc=True) # Ideal model = VQE(h2, Minimizer('Cobyla', tol=1 / (100 * shots), disp=False), 'UCCSD', options=option_ideal) theta = model.optimize() Es_ideal[i], VARs_ideal[i] = model.get_mean(theta, N=10000, M=10) vqe_coeffs_ideal[i] = model.get_state_coeff(theta) # Noisy model = VQE(h2, Minimizer('Cobyla', tol=1 / (100 * shots), disp=False), 'UCCSD', options=option_noisy) theta = model.optimize() Es_noisy[i], VARs_noisy[i] = model.get_mean(theta, N=10000, M=10) vqe_coeffs_noisy[i] = model.get_state_coeff(theta) i += 1 np.save('UCC/bonds.npy', omegas)
import time t1 = time.time() pairing = PairingHamiltonian(n, l, h_pq, h_pqrs) t2 = time.time() print('Time:', t2 - t1) pairing.group_paulis(qwc=False, gc=True) theta = [5.829889373194686] # Hardcode good parameter #options = {'count_states':False,'shots':1000,'print':True} #options = {'shots':10000,'print':True} options = { 'shots': 1000, 'seed': 1, #'optimization_level':1, #'device':'ibmq_london', #'meas_fit':True, #'layout':[0,3,2,1], #'noise_model':True, #'basis_gates':True, #'coupling_map':True, 'print': True } model = VQE(pairing, Minimizer('Powell'), 'RYPAIRING', options=options) #param = model.optimize() #print(model.theta) print(model.expval(theta))
for p in range(0, l - 1, 2): for r in range(0, l - 1, 2): h_pqrs[p, p + 1, r, r + 1] = -0.5 * g UCCD = UnitaryCoupledCluster(n, l, 'D', 1) theta = UCCD.new_parameters() Pairing = SecondQuantizedHamiltonian(n, l, h_pq, h_pqrs) options = {'shots': 10000} methods = ['Powell', 'Cobyla', 'Nelder-Mead'] for method in methods: new_theta = theta print('VQE with optimization method:', method) model = VQE(Pairing, ansatz='UCCD', options=options) model.optimize_classical(method=method) np.save('data/' + method + '10k.npy', model.energies) theta = Pairing.theta model = VQE(Pairing, ansatz='UCCD', options=options) opt_options = {'feedback': 1, 'grad_avg': 5} optimization = SPSA(model.expval, theta, min_change=0.1, noise_var=0.01, options=opt_options) optimization.run() method = 'SPSA' np.save('data/' + method + '10k.npy', model.energies)
h_pqrs = np.zeros((l, l, l, l)) for p in range(0, l - 1, 2): for r in range(0, l - 1, 2): h_pqrs[p, p + 1, r, r + 1] = -0.5 * g # Prepare circuit list pairing = SecondQuantizedHamiltonian(n, l, h_pq, h_pqrs) grid_points = 500 x = np.linspace(0, 2 * np.pi, grid_points) params = [[i] for i in x] Es = np.zeros(grid_points) legal = np.zeros(grid_points) illegal = np.zeros(grid_points) i = 0 for theta in tqdm(params): vqe = VQE(pairing, ansatz='UCCD') vqe.options['shots'] = 1000 vqe.options['count_states'] = True vqe.options['backend'] = 'statevector_simulator' Es[i] = vqe.expval() legal[i] = vqe.legal illegal[i] = vqe.illegal i += 1 np.save('data/brute/1D/x.npy', x) np.save('data/brute/1D/values1000.npy', Es) np.save('data/brute/1D/legal1000.npy', legal) np.save('data/brute/1D/illegal1000.npy', illegal)
vqe_coeffs_noisy = np.zeros((len(omegas), 6)) i = 0 for omega in tqdm(omegas): h, v, E = get_qdot_matrix(n, l, omega) ev, vv = FCI(n, l, h, v, ret_all=True) FCIs[i] = ev[0] HFs[i] = E[0].real fci_coeffs[i] = vv[:, 0].real h2 = SecondQuantizedHamiltonian(n, l, h, v, anti_symmetric=True) h2.group_paulis(qwc=True, gc=True) # Ideal model = VQE(h2, Minimizer('Cobyla', tol=1 / (100 * shots), disp=False), 'RYRZ', ansatz_depth=2, options=option_ideal) theta = model.optimize() Es_ideal[i], VARs_ideal[i] = model.get_mean(theta, N=10000, M=10) vqe_coeffs_ideal[i] = model.get_state_coeff(theta) # Noisy model = VQE(h2, Minimizer('Cobyla', tol=1 / (100 * shots), disp=False), 'RYRZ', ansatz_depth=2, options=option_noisy) theta = model.optimize() Es_noisy[i], VARs_noisy[i] = model.get_mean(theta, N=10000, M=10) vqe_coeffs_noisy[i] = model.get_state_coeff(theta) i += 1