def test_uccsd_hf_qpUCCD(self): """ paired uccd test """ optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( self.fermionic_transformation.molecule_info['num_orbitals'], self.fermionic_transformation.molecule_info['num_particles'], qubit_mapping=self.fermionic_transformation._qubit_mapping, two_qubit_reduction=self.fermionic_transformation._two_qubit_reduction) var_form = UCCSD( num_orbitals=self.fermionic_transformation.molecule_info['num_orbitals'], num_particles=self.fermionic_transformation.molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=initial_state, qubit_mapping=self.fermionic_transformation._qubit_mapping, two_qubit_reduction=self.fermionic_transformation._two_qubit_reduction, num_time_slices=1, shallow_circuit_concat=False, method_doubles='pucc', excitation_type='d' ) solver = VQE(var_form=var_form, optimizer=optimizer, quantum_instance=QuantumInstance( backend=BasicAer.get_backend('statevector_simulator'))) gsc = GroundStateEigensolver(self.fermionic_transformation, solver) result = gsc.solve(self.driver) self.assertAlmostEqual(result.total_energies[0], self.reference_energy_pUCCD, places=6)
def test_tapered_op(self): """ tapered op test """ optimizer = SLSQP(maxiter=1000) init_state = HartreeFock( num_orbitals=self.fermionic_transformation.molecule_info['num_orbitals'], qubit_mapping=self.fermionic_transformation._qubit_mapping, two_qubit_reduction=self.fermionic_transformation._two_qubit_reduction, num_particles=self.fermionic_transformation.molecule_info['num_particles'], sq_list=self.z2_symmetries.sq_list) var_form = UCCSD( num_orbitals=self.fermionic_transformation.molecule_info['num_orbitals'], num_particles=self.fermionic_transformation.molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=self.fermionic_transformation._qubit_mapping, two_qubit_reduction=self.fermionic_transformation._two_qubit_reduction, num_time_slices=1, z2_symmetries=self.z2_symmetries) solver = VQE(var_form=var_form, optimizer=optimizer, quantum_instance=QuantumInstance( backend=BasicAer.get_backend('statevector_simulator'))) gsc = GroundStateEigensolver(self.fermionic_transformation, solver) result = gsc.solve(self.driver) self.assertAlmostEqual(result.total_energies[0], self.reference_energy, places=6)
def setUp(self): super().setUp() self.reference_energy = -1.1373060356951838 self.seed = 700 aqua_globals.random_seed = self.seed self.driver = HDF5Driver( self.get_resource_path('test_driver_hdf5.hdf5')) fermionic_transformation = FermionicTransformation( qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=False) self.qubit_op, _ = fermionic_transformation.transform(self.driver) self.fermionic_transformation = fermionic_transformation self.optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( fermionic_transformation.molecule_info['num_orbitals'], fermionic_transformation.molecule_info['num_particles'], qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction) self.var_form = UCCSD( num_orbitals=fermionic_transformation. molecule_info['num_orbitals'], num_particles=fermionic_transformation. molecule_info['num_particles'], initial_state=initial_state, qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction)
def test_excitation_preserving(self): """Test the excitation preserving wavefunction on a chemistry example.""" driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5')) fermionic_transformation = FermionicTransformation( qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=False) qubit_op, _ = fermionic_transformation.transform(driver) optimizer = SLSQP(maxiter=100) initial_state = HartreeFock( fermionic_transformation.molecule_info['num_orbitals'], fermionic_transformation.molecule_info['num_particles'], qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction) wavefunction = ExcitationPreserving(qubit_op.num_qubits) wavefunction.compose(initial_state, front=True, inplace=True) solver = VQE(var_form=wavefunction, optimizer=optimizer, quantum_instance=QuantumInstance( BasicAer.get_backend('statevector_simulator'), seed_simulator=aqua_globals.random_seed, seed_transpiler=aqua_globals.random_seed)) gsc = GroundStateEigensolver(fermionic_transformation, solver) result = gsc.solve(driver) self.assertAlmostEqual(result.total_energies[0], self.reference_energy, places=4)
def setUp(self): super().setUp() # np.random.seed(50) self.seed = 50 aqua_globals.random_seed = self.seed try: driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') return molecule = driver.run() self.num_particles = molecule.num_alpha + molecule.num_beta self.num_spin_orbitals = molecule.num_orbitals * 2 fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) map_type = 'PARITY' qubit_op = fer_op.mapping(map_type) self.qubit_op = Z2Symmetries.two_qubit_reduction( to_weighted_pauli_operator(qubit_op), self.num_particles) self.num_qubits = self.qubit_op.num_qubits self.init_state = HartreeFock(self.num_spin_orbitals, self.num_particles) self.var_form_base = None
def test_iqpe(self, distance): """ iqpe test """ self.log.debug('Testing End-to-End with IQPE on H2 with ' 'inter-atomic distance %s.', distance) try: driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 {}'.format(distance), unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') molecule = driver.run() qubit_mapping = 'parity' fer_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) qubit_op = fer_op.mapping(map_type=qubit_mapping, threshold=1e-10) qubit_op = Z2Symmetries.two_qubit_reduction(qubit_op, 2) exact_eigensolver = NumPyMinimumEigensolver(qubit_op) results = exact_eigensolver.run() reference_energy = results.eigenvalue.real self.log.debug('The exact ground state energy is: %s', results.eigenvalue.real) num_particles = molecule.num_alpha + molecule.num_beta two_qubit_reduction = True num_orbitals = qubit_op.num_qubits + (2 if two_qubit_reduction else 0) num_time_slices = 1 num_iterations = 6 state_in = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction) iqpe = IQPE(qubit_op, state_in, num_time_slices, num_iterations, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) backend = qiskit.BasicAer.get_backend('qasm_simulator') quantum_instance = QuantumInstance(backend, shots=100) 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 energy from QPE: %s', result.eigenvalue.real) self.log.debug('reference energy: %s', reference_energy) self.log.debug('ref energy (transformed): %s', (reference_energy + result.translation) * result.stretch) self.log.debug('ref binary str label: %s', decimal_to_binary( (reference_energy + result.translation) * result.stretch, max_num_digits=num_iterations + 3, fractional_part_only=True )) np.testing.assert_approx_equal(result.eigenvalue.real, reference_energy, significant=2)
def cb_create_solver(num_particles, num_orbitals, qubit_mapping, two_qubit_reduction, z2_symmetries): state_in = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, z2_symmetries.sq_list) iqpe = IQPE(None, state_in, num_time_slices=1, num_iterations=6, expansion_mode='suzuki', expansion_order=2, shallow_circuit_concat=True) iqpe.quantum_instance = QuantumInstance( BasicAer.get_backend('qasm_simulator'), shots=100) return iqpe
def test_h2_one_qubit_statevector(self): """Test H2 with tapering and statevector backend.""" two_qubit_reduction = True qubit_mapping = 'parity' warnings.filterwarnings('ignore', category=DeprecationWarning) core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=two_qubit_reduction, freeze_core=False, orbital_reduction=[]) warnings.filterwarnings('always', category=DeprecationWarning) qubit_op, _ = core.run(self.molecule) num_orbitals = core.molecule_info['num_orbitals'] num_particles = core.molecule_info['num_particles'] # tapering z2_symmetries = Z2Symmetries.find_Z2_symmetries(qubit_op) # know the sector tapered_op = z2_symmetries.taper(qubit_op)[1] initial_state = HartreeFock(num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, sq_list=tapered_op.z2_symmetries.sq_list) var_form = UCCSD(num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=tapered_op.z2_symmetries) optimizer = SPSA(maxiter=50) eom_vqe = QEomVQE(tapered_op, var_form, optimizer, num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=tapered_op.z2_symmetries, untapered_op=qubit_op) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) result = eom_vqe.run(quantum_instance) np.testing.assert_array_almost_equal(self.reference, result['energies'], decimal=5)
def test_uccsd_hf_excitations(self): """ uccsd tapering test using all double excitations """ # initial state init_state = HartreeFock( num_orbitals=self.fermionic_transformation.molecule_info['num_orbitals'], qubit_mapping=self.fermionic_transformation._qubit_mapping, two_qubit_reduction=self.fermionic_transformation._two_qubit_reduction, num_particles=self.fermionic_transformation.molecule_info['num_particles'], sq_list=self.fermionic_transformation.molecule_info['z2_symmetries'].sq_list) # check singlet excitations var_form = UCCSD( num_orbitals=self.fermionic_transformation.molecule_info['num_orbitals'], num_particles=self.fermionic_transformation.molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=self.fermionic_transformation._qubit_mapping, two_qubit_reduction=self.fermionic_transformation._two_qubit_reduction, num_time_slices=1, z2_symmetries=self.fermionic_transformation.molecule_info['z2_symmetries'], shallow_circuit_concat=False, method_doubles='succ', excitation_type='d', skip_commute_test=True) double_excitations_singlet = var_form._double_excitations res = TestUCCSDHartreeFock.excitation_lists_comparator( double_excitations_singlet, self.reference_singlet_double_excitations) self.assertEqual(res, True) # check grouped singlet excitations var_form = UCCSD( num_orbitals=self.fermionic_transformation.molecule_info['num_orbitals'], num_particles=self.fermionic_transformation.molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=self.fermionic_transformation._qubit_mapping, two_qubit_reduction=self.fermionic_transformation._two_qubit_reduction, num_time_slices=1, z2_symmetries=self.fermionic_transformation.molecule_info['z2_symmetries'], shallow_circuit_concat=False, method_doubles='succ_full', excitation_type='d', skip_commute_test=True) double_excitations_singlet_grouped = var_form._double_excitations_grouped res_groups = TestUCCSDHartreeFock.group_excitation_lists_comparator( double_excitations_singlet_grouped, self.reference_singlet_groups) self.assertEqual(res_groups, True)
def cb_default_solver(num_particles, num_orbitals, qubit_mapping, two_qubit_reduction, z2_symmetries): """ Default solver """ initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, z2_symmetries.sq_list) var_form = UCCSD(num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=z2_symmetries) vqe = VQE(var_form=var_form) vqe.quantum_instance = quantum_instance return vqe
def cb_create_solver(num_particles, num_orbitals, qubit_mapping, two_qubit_reduction, z2_symmetries): initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, z2_symmetries.sq_list) var_form = UCCSD(num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=z2_symmetries) vqe = VQE(var_form=var_form, optimizer=SLSQP(maxiter=500)) vqe.quantum_instance = BasicAer.get_backend( 'statevector_simulator') return vqe
def test_uccsd_hf_qUCCSD(self): """ uccsd tapering test using all double excitations """ fermionic_transformation = FermionicTransformation( transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[], z2symmetry_reduction='auto' ) qubit_op, _ = fermionic_transformation.transform(self.driver) # optimizer optimizer = SLSQP(maxiter=100) # initial state init_state = HartreeFock( num_orbitals=fermionic_transformation.molecule_info['num_orbitals'], qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction, num_particles=fermionic_transformation.molecule_info['num_particles'], sq_list=fermionic_transformation.molecule_info['z2_symmetries'].sq_list) var_form = UCCSD( num_orbitals=fermionic_transformation.molecule_info['num_orbitals'], num_particles=fermionic_transformation.molecule_info['num_particles'], active_occupied=None, active_unoccupied=None, initial_state=init_state, qubit_mapping=fermionic_transformation._qubit_mapping, two_qubit_reduction=fermionic_transformation._two_qubit_reduction, num_time_slices=1, z2_symmetries=fermionic_transformation.molecule_info['z2_symmetries'], shallow_circuit_concat=False, method_doubles='ucc', excitation_type='sd', skip_commute_test=True) solver = VQE(var_form=var_form, optimizer=optimizer, quantum_instance=QuantumInstance( backend=BasicAer.get_backend('statevector_simulator'))) raw_result = solver.compute_minimum_eigenvalue(qubit_op, None) result = fermionic_transformation.interpret(raw_result) self.assertAlmostEqual(result.total_energies[0], self.reference_energy_UCCSD, places=6)
def get_solver(self, transformation): num_orbitals = transformation.molecule_info['num_orbitals'] num_particles = transformation.molecule_info['num_particles'] qubit_mapping = transformation.qubit_mapping two_qubit_reduction = transformation.molecule_info['two_qubit_reduction'] z2_symmetries = transformation.molecule_info['z2_symmetries'] initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping, two_qubit_reduction, z2_symmetries.sq_list) var_form = UCCSD(num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, z2_symmetries=z2_symmetries) vqe = VQE(var_form=var_form, quantum_instance=self._quantum_instance, optimizer=L_BFGS_B()) return vqe
def test_h2_two_qubits_statevector(self): """Test H2 with parity mapping and statevector backend.""" two_qubit_reduction = True qubit_mapping = 'parity' warnings.filterwarnings('ignore', category=DeprecationWarning) core = Hamiltonian(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=two_qubit_reduction, freeze_core=False, orbital_reduction=[]) warnings.filterwarnings('always', category=DeprecationWarning) qubit_op, _ = core.run(self.molecule) num_orbitals = core.molecule_info['num_orbitals'] num_particles = core.molecule_info['num_particles'] initial_state = HartreeFock(num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction) var_form = UCCSD(num_orbitals=num_orbitals, num_particles=num_particles, initial_state=initial_state, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction) optimizer = COBYLA(maxiter=1000, tol=1e-8) eom_vqe = QEomVQE(qubit_op, var_form, optimizer, num_orbitals=num_orbitals, num_particles=num_particles, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction) backend = BasicAer.get_backend('statevector_simulator') quantum_instance = QuantumInstance(backend) result = eom_vqe.run(quantum_instance) np.testing.assert_array_almost_equal(self.reference, result['energies'], decimal=4)
def test_readme_sample(self): """ readme sample test """ # pylint: disable=import-outside-toplevel,redefined-builtin def print(*args): """ overloads print to log values """ if args: self.log.debug(args[0], *args[1:]) # --- Exact copy of sample code ---------------------------------------- from qiskit.chemistry import FermionicOperator from qiskit.chemistry.drivers import PySCFDriver, UnitsType from qiskit.aqua.operators import Z2Symmetries # Use PySCF, a classical computational chemistry software # package, to compute the one-body and two-body integrals in # molecular-orbital basis, necessary to form the Fermionic operator driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, basis='sto3g') molecule = driver.run() num_particles = molecule.num_alpha + molecule.num_beta num_spin_orbitals = molecule.num_orbitals * 2 # Build the qubit operator, which is the input to the VQE algorithm in Aqua ferm_op = FermionicOperator(h1=molecule.one_body_integrals, h2=molecule.two_body_integrals) map_type = 'PARITY' qubit_op = ferm_op.mapping(map_type) qubit_op = Z2Symmetries.two_qubit_reduction(qubit_op, num_particles) num_qubits = qubit_op.num_qubits # setup a classical optimizer for VQE from qiskit.aqua.components.optimizers import L_BFGS_B optimizer = L_BFGS_B() # setup the initial state for the variational form from qiskit.chemistry.circuit.library import HartreeFock init_state = HartreeFock(num_spin_orbitals, num_particles) # setup the variational form for VQE from qiskit.circuit.library import TwoLocal var_form = TwoLocal(num_qubits, ['ry', 'rz'], 'cz') # add the initial state var_form.compose(init_state, front=True) # setup and run VQE from qiskit.aqua.algorithms import VQE algorithm = VQE(qubit_op, var_form, optimizer) # set the backend for the quantum computation from qiskit import Aer backend = Aer.get_backend('statevector_simulator') result = algorithm.run(backend) print(result.eigenvalue.real) # ---------------------------------------------------------------------- self.assertAlmostEqual(result.eigenvalue.real, -1.8572750301938803, places=6)
def test_qubits_4_jw_h2(self): """ qubits 4 jw h2 test """ state = HartreeFock(4, (1, 1), 'jordan_wigner', False) ref = QuantumCircuit(4) ref.x([0, 2]) self.assertEqual(state, ref)
def test_qubits_4_py_h2(self): """ qubits 4 py h2 test """ state = HartreeFock(4, (1, 1), 'parity', False) ref = QuantumCircuit(4) ref.x([0, 1]) self.assertEqual(state, ref)
def test_qubits_4_bk_h2(self): """ qubits 4 bk h2 test """ state = HartreeFock(4, (1, 1), 'bravyi_kitaev', False) ref = QuantumCircuit(4) ref.x([0, 1, 2]) self.assertEqual(state, ref)
def test_h2_bopes_sampler(self): """Test BOPES Sampler on H2""" seed = 50 aqua_globals.random_seed = seed # Molecule dof = partial(Molecule.absolute_distance, atom_pair=(1, 0)) m = Molecule(geometry=[['H', [0., 0., 1.]], ['H', [0., 0.45, 1.]]], degrees_of_freedom=[dof]) f_t = FermionicTransformation() driver = PySCFDriver(molecule=m) qubitop, _ = f_t.transform(driver) # Quantum Instance: shots = 1 backend = 'statevector_simulator' quantum_instance = QuantumInstance(BasicAer.get_backend(backend), shots=shots) quantum_instance.run_config.seed_simulator = seed quantum_instance.compile_config['seed_transpiler'] = seed # Variational form i_state = HartreeFock( num_orbitals=f_t._molecule_info['num_orbitals'], qubit_mapping=f_t._qubit_mapping, two_qubit_reduction=f_t._two_qubit_reduction, num_particles=f_t._molecule_info['num_particles'], sq_list=f_t._molecule_info['z2_symmetries'].sq_list) var_form = RealAmplitudes(qubitop.num_qubits, reps=1, entanglement='full', skip_unentangled_qubits=False) var_form.compose(i_state, front=True) # Classical optimizer: # Analytic Quantum Gradient Descent (AQGD) (with Epochs) aqgd_max_iter = [10] + [1] * 100 aqgd_eta = [1e0] + [1.0 / k for k in range(1, 101)] aqgd_momentum = [0.5] + [0.5] * 100 optimizer = AQGD(maxiter=aqgd_max_iter, eta=aqgd_eta, momentum=aqgd_momentum, tol=1e-6, averaging=4) # Min Eigensolver: VQE solver = VQE(var_form=var_form, optimizer=optimizer, quantum_instance=quantum_instance, expectation=PauliExpectation()) me_gss = GroundStateEigensolver(f_t, solver) # BOPES sampler sampler = BOPESSampler(gss=me_gss) # absolute internuclear distance in Angstrom points = [0.7, 1.0, 1.3] results = sampler.sample(driver, points) points_run = results.points energies = results.energies np.testing.assert_array_almost_equal(points_run, [0.7, 1.0, 1.3]) np.testing.assert_array_almost_equal( energies, [-1.13618945, -1.10115033, -1.03518627], decimal=2)
def test_qubits_6_py_lih(self): """ qubits 6 py lih test """ state = HartreeFock(10, (1, 1), 'parity', True, [1, 2]) ref = QuantumCircuit(6) ref.x([0, 1]) self.assertEqual(state, ref)
def test_qubits_2_py_h2(self): """ qubits 2 py h2 test """ state = HartreeFock(4, 2, 'parity', True) ref = QuantumCircuit(2) ref.x(0) self.assertEqual(state, ref)