def test_callback(self): """Test the callback on VQE.""" history = {'eval_count': [], 'parameters': [], 'mean': [], 'std': []} def store_intermediate_result(eval_count, parameters, mean, std): history['eval_count'].append(eval_count) history['parameters'].append(parameters) history['mean'].append(mean) history['std'].append(std) optimizer = COBYLA(maxiter=3) wavefunction = self.ry_wavefunction vqe = VQE(self.h2_op, wavefunction, optimizer, callback=store_intermediate_result) vqe.run(self.qasm_simulator) self.assertTrue( all(isinstance(count, int) for count in history['eval_count'])) self.assertTrue( all(isinstance(mean, float) for mean in history['mean'])) self.assertTrue(all(isinstance(std, float) for std in history['std'])) for params in history['parameters']: self.assertTrue(all(isinstance(param, float) for param in params))
def test_vqe_reuse(self): """ Test vqe reuse """ vqe = VQE() with self.assertRaises(AquaError): _ = vqe.run() num_qubits = self.qubit_op.num_qubits var_form = RY(num_qubits, depth=3) vqe.var_form = var_form with self.assertRaises(AquaError): _ = vqe.run() vqe.operator = self.qubit_op with self.assertRaises(AquaError): _ = vqe.run() qinst = QuantumInstance(BasicAer.get_backend('statevector_simulator')) vqe.quantum_instance = qinst result = vqe.run() self.assertAlmostEqual(result.eigenvalue.real, -1.85727503, places=5) operator = MatrixOperator(np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) vqe.operator = operator result = vqe.run() self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5)
def test_reuse(self): """Test re-using a VQE algorithm instance.""" vqe = VQE() with self.subTest(msg='assert running empty raises AquaError'): with self.assertRaises(AquaError): _ = vqe.run() var_form = TwoLocal(rotation_blocks=['ry', 'rz'], entanglement_blocks='cz') vqe.var_form = var_form with self.subTest(msg='assert missing operator raises AquaError'): with self.assertRaises(AquaError): _ = vqe.run() vqe.operator = self.h2_op with self.subTest(msg='assert missing backend raises AquaError'): with self.assertRaises(AquaError): _ = vqe.run() vqe.quantum_instance = self.statevector_simulator with self.subTest(msg='assert VQE works once all info is available'): result = vqe.run() self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) operator = PrimitiveOp( np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) with self.subTest(msg='assert minimum eigensolver interface works'): result = vqe.compute_minimum_eigenvalue(operator) self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5)
def test_backend_change(self, user_expectation): """Test that VQE works when backend changes.""" vqe = VQE( operator=self.h2_op, var_form=TwoLocal(rotation_blocks=['ry', 'rz'], entanglement_blocks='cz'), optimizer=SLSQP(maxiter=2), expectation=user_expectation, quantum_instance=BasicAer.get_backend('statevector_simulator')) result0 = vqe.run() if user_expectation is not None: with self.subTest('User expectation kept.'): self.assertEqual(vqe.expectation, user_expectation) else: with self.subTest('Expectation created.'): self.assertIsInstance(vqe.expectation, ExpectationBase) try: vqe.set_backend(BasicAer.get_backend('qasm_simulator')) except Exception as ex: # pylint: disable=broad-except self.fail("Failed to change backend. Error: '{}'".format(str(ex))) return result1 = vqe.run() if user_expectation is not None: with self.subTest( 'Change backend with user expectation, it is kept.'): self.assertEqual(vqe.expectation, user_expectation) else: with self.subTest( 'Change backend without user expectation, one created.'): self.assertIsInstance(vqe.expectation, ExpectationBase) with self.subTest('Check results.'): self.assertEqual(len(result0.optimal_point), len(result1.optimal_point))
def test_vqe_callback(self, var_form_type): """ VQE Callback test """ history = {'eval_count': [], 'parameters': [], 'mean': [], 'std': []} def store_intermediate_result(eval_count, parameters, mean, std): history['eval_count'].append(eval_count) history['parameters'].append(parameters) history['mean'].append(mean) history['std'].append(std) backend = BasicAer.get_backend('qasm_simulator') num_qubits = self.qubit_op.num_qubits init_state = Zero(num_qubits) var_form = RY(num_qubits, depth=1, initial_state=init_state) if var_form_type is QuantumCircuit: params = ParameterVector('θ', var_form.num_parameters) var_form = var_form.construct_circuit(params) optimizer = COBYLA(maxiter=3) algo = VQE(self.qubit_op, var_form, optimizer, callback=store_intermediate_result, auto_conversion=False) aqua_globals.random_seed = 50 quantum_instance = QuantumInstance(backend, seed_transpiler=50, shots=1024, seed_simulator=50) algo.run(quantum_instance) self.assertTrue(all(isinstance(count, int) for count in history['eval_count'])) self.assertTrue(all(isinstance(mean, float) for mean in history['mean'])) self.assertTrue(all(isinstance(std, float) for std in history['std'])) for params in history['parameters']: self.assertTrue(all(isinstance(param, float) for param in params))
def test_vqe_reuse(self): """ Test vqe reuse """ vqe = VQE() with self.assertRaises(AquaError): _ = vqe.run() var_form = TwoLocal(rotation_blocks=['ry', 'rz'], entanglement_blocks='cz') vqe.var_form = var_form with self.assertRaises(AquaError): _ = vqe.run() vqe.operator = self.qubit_op with self.assertRaises(AquaError): _ = vqe.run() qinst = QuantumInstance(BasicAer.get_backend('statevector_simulator')) vqe.quantum_instance = qinst result = vqe.run() self.assertAlmostEqual(result.eigenvalue.real, -1.85727503, places=5) operator = PrimitiveOp( np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) vqe.operator = operator result = vqe.run() self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5)
def test_vqe_callback(self): tmp_filename = 'vqe_callback_test.csv' is_file_exist = os.path.exists(self._get_resource_path(tmp_filename)) if is_file_exist: os.remove(self._get_resource_path(tmp_filename)) def store_intermediate_result(eval_count, parameters, mean, std): with open(self._get_resource_path(tmp_filename), 'a') as f: content = "{},{},{:.5f},{:.5f}".format(eval_count, parameters, mean, std) print(content, file=f, flush=True) backend = get_aer_backend('qasm_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 = COBYLA(maxiter=3) algo = VQE(self.algo_input.qubit_op, var_form, optimizer, 'paulis', callback=store_intermediate_result) algo.random_seed = 50 run_config = RunConfig(shots=1024, seed=50) quantum_instance = QuantumInstance(backend, seed_mapper=50, run_config=run_config) algo.run(quantum_instance) is_file_exist = os.path.exists(self._get_resource_path(tmp_filename)) self.assertTrue(is_file_exist, "Does not store content successfully.") # check the content ref_content = [[ "1", "[-0.03391886 -1.70850424 -1.53640265 -0.65137839]", "-0.59622", "0.01546" ], [ "2", "[ 0.96608114 -1.70850424 -1.53640265 -0.65137839]", "-0.77452", "0.01692" ], [ "3", "[ 0.96608114 -0.70850424 -1.53640265 -0.65137839]", "-0.80327", "0.01519" ]] with open(self._get_resource_path(tmp_filename)) as f: idx = 0 for record in f.readlines(): eval_count, parameters, mean, std = record.split(",") self.assertEqual(eval_count.strip(), ref_content[idx][0]) self.assertEqual(parameters, ref_content[idx][1]) self.assertEqual(mean.strip(), ref_content[idx][2]) self.assertEqual(std.strip(), ref_content[idx][3]) idx += 1 if is_file_exist: os.remove(self._get_resource_path(tmp_filename))
def test_vqe_no_varform_params(self): """Test specifying a variational form with no parameters raises an error.""" circuit = QuantumCircuit(self.qubit_op.num_qubits) for i in range(circuit.num_qubits): circuit.h(i) circuit.cx(i, (i + 1) % circuit.num_qubits) circuit.rx(0.2, i) vqe = VQE(self.qubit_op, circuit) with self.assertRaises(RuntimeError): vqe.run(BasicAer.get_backend('statevector_simulator'))
def test_vqe_callback(self): """ VQE Callback test """ tmp_filename = 'vqe_callback_test.csv' is_file_exist = os.path.exists(self.get_resource_path(tmp_filename)) if is_file_exist: os.remove(self.get_resource_path(tmp_filename)) def store_intermediate_result(eval_count, parameters, mean, std): with open(self.get_resource_path(tmp_filename), 'a') as file: content = "{},{},{:.5f},{:.5f}".format(eval_count, parameters, mean, std) print(content, file=file, flush=True) backend = BasicAer.get_backend('qasm_simulator') num_qubits = self.qubit_op.num_qubits init_state = Zero(num_qubits) var_form = RY(num_qubits, 1, initial_state=init_state) optimizer = COBYLA(maxiter=3) algo = VQE(self.qubit_op, var_form, optimizer, callback=store_intermediate_result, auto_conversion=False) aqua_globals.random_seed = 50 quantum_instance = QuantumInstance(backend, seed_transpiler=50, shots=1024, seed_simulator=50) algo.run(quantum_instance) is_file_exist = os.path.exists(self.get_resource_path(tmp_filename)) self.assertTrue(is_file_exist, "Does not store content successfully.") # check the content ref_content = [['1', '[-0.03391886 -1.70850424 -1.53640265 -0.65137839]', '-0.61121', '0.01572'], ['2', '[ 0.96608114 -1.70850424 -1.53640265 -0.65137839]', '-0.79235', '0.01722'], ['3', '[ 0.96608114 -0.70850424 -1.53640265 -0.65137839]', '-0.82829', '0.01529'] ] try: with open(self.get_resource_path(tmp_filename)) as file: idx = 0 for record in file.readlines(): eval_count, parameters, mean, std = record.split(",") self.assertEqual(eval_count.strip(), ref_content[idx][0]) self.assertEqual(parameters, ref_content[idx][1]) self.assertEqual(mean.strip(), ref_content[idx][2]) self.assertEqual(std.strip(), ref_content[idx][3]) idx += 1 finally: if is_file_exist: os.remove(self.get_resource_path(tmp_filename))
def test_vqe_qasm_snapshot_mode(self, mode): """ VQE Aer qasm_simulator snapshot mode test """ try: # pylint: disable=import-outside-toplevel from qiskit import Aer except Exception as ex: # pylint: disable=broad-except self.skipTest( "Aer doesn't appear to be installed. Error: '{}'".format( str(ex))) return backend = Aer.get_backend('qasm_simulator') optimizer = L_BFGS_B() wavefunction = self.ry_wavefunction[mode] if mode == 'wrapped': warnings.filterwarnings('ignore', category=DeprecationWarning) vqe = VQE(self.qubit_op, wavefunction, optimizer, max_evals_grouped=1) if mode == 'wrapped': warnings.filterwarnings('always', category=DeprecationWarning) quantum_instance = QuantumInstance( backend, shots=1, seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed) result = vqe.run(quantum_instance) self.assertAlmostEqual(result.eigenvalue.real, -1.85727503, places=6)
def _vqe_run(self, operator_list: List[BaseOperator], initial_parameters: np.ndarray, **kwargs) -> dict: self._current_operator_list = operator_list self._current_initial_parameters = initial_parameters var_form = self.variational_form() vqe = VQE( operator=self.hamiltonian, var_form=var_form, optimizer=self.vqe_optimizer, initial_point=initial_parameters, max_evals_grouped=self.max_evals_grouped, aux_operators=self.aux_operators, callback=None, auto_conversion=self.auto_conversion ) vqe_result = vqe.run(self.quantum_instance, **kwargs) # == vqe._ret return { 'optimal_circuit': vqe.get_optimal_circuit(), 'optimal_params': vqe.optimal_params, '_ret': vqe_result }
def test_swaprz(self, mode): """ SwapRZ variational form test """ driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5')) qmolecule = driver.run() operator = Hamiltonian(qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False) qubit_op, _ = operator.run(qmolecule) optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( operator.molecule_info['num_orbitals'], operator.molecule_info['num_particles'], qubit_mapping=operator._qubit_mapping, two_qubit_reduction=operator._two_qubit_reduction) if mode == 'wrapped': warnings.filterwarnings('ignore', category=DeprecationWarning) wavefunction = SwapRZ(qubit_op.num_qubits, initial_state=initial_state) else: wavefunction = ExcitationPreserving(qubit_op.num_qubits, initial_state=initial_state) algo = VQE(qubit_op, wavefunction, optimizer) if mode == 'wrapped': warnings.filterwarnings('always', category=DeprecationWarning) result = algo.run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) result = operator.process_algorithm_result(result) self.assertAlmostEqual(result.energy, self.reference_energy, places=6)
def test_vqe(self): """Test VQE with gradients""" method = 'lin_comb' backend = 'qasm_simulator' q_instance = QuantumInstance(BasicAer.get_backend(backend), seed_simulator=79, seed_transpiler=2) # Define the Hamiltonian h2_hamiltonian = -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) \ - 0.01 * (Z ^ Z) + 0.18 * (X ^ X) h2_energy = -1.85727503 # Define the Ansatz wavefunction = QuantumCircuit(2) params = ParameterVector('theta', length=8) itr = iter(params) wavefunction.ry(next(itr), 0) wavefunction.ry(next(itr), 1) wavefunction.rz(next(itr), 0) wavefunction.rz(next(itr), 1) wavefunction.cx(0, 1) wavefunction.ry(next(itr), 0) wavefunction.ry(next(itr), 1) wavefunction.rz(next(itr), 0) wavefunction.rz(next(itr), 1) # Conjugate Gradient algorithm optimizer = CG(maxiter=10) grad = Gradient(grad_method=method) # Gradient callable vqe = VQE(h2_hamiltonian, wavefunction, optimizer=optimizer, gradient=grad) result = vqe.run(q_instance) np.testing.assert_almost_equal(result['optimal_value'], h2_energy, decimal=0)
def simulate(self, var_params): """ Evaluate the parameterized circuit for the input amplitudes. Args: var_params (list): The initial amplitudes (float64). Returns: float64: The total energy (energy). Raise: ValueError: If the dimension of the amplitude list is incorrect. """ if len(var_params) != self.amplitude_dimension: raise ValueError("Incorrect dimension for amplitude list.") # Use the Qiskit VQE class to perform a single energy evaluation from qiskit.aqua.components.optimizers import COBYLA cobyla = COBYLA(maxiter=0) vqe = VQE(self.qubit_hamiltonian, self.var_form, cobyla, initial_point=var_params) quantum_instance = QuantumInstance(backend=self.backend, shots=1000000) results = vqe.run(quantum_instance) energy = results['eigvals'][0] + self.nuclear_repulsion_energy # Save the amplitudes so we have the optimal ones for RDM calculation self.optimized_amplitudes = var_params return energy
def test_uccsd_hf(self): """ uccsd hf test """ backend = BasicAer.get_backend('statevector_simulator') algo = VQE(self.qubit_op, self.var_form, self.optimizer) result = algo.run(QuantumInstance(backend)) result = self.core.process_algorithm_result(result) self.assertAlmostEqual(result.energy, self.reference_energy, places=6)
def test_uccsd_hf(self): """ uccsd hf test """ driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5')) qmolecule = driver.run() core = Hamiltonian(qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True) qubit_op, _ = core.run(qmolecule) optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( core.molecule_info['num_orbitals'], core.molecule_info['num_particles'], qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction) var_form = UCCSD(num_orbitals=core.molecule_info['num_orbitals'], num_particles=core.molecule_info['num_particles'], initial_state=initial_state, qubit_mapping=core._qubit_mapping, two_qubit_reduction=core._two_qubit_reduction) algo = VQE(qubit_op, var_form, optimizer) result = algo.run( QuantumInstance(BasicAer.get_backend('statevector_simulator'))) result = core.process_algorithm_result(result) self.assertAlmostEqual(result.energy, self.reference_energy, places=6)
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_qasm_snapshot_mode(self): """Test the VQE using Aer's qasm_simulator snapshot mode.""" try: # pylint: disable=import-outside-toplevel from qiskit import Aer except Exception as ex: # pylint: disable=broad-except self.skipTest( "Aer doesn't appear to be installed. Error: '{}'".format( str(ex))) return backend = Aer.get_backend('qasm_simulator') optimizer = L_BFGS_B() wavefunction = self.ry_wavefunction vqe = VQE(self.h2_op, wavefunction, optimizer, expectation=AerPauliExpectation(), max_evals_grouped=1) quantum_instance = QuantumInstance( backend, shots=1, seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed) result = vqe.run(quantum_instance) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6)
def test_with_aer_qasm(self): """Test VQE with Aer's qasm_simulator.""" try: # pylint: disable=import-outside-toplevel from qiskit import Aer except Exception as ex: # pylint: disable=broad-except self.skipTest( "Aer doesn't appear to be installed. Error: '{}'".format( str(ex))) return backend = Aer.get_backend('qasm_simulator') optimizer = SPSA(maxiter=200, last_avg=5) wavefunction = self.ry_wavefunction vqe = VQE(self.h2_op, wavefunction, optimizer, expectation=PauliExpectation()) quantum_instance = QuantumInstance( backend, seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed) result = vqe.run(quantum_instance) self.assertAlmostEqual(result.eigenvalue.real, -1.86305, places=2)
def test_excitation_preserving(self): """Test the excitation preserving wavefunction on a chemistry example.""" driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5')) qmolecule = driver.run() operator = Hamiltonian(qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False) qubit_op, _ = operator.run(qmolecule) optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( operator.molecule_info['num_orbitals'], operator.molecule_info['num_particles'], qubit_mapping=operator._qubit_mapping, two_qubit_reduction=operator._two_qubit_reduction) wavefunction = ExcitationPreserving(qubit_op.num_qubits, initial_state=initial_state) algo = VQE(qubit_op, wavefunction, optimizer) result = algo.run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) result = operator.process_algorithm_result(result) self.assertAlmostEqual(result.energy, self.reference_energy, places=6)
def test_vqe_2_iqpe(self): """ vqe to iqpe test """ backend = BasicAer.get_backend('qasm_simulator') num_qbits = self.qubit_op.num_qubits wavefunction = TwoLocal(num_qbits, ['ry', 'rz'], 'cz', reps=3, insert_barriers=True) optimizer = SPSA(maxiter=10) algo = VQE(self.qubit_op, wavefunction, optimizer) quantum_instance = QuantumInstance(backend, seed_simulator=self.seed, seed_transpiler=self.seed) result = algo.run(quantum_instance) self.log.debug('VQE result: %s.', result) ref_eigenval = -1.85727503 # Known reference value num_time_slices = 1 num_iterations = 6 param_dict = result.optimal_parameters state_in = VarFormBased(wavefunction, param_dict) iqpe = IQPE(self.qubit_op, state_in, num_time_slices, num_iterations, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) quantum_instance = QuantumInstance(backend, shots=100, seed_transpiler=self.seed, seed_simulator=self.seed) result = iqpe.run(quantum_instance) self.log.debug('top result str label: %s', result.top_measurement_label) self.log.debug('top result in decimal: %s', result.top_measurement_decimal) self.log.debug('stretch: %s', result.stretch) self.log.debug('translation: %s', result.translation) self.log.debug('final eigenvalue from QPE: %s', result.eigenvalue) self.log.debug('reference eigenvalue: %s', ref_eigenval) self.log.debug('ref eigenvalue (transformed): %s', (ref_eigenval + result.translation) * result.stretch) self.log.debug( 'reference binary str label: %s', decimal_to_binary( (ref_eigenval.real + result.translation) * result.stretch, max_num_digits=num_iterations + 3, fractional_part_only=True)) self.assertAlmostEqual(result.eigenvalue.real, ref_eigenval.real, delta=1e-2)
def test_swaprz(self): """ SwapRZ variational form test """ driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5')) qmolecule = driver.run() operator = Hamiltonian(qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False) qubit_op, _ = operator.run(qmolecule) optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( qubit_op.num_qubits, operator.molecule_info['num_orbitals'], operator.molecule_info['num_particles'], qubit_mapping=operator._qubit_mapping, two_qubit_reduction=operator._two_qubit_reduction) var_form = SwapRZ(qubit_op.num_qubits, initial_state=initial_state) algo = VQE(qubit_op, var_form, optimizer) result = algo.run( QuantumInstance(BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) _, result = operator.process_algorithm_result(result) self.assertAlmostEqual(result['energy'], self.reference_energy, places=6)
def test_uccsd_hf_qUCCSD(self): """ uccsd tapering test using all double excitations """ # optimizer optimizer = SLSQP(maxiter=100) # initial state init_state = HartreeFock(num_qubits=self.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.the_tapered_op.z2_symmetries.sq_list) var_form = UCCSD(num_qubits=self.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=self.the_tapered_op.z2_symmetries, shallow_circuit_concat=False, method_doubles='ucc', excitation_type='sd', skip_commute_test=True) algo = VQE(self.the_tapered_op, var_form, optimizer) result = algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator'))) _, result = self.core.process_algorithm_result(result) self.assertAlmostEqual(result['energy'], self.reference_energy_UCCSD, places=6)
def test_uccsd_hf_qpUCCD(self): """ paired uccd test """ optimizer = SLSQP(maxiter=100) initial_state = HartreeFock(self.qubit_op.num_qubits, self.core.molecule_info['num_orbitals'], self.core.molecule_info['num_particles'], qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction) var_form = UCCSD(num_qubits=self.qubit_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=initial_state, qubit_mapping=self.core._qubit_mapping, two_qubit_reduction=self.core._two_qubit_reduction, num_time_slices=1, shallow_circuit_concat=False, method_doubles='pucc', excitation_type='d' ) algo = VQE(self.qubit_op, var_form, optimizer) result = algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator'))) _, result = self.core.process_algorithm_result(result) self.assertAlmostEqual(result['energy'], self.reference_energy_pUCCD, places=6)
def test_deprecated_variational_forms(self): """Test running the VQE on a deprecated VariationalForm object.""" warnings.filterwarnings('ignore', category=DeprecationWarning) wavefunction = RYRZ(2) vqe = VQE(self.h2_op, wavefunction, L_BFGS_B()) warnings.filterwarnings('always', category=DeprecationWarning) result = vqe.run(self.statevector_simulator) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy)
def test_vqe_qasm(self): backend = BasicAer.get_backend('qasm_simulator') num_qubits = self.algo_input.qubit_op.num_qubits var_form = RY(num_qubits, 3) optimizer = SPSA(max_trials=300, last_avg=5) algo = VQE(self.algo_input.qubit_op, var_form, optimizer, max_evals_grouped=1) quantum_instance = QuantumInstance(backend, shots=10000, optimization_level=0) result = algo.run(quantum_instance) self.assertAlmostEqual(result['energy'], -1.85727503, places=2)
def test_circuit_input(self): """Test running the VQE on a plain QuantumCircuit object.""" wavefunction = QuantumCircuit(2).compose(EfficientSU2(2)) optimizer = SLSQP(maxiter=50) vqe = VQE(self.h2_op, wavefunction, optimizer=optimizer) result = vqe.run(self.statevector_simulator) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5)
def test_vqe_2_iqpe(self): """ vqe to iqpe test """ backend = BasicAer.get_backend('qasm_simulator') num_qbits = self.algo_input.qubit_op.num_qubits var_form = RYRZ(num_qbits, 3) optimizer = SPSA(max_trials=10) # optimizer.set_options(**{'max_trials': 500}) algo = VQE(self.algo_input.qubit_op, var_form, optimizer) quantum_instance = QuantumInstance(backend, seed_simulator=self.seed, seed_transpiler=self.seed) result = algo.run(quantum_instance) self.log.debug('VQE result: %s.', result) ref_eigenval = -1.85727503 num_time_slices = 1 num_iterations = 6 state_in = VarFormBased(var_form, result['opt_params']) iqpe = IQPE(self.algo_input.qubit_op, state_in, num_time_slices, num_iterations, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) quantum_instance = QuantumInstance(backend, shots=100, seed_transpiler=self.seed, seed_simulator=self.seed) result = iqpe.run(quantum_instance) self.log.debug('top result str label: %s', result['top_measurement_label']) self.log.debug('top result in decimal: %s', result['top_measurement_decimal']) self.log.debug('stretch: %s', result['stretch']) self.log.debug('translation: %s', result['translation']) self.log.debug('final eigenvalue from QPE: %s', result['energy']) self.log.debug('reference eigenvalue: %s', ref_eigenval) self.log.debug('ref eigenvalue (transformed): %s', (ref_eigenval + result['translation']) * result['stretch']) self.log.debug( 'reference binary str label: %s', decimal_to_binary( (ref_eigenval + result['translation']) * result['stretch'], max_num_digits=num_iterations + 3, fractional_part_only=True)) np.testing.assert_approx_equal(result['energy'], ref_eigenval, significant=2)
def solve_maxcut_vqe(graph, solve_type): backend = get_compute_backend(solve_type) operator, offset = get_operator(graph) vqe = VQE( operator, RYRZ(graph.number_of_nodes(), depth=3, entanglement="linear"), L_BFGS_B(maxfun=6000), ) result = vqe.run(QuantumInstance(backend)) return result
def test_basic_aer_qasm(self): """Test the VQE on BasicAer's QASM simulator.""" optimizer = SPSA(max_trials=300, last_avg=5) wavefunction = self.ry_wavefunction vqe = VQE(self.h2_op, wavefunction, optimizer, max_evals_grouped=1) # TODO benchmark this later. result = vqe.run(self.qasm_simulator) self.assertAlmostEqual(result.eigenvalue.real, -1.86823, places=2)