def test_vqe_caching_direct(self, batch_mode=True): backend = BasicAer.get_backend('statevector_simulator') num_qubits = self.algo_input.qubit_op.num_qubits init_state = Zero(num_qubits) var_form = RY(num_qubits, 3, initial_state=init_state) optimizer = L_BFGS_B() algo = VQE(self.algo_input.qubit_op, var_form, optimizer, 'matrix', batch_mode=batch_mode) quantum_instance_caching = QuantumInstance(backend, circuit_caching=True, skip_qobj_deepcopy=True, skip_qobj_validation=True) result_caching = algo.run(quantum_instance_caching) self.assertLessEqual(quantum_instance_caching.circuit_cache.misses, 0) self.assertAlmostEqual( self.reference_vqe_result['statevector_simulator']['energy'], result_caching['energy']) speedup_check = 3 self.log.info( result_caching['eval_time'], self.reference_vqe_result['statevector_simulator']['eval_time'] / speedup_check)
def test_saving_and_loading(self): backend = BasicAer.get_backend('statevector_simulator') num_qubits = self.algo_input.qubit_op.num_qubits init_state = Zero(num_qubits) var_form = RY(num_qubits, 3, initial_state=init_state) optimizer = L_BFGS_B() algo = VQE(self.algo_input.qubit_op, var_form, optimizer, 'matrix') fd, cache_tmp_file = tempfile.mkstemp(suffix='.inp') os.close(fd) quantum_instance_caching = QuantumInstance(backend, circuit_caching=True, cache_file=cache_tmp_file, skip_qobj_deepcopy=True, skip_qobj_validation=True) algo.run(quantum_instance_caching) self.assertLessEqual(quantum_instance_caching.circuit_cache.misses, 0) is_file_exist = os.path.exists(cache_tmp_file) self.assertTrue(is_file_exist, "Does not store content successfully.") circuit_cache_new = CircuitCache(skip_qobj_deepcopy=True, cache_file=cache_tmp_file) self.assertEqual(quantum_instance_caching.circuit_cache.mappings, circuit_cache_new.mappings) self.assertLessEqual(circuit_cache_new.misses, 0) if is_file_exist: os.remove(cache_tmp_file)
def test_vqe_caching_direct(self, max_evals_grouped): self._build_refrence_result(backends=['statevector_simulator']) backend = BasicAer.get_backend('statevector_simulator') num_qubits = self.algo_input.qubit_op.num_qubits init_state = Zero(num_qubits) var_form = RY(num_qubits, 3, initial_state=init_state) optimizer = L_BFGS_B() algo = VQE(self.algo_input.qubit_op, var_form, optimizer, max_evals_grouped=max_evals_grouped) quantum_instance_caching = QuantumInstance( backend, circuit_caching=True, skip_qobj_deepcopy=True, skip_qobj_validation=True, optimization_level=self.optimization_level) result_caching = algo.run(quantum_instance_caching) self.assertLessEqual(quantum_instance_caching.circuit_cache.misses, 0) self.assertAlmostEqual( self.reference_vqe_result['statevector_simulator']['energy'], result_caching['energy']) speedup_min = 3 speedup = result_caching['eval_time'] / self.reference_vqe_result[ 'statevector_simulator']['eval_time'] self.assertLess(speedup, speedup_min)
def test_tapered_op(self): """ tapered op test """ tapered_ops = self.z2_symmetries.taper(self.qubit_op) smallest_idx = 0 # Prior knowledge of which tapered_op has ground state the_tapered_op = tapered_ops[smallest_idx] optimizer = SLSQP(maxiter=1000) init_state = HartreeFock(num_qubits=the_tapered_op.num_qubits, num_orbitals=self.core._molecule_info['num_orbitals'], qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_particles=self.core._molecule_info['num_particles'], sq_list=the_tapered_op.z2_symmetries.sq_list) var_form = UCCSD(num_qubits=the_tapered_op.num_qubits, depth=1, num_orbitals=self.core._molecule_info['num_orbitals'], num_particles=self.core._molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_time_slices=1, z2_symmetries=the_tapered_op.z2_symmetries) algo = VQE(the_tapered_op, var_form, optimizer) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend) algo_result = algo.run(quantum_instance) _, result = self.core.process_algorithm_result(algo_result) self.assertAlmostEqual(result['energy'], self.reference_energy, places=6)
def test_saving_and_loading_e2e(self): backend = BasicAer.get_backend('statevector_simulator') num_qubits = self.algo_input.qubit_op.num_qubits init_state = Zero(num_qubits) var_form = RY(num_qubits, 1, initial_state=init_state) optimizer = L_BFGS_B(maxiter=10) algo = VQE(self.algo_input.qubit_op, var_form, optimizer) with tempfile.NamedTemporaryFile(suffix='.inp', delete=True) as cache_tmp_file: cache_tmp_file_name = cache_tmp_file.name quantum_instance_caching = QuantumInstance( backend, circuit_caching=True, cache_file=cache_tmp_file_name, skip_qobj_deepcopy=True, skip_qobj_validation=True, optimization_level=self.optimization_level) algo.run(quantum_instance_caching) self.assertLessEqual(quantum_instance_caching.circuit_cache.misses, 0) is_file_exist = os.path.exists(cache_tmp_file_name) self.assertTrue(is_file_exist, "Does not store content successfully.") circuit_cache_new = CircuitCache(skip_qobj_deepcopy=True, cache_file=cache_tmp_file_name) self.assertEqual(quantum_instance_caching.circuit_cache.mappings, circuit_cache_new.mappings) self.assertLessEqual(circuit_cache_new.misses, 0)
def test_end2end_h2(self, name, optimizer, backend, shots): """ end to end h2 """ del name # unused if optimizer == 'COBYLA': optimizer = COBYLA() optimizer.set_options(maxiter=1000) elif optimizer == 'SPSA': optimizer = SPSA(max_trials=2000) ryrz = RYRZ(self.qubit_op.num_qubits, depth=3, entanglement='full') vqe = VQE(self.qubit_op, ryrz, optimizer, aux_operators=self.aux_ops) quantum_instance = QuantumInstance(backend, shots=shots) results = vqe.run(quantum_instance) self.assertAlmostEqual(results['energy'], self.reference_energy, places=4)
def test_end2end_h2(self, name, optimizer, backend, mode, shots): if optimizer == 'COBYLA': optimizer = COBYLA() optimizer.set_options(maxiter=1000) elif optimizer == 'SPSA': optimizer = SPSA(max_trials=2000) ryrz = RYRZ(self.algo_input.qubit_op.num_qubits, depth=3, entanglement='full') vqe = VQE(self.algo_input.qubit_op, ryrz, optimizer, mode, aux_operators=self.algo_input.aux_ops) run_config = RunConfig(shots=shots, max_credits=10, memory=False) quantum_instance = QuantumInstance(backend, run_config) results = vqe.run(quantum_instance) self.assertAlmostEqual(results['energy'], self.reference_energy, places=4)
def test_tapered_op(self): # set_qiskit_chemistry_logging(logging.DEBUG) tapered_ops = [] for coeff in itertools.product([1, -1], repeat=len(self.sq_list)): tapered_op = Operator.qubit_tapering(self.qubit_op, self.cliffords, self.sq_list, list(coeff)) tapered_ops.append((list(coeff), tapered_op)) smallest_idx = 0 # Prior knowledge of which tapered_op has ground state the_tapered_op = tapered_ops[smallest_idx][1] the_coeff = tapered_ops[smallest_idx][0] optimizer = SLSQP(maxiter=1000) init_state = HartreeFock( num_qubits=the_tapered_op.num_qubits, num_orbitals=self.core._molecule_info['num_orbitals'], qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_particles=self.core._molecule_info['num_particles'], sq_list=self.sq_list) var_form = UCCSD( num_qubits=the_tapered_op.num_qubits, depth=1, num_orbitals=self.core._molecule_info['num_orbitals'], num_particles=self.core._molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_time_slices=1, cliffords=self.cliffords, sq_list=self.sq_list, tapering_values=the_coeff, symmetries=self.symmetries) algo = VQE(the_tapered_op, var_form, optimizer, 'matrix') backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend) algo_result = algo.run(quantum_instance) lines, result = self.core.process_algorithm_result(algo_result) self.assertAlmostEqual(result['energy'], self.reference_energy, places=6)
def test_vqe_caching_direct(self, batch_mode): backend = get_aer_backend('statevector_simulator') num_qubits = self.algo_input.qubit_op.num_qubits init_state = Zero(num_qubits) var_form = RY(num_qubits, 3, initial_state=init_state) optimizer = L_BFGS_B() algo = VQE(self.algo_input.qubit_op, var_form, optimizer, 'matrix', batch_mode=batch_mode) circuit_cache = CircuitCache(skip_qobj_deepcopy=True) quantum_instance_caching = QuantumInstance(backend, circuit_cache=circuit_cache, skip_qobj_validation=True) result_caching = algo.run(quantum_instance_caching) self.assertLessEqual(circuit_cache.misses, 1) self.assertAlmostEqual( self.reference_vqe_result['statevector_simulator']['energy'], result_caching['energy'])
def run_VQE(self): """Runs the Variational Quantum Eigensolver (VQE)""" qubit_op = self.construct_wpo_operator() self.ref = self.exact_eigensolver(qubit_op) # Setting initial state, variational form, and backend init_state = self.init_state_name(self.num_qubits) var_form = self.vf_name(self.num_qubits, depth=self.depth, entanglement='linear', initial_state=init_state) # Don't use SPSA if using a noiseless simulator if self.device == 'statevector_simulator': optimizers = [COBYLA, L_BFGS_B, SLSQP] else: optimizers = [COBYLA, SPSA] print(self.param_table()) # Initializing empty lists & dicts for storage df = pd.DataFrame() algos = {} algo_results = {} for optimizer in optimizers: # For reproducibility aqua_globals.random_seed = 250 print(f'\rOptimizer: {optimizer.__name__} ', end='') counts = [] values = [] params = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) # Running VQE algo = VQE(qubit_op, var_form, optimizer(), callback=store_intermediate_result) quantum_instance = QuantumInstance(backend=self.backend, shots=self.shots) algo_result = algo.run(quantum_instance) df[optimizer.__name__] = pd.Series(data=values, index=counts) algos[optimizer.__name__] = algo algo_results[optimizer.__name__] = algo_result print('\rOptimization complete') self.algos = algos self.result_df = df self.algo_results = algo_results self.optimizers = algo_results.keys() self.results_to_save = { 'file_path': self.file_path, 'ref': self.ref, 'n_qubits': self.num_qubits, 'n_paulis': self.num_paulis, 'depth': self.depth, 'n_shots': self.shots, 'algo_results': self.algo_results, 'result_df': self.result_df }
for i in range(len(optimizers)): aqua_globals.random_seed = 250 optimizer = optimizers[i]() print('\rOptimizer: {} '.format(type(optimizer).__name__), end='') counts = [] values = [] params = [] def store_intermediate_result(eval_count, parameters, mean, std): counts.append(eval_count) values.append(mean) params.append(parameters) algo = VQE(qubit_op, var_form, optimizer, callback=store_intermediate_result) quantum_instance = QuantumInstance(backend=backend) algo_result = algo.run(quantum_instance) converge_cnts[i] = np.asarray(counts) converge_vals[i] = np.asarray(values) param_vals[i] = np.asarray(params) print('\rOptimization complete ') # In[12]: ee = ExactEigensolver(qubit_op) result = ee.run() ref = result['energy'] print('Reference value: {}'.format(ref))
def run_ucc_r12(opt): """ Parameters ---------- * opt dictionary with user and default options/thresholds Returns ------- * UCC-R12 ground state energy """ import itertools import logging import numpy as np import time from datetime import datetime import qiskit from qiskit import BasicAer,Aer from qiskit.aqua import set_qiskit_aqua_logging, QuantumInstance from qiskit.aqua.operators import Z2Symmetries, WeightedPauliOperator from qiskit.aqua.algorithms.adaptive import VQE from qiskit.aqua.algorithms.classical import ExactEigensolver from qiskit.aqua.components.optimizers import L_BFGS_B,CG,SPSA,SLSQP, COBYLA from qiskit.chemistry.drivers import PySCFDriver, UnitsType, HFMethodType from qiskit.chemistry.core import TransformationType, QubitMappingType from qiskit.chemistry.aqua_extensions.components.initial_states import HartreeFock from qiskit.chemistry import set_qiskit_chemistry_logging # ----- local functions ----- # import sys sys.path.append('/Users/mario/Documents/GitHub/R12-F12/project_ec/ucc_ec/') from qmolecule_ec import QMolecule_ec,build_parameter_list from hamiltonian_ec import Hamiltonian from uccsd_ec import UCCSD from davidson import davidson #import logging #set_qiskit_chemistry_logging(logging.DEBUG) logfile = open(opt["logfile"],'w') dateTimeObj = datetime.now() logfile.write("date and time "+str(dateTimeObj)+"\n") logfile.write("\n\n") import subprocess label = subprocess.check_output(['git','log','-1','--format="%H"']).strip() logfile.write("git commit "+str(label)+"\n") logfile.write("\n\n") qiskit_dict = qiskit.__qiskit_version__ logfile.write("qiskit version \n") for k in qiskit_dict: logfile.write(k+" : "+qiskit_dict[k]+"\n") logfile.write("\n\n") logfile.write("local run options \n") for k in opt: logfile.write(k+" : "+str(opt[k])+"\n") logfile.write("\n\n") import time t0 = time.time() if(opt["input_file"] is None): # ----- normal molecular calc ----- # if(opt["calc_type"].lower() == "rhf"): hf=HFMethodType.RHF if(opt["calc_type"].lower() == "rohf"): hf=HFMethodType.ROHF if(opt["calc_type"].lower() == "uhf"): hf=HFMethodType.UHF driver = PySCFDriver(atom=opt["geometry"],unit=UnitsType.ANGSTROM,charge=opt["charge"],spin=opt["spin"],basis=opt["basis"],hf_method=hf) molecule = driver.run() molecule_ec = QMolecule_ec(molecule=molecule,filename=None,logfile=logfile) else: # ----- custom matrix elements ----- # molecule_ec = QMolecule_ec(molecule=None,filename=opt["input_file"],calc=opt["calc_type"],nfreeze=opt["nfreeze"],logfile=logfile) molecule_ec.mo_eri_ints_ec = (molecule_ec.mo_eri_ints_ec).transpose((0,1,3,2)) t1 = time.time() logfile.write("classical ES and setup: %f [s] \n" % (t1-t0)) logfile.write("\n\n") core = Hamiltonian(qubit_mapping=QubitMappingType.PARITY,two_qubit_reduction=True,freeze_core=False) qubit_op, _ = core.run(molecule_ec) t2 = time.time() logfile.write("second-quantized Hamiltonian setup : %f [s] \n" % (t2-t1)) logfile.write("\n\n") logfile.write("Original number of qubits %d \n" % (qubit_op.num_qubits)) z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op) nsym = len(z2_symmetries.sq_paulis) the_tapered_op = qubit_op sqlist = None z2syms = None if(nsym>0): logfile.write('\nZ2 symmetries found: \n') for symm in z2_symmetries.symmetries: logfile.write(symm.to_label()) logfile.write('\nsingle-qubit operators found: \n') for sq in z2_symmetries.sq_paulis: logfile.write(sq.to_label()) logfile.write('\nCliffords found: \n') for clifford in z2_symmetries.cliffords: logfile.write(clifford.print_details()) logfile.write('\nsingle-qubit list: {} \n'.format(z2_symmetries.sq_list)) tapered_ops = z2_symmetries.taper(qubit_op) for tapered_op in tapered_ops: logfile.write("Number of qubits of tapered qubit operator: %d \n" % (tapered_op.num_qubits)) t3 = time.time() logfile.write("detection of symmetries: %f [s] \n" % (t3-t2)) smallest_eig_value = 99999999999999 smallest_idx = -1 for idx in range(len(tapered_ops)): td0 = time.time() from utils import retrieve_SCF_energy print("In sector ",idx,len(tapered_ops)) curr_value = retrieve_SCF_energy(tapered_ops[idx].copy(),core,opt) #,parm_list) curr_value = np.abs(curr_value-molecule_ec.hf_energy) print("Deviation ",curr_value) if curr_value < smallest_eig_value: smallest_eig_value = curr_value smallest_idx = idx if(curr_value<1e-6): break td1 = time.time() val = curr_value logfile.write("Lowest-energy computational basis state of the {}-th tapered operator is %s %f \n" % (str(idx),val)) logfile.write("HF search time %f: \n" % (td1-td0)) the_tapered_op = tapered_ops[smallest_idx] the_coeff = tapered_ops[smallest_idx].z2_symmetries.tapering_values logfile.write("{}-th tapered operator, with corresponding symmetry sector of {}".format(smallest_idx, the_coeff)) logfile.write("\nNumber of qubits in the {}-th tapered operator {}\n\n".format(smallest_idx,the_tapered_op.num_qubits)) sqlist = the_tapered_op.z2_symmetries.sq_list z2syms = the_tapered_op.z2_symmetries # ======== # setup initial state # ======== init_state = HartreeFock(num_qubits=the_tapered_op.num_qubits, num_orbitals=core._molecule_info['num_orbitals'], qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_particles=core._molecule_info['num_particles'],sq_list=sqlist) # ---- initial parameter guess init_parm = None if(opt["start_pt"].lower()=="file"): init_parm = np.loadtxt('vqe.parameters') if(opt["var_form"].lower()=="uccsd" and opt["start_pt"].lower()=="ccsd"): parm_list = build_parameter_list(molecule_ec) logfile.write("Initial parameters = %d\n" % len(parm_list)) for mu,p in enumerate(parm_list): logfile.write('%d %f\n' % (mu,p)) if(opt["var_form"].lower()=="uccsd"): var_form = UCCSD(num_qubits=the_tapered_op.num_qubits,depth=opt["UCCSD_depth"], num_orbitals=core._molecule_info['num_orbitals'], num_particles=core._molecule_info['num_particles'], active_occupied=opt["UCCSD_active_occupied"], active_unoccupied=opt["UCCSD_active_unoccupied"], initial_state=init_state, qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_time_slices=opt["UCCSD_num_time_slices"],z2_symmetries=z2syms,init_parm=parm_list) if(opt["var_form"].lower()=="uccsd" and opt["start_pt"].lower()=="ccsd"): nparm,ndepth = len(var_form._mask),var_form._depth init_parm = np.zeros(nparm*ndepth) for idp in range(ndepth): for ims in range(nparm): init_parm[ims+idp*nparm] = parm_list[var_form._mask[ims]] logfile.write("Selected parameters = %d\n" % nparm) for mu,p in enumerate(var_form._mask): logfile.write('%d %f\n' % (p,parm_list[p])) elif(opt["var_form"].lower()=="ry"): var_form = RY(the_tapered_op.num_qubits,depth=opt["R_depth"], entanglement=opt["R_entanglement"],initial_state=HF_state) elif(opt["var_form"].lower()=="ryrz"): var_form = RYRZ(the_tapered_op.num_qubits,depth=opt["R_depth"], entanglement=opt["R_entanglement"],initial_state=HF_state) elif(opt["var_form"].lower()=="swaprz"): var_form = SwapRZ(the_tapered_op.num_qubits,depth=opt["R_depth"], entanglement=opt["R_entanglement"],initial_state=HF_state) else: print("invalid variational form") assert(False) # setup optimizer if( opt["optimizer"].lower()=="bfgs"): optimizer = L_BFGS_B(maxiter=opt["max_eval"]) elif(opt["optimizer"].lower()=="cg"): optimizer = CG(maxiter=opt["max_eval"]) elif(opt["optimizer"].lower()=="slsqp"): optimizer = SLSQP(maxiter=opt["max_eval"]) elif(opt["optimizer"].lower()=="spsa"): optimizer = SPSA() elif(opt["optimizer"].lower()=="cobyla"): optimizer = COBYLA(maxiter=opt["max_eval"]) else: print("not coded yet"); assert(False) # set vqe if(opt["var_form"].lower()=="uccsd"): algo = VQE(the_tapered_op,var_form,optimizer,initial_point=init_parm) else: algo = VQE(the_tapered_op,var_form,optimizer) # setup backend backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend) t0 = time.time() algo_result = algo.run(quantum_instance) t1 = time.time() logfile.write("\nVQE time [s] %f \n\n" % (t1-t0)) result = core.process_algorithm_result(algo_result) for line in result[0]: logfile.write(line+"\n") logfile.write("\nThe parameters for UCCSD are:\n") for i,(tc,tq) in enumerate(zip(init_parm,algo_result['opt_params'])): logfile.write("%d %f %f \n" % (i,tc,tq)) if(opt["print_parameters"]): par_file = open('vqe.parameters','w') for p in algo_result['opt_params']: par_file.write("%f \n" % p) par_file.close() #td0 = time.time() #ee = davidson(the_tapered_op,'fci') #td1 = time.time() #logfile.write("\n\nExact diagonalization, energy: %f \n" % (ee+molecule_ec.nuclear_repulsion_energy+molecule_ec.energy_offset_ec)) #logfile.write("Davidson FCI time: %f [s] \n" % (td1-td0)) print('============================================================================') print(' DONE!') print('============================================================================') return 0
var_form = UCCSD(num_qubits=the_tapered_op.num_qubits, depth=1, num_orbitals=core._molecule_info['num_orbitals'], num_particles=core._molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction, num_time_slices=1, z2_symmetries=the_tapered_op.z2_symmetries, shallow_circuit_concat=False) # force_no_tap_excitation=True, # method_doubles='succ', # excitation_type='d', # same_spin_doubles=False) # set up VQE algo = VQE(the_tapered_op, var_form, optimizer) # Choose the backend (use Aer instead of BasicAer) backend = Aer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend=backend, optimization_level=1) # run the algorithm algo_result = algo.run(quantum_instance) # get the results _, result = core.process_algorithm_result(algo_result) print(result)