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 test_output(self): """ output test """ fermionic_transformation = \ FermionicTransformation(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=False, orbital_reduction=[]) qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation) self._validate_info(fermionic_transformation) self._validate_input_object(qubit_op)
def test_freeze_core(self): """ freeze core test """ fermionic_transformation = \ FermionicTransformation(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=False, freeze_core=True, orbital_reduction=[]) qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation, energy_shift=-7.7962196) self._validate_info(fermionic_transformation, num_particles=[1, 1], num_orbitals=10) self._validate_input_object(qubit_op, num_qubits=10, num_paulis=276)
def test_freeze_core(self): """ freeze core test -- Should be in effect a no-op for H2 """ fermionic_transformation = FermionicTransformation( transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=True, orbital_reduction=[]) qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation) self._validate_info(fermionic_transformation) self._validate_input_object(qubit_op)
def test_parity(self): """ parity test """ fermionic_transformation = \ FermionicTransformation(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=False, orbital_reduction=[]) qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation) self._validate_info(fermionic_transformation, actual_two_qubit_reduction=True) self._validate_input_object(qubit_op, num_qubits=10)
def test_particle_hole(self): """ particle hole test """ fermionic_transformation = FermionicTransformation( transformation=TransformationType.PARTICLE_HOLE, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=False, orbital_reduction=[]) qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation, ph_energy_shift=-1.83696799) self._validate_info(fermionic_transformation) self._validate_input_object(qubit_op)
def test_bravyi_kitaev(self): """ bravyi kitaev test """ fermionic_transformation = FermionicTransformation( transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.BRAVYI_KITAEV, two_qubit_reduction=False, freeze_core=False, orbital_reduction=[]) qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation) self._validate_info(fermionic_transformation) self._validate_input_object(qubit_op)
def test_potential_interface(self): """Tests potential interface.""" seed = 50 aqua_globals.random_seed = seed stretch = partial(Molecule.absolute_distance, atom_pair=(1, 0)) # H-H molecule near equilibrium geometry m = Molecule(geometry=[ ['H', [0., 0., 0.]], ['H', [1., 0., 0.]], ], degrees_of_freedom=[stretch], masses=[1.6735328E-27, 1.6735328E-27]) f_t = FermionicTransformation() driver = PySCFDriver(molecule=m) f_t.transform(driver) solver = NumPyMinimumEigensolver() me_gss = GroundStateEigensolver(f_t, solver) # Run BOPESSampler with exact eigensolution points = np.arange(0.45, 5.3, 0.3) sampler = BOPESSampler(gss=me_gss) res = sampler.sample(driver, points) # Testing Potential interface pot = MorsePotential(m) pot.fit(res.points, res.energies) np.testing.assert_array_almost_equal([pot.alpha, pot.r_0], [2.235, 0.720], decimal=3) np.testing.assert_array_almost_equal([pot.d_e, pot.m_shift], [0.2107, -1.1419], decimal=3)
def test_jordan_wigner_2q(self): """ jordan wigner 2q test """ fermionic_transformation = FermionicTransformation( transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=True, freeze_core=False, orbital_reduction=[]) qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation) # Reported effective 2 qubit reduction should be false self._validate_info(fermionic_transformation, actual_two_qubit_reduction=False) self._validate_input_object(qubit_op)
def test_freeze_core_all_reduction_ph(self): """ freeze core all reduction ph test """ fermionic_transformation = \ FermionicTransformation(transformation=TransformationType.PARTICLE_HOLE, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[-2, -1]) qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation, energy_shift=-7.7962196, ph_energy_shift=-1.05785247) self._validate_info(fermionic_transformation, num_particles=[1, 1], num_orbitals=6, actual_two_qubit_reduction=True) self._validate_input_object(qubit_op, num_qubits=4, num_paulis=52)
def test_freeze_core_all_reduction(self): """ freeze core all reduction test """ fermionic_transformation = \ FermionicTransformation(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[-3, -2]) qubit_op, _ = fermionic_transformation.transform(self.driver) self._validate_vars(fermionic_transformation, energy_shift=-7.7962196) self._validate_info(fermionic_transformation, num_particles=(1, 1), num_orbitals=6, actual_two_qubit_reduction=True) self._validate_input_object(qubit_op, num_qubits=4, num_paulis=100)
def test_orbital_reduction(self): """ orbital reduction test --- Remove virtual orbital just for test purposes (not sensible!) """ fermionic_transformation = FermionicTransformation( transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=False, orbital_reduction=[-1]) # get dummy aux operator qmolecule = self.driver.run() fer_op = FermionicOperator(h1=qmolecule.one_body_integrals, h2=qmolecule.two_body_integrals) dummy = fer_op.total_particle_number() expected = (I ^ I) - 0.5 * (I ^ Z) - 0.5 * (Z ^ I) qubit_op, aux_ops = fermionic_transformation.transform(self.driver, [dummy]) self._validate_vars(fermionic_transformation) self._validate_info(fermionic_transformation, num_orbitals=2) self._validate_input_object(qubit_op, num_qubits=2, num_paulis=4) # the first six aux_ops are added automatically, ours is the 7th one self.assertEqual(aux_ops[6], expected)
class TestUCCSDHartreeFock(QiskitChemistryTestCase): """Test for these aqua extensions.""" def setUp(self): super().setUp() try: self.molecule = "H 0.000000 0.000000 0.735000;H 0.000000 0.000000 0.000000" self.driver = PySCFDriver(atom=self.molecule, unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='631g') self.fermionic_transformation = \ FermionicTransformation(transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[]) self.qubit_op, _ = self.fermionic_transformation.transform(self.driver) self.reference_energy_pUCCD = -1.1434447924298028 self.reference_energy_UCCD0 = -1.1476045878481704 self.reference_energy_UCCD0full = -1.1515491334334347 # reference energy of UCCSD/VQE with tapering everywhere self.reference_energy_UCCSD = -1.1516142309717594 # reference energy of UCCSD/VQE when no tapering on excitations is used self.reference_energy_UCCSD_no_tap_exc = -1.1516142309717594 # excitations for succ self.reference_singlet_double_excitations = [[0, 1, 4, 5], [0, 1, 4, 6], [0, 1, 4, 7], [0, 2, 4, 6], [0, 2, 4, 7], [0, 3, 4, 7]] # groups for succ_full self.reference_singlet_groups = [[[0, 1, 4, 5]], [[0, 1, 4, 6], [0, 2, 4, 5]], [[0, 1, 4, 7], [0, 3, 4, 5]], [[0, 2, 4, 6]], [[0, 2, 4, 7], [0, 3, 4, 6]], [[0, 3, 4, 7]]] except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') 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_uccsd_hf_qUCCD0(self): """ singlet 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='succ', 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_UCCD0, places=6) def test_uccsd_hf_qUCCD0full(self): """ singlet full 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='succ_full', 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_UCCD0full, places=6) 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 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) @staticmethod def pop_el_when_matched(list1, list2): """ Compares if in list1 and list2 one of excitations is the same (regardless of permutations of its elements). When same excitation is found, it returns the 2 lists without that excitation . Args: list1 (list): list of excitations (e.g. [[0, 2, 4, 6], [0, 2, 4, 7]]) list2 (list): list of excitations Returns: list: list1 with one popped element if match was found list: list2 with one popped element if match was found """ counter = 0 for i, exc1 in enumerate(list1): for j, exc2 in enumerate(list2): for ind1 in exc1: for ind2 in exc2: if ind1 == ind2: counter += 1 if counter == len(exc1) and counter == len(exc2): list1.pop(i) list2.pop(j) break break return list1, list2 @staticmethod def excitation_lists_comparator(list1, list2): """ Compares if list1 and list2 contain same excitations (regardless of permutations of its elements). Only works provided all indices for an excitation are different. Args: list1 (list): list of excitations (e.g. [[0, 2, 4, 6], [0, 2, 4, 7]]) list2 (list): list of excitations Returns: bool: True or False, if list1 and list2 contain the same excitations """ if len(list1) != len(list2): return False number_el = len(list1) for _ in range(number_el): list1, list2 = TestUCCSDHartreeFock.pop_el_when_matched(list1, list2) return bool(len(list1) or len(list2) in [0]) @staticmethod def group_excitation_lists_comparator(glist1, glist2): """ Compares if list1 and list2 contain same excitations (regardless of permutations of its elements). Only works provided all indices for an excitation are different. Args: glist1 (list): list of excitations (e.g. [[0, 2, 4, 6], [0, 2, 4, 7]]) glist2 (list): list of excitations Returns: bool: True or False, if list1 and list2 contain the same excitations """ if len(glist1) != len(glist2): return False number_groups = len(glist1) counter = 0 for _, gr1 in enumerate(glist1): for _, gr2 in enumerate(glist2): res = TestUCCSDHartreeFock.excitation_lists_comparator(gr1, gr2) if res is True: counter += 1 return bool(counter == number_groups)
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)
class TestSymmetries(QiskitChemistryTestCase): """Test for symmetry processing.""" def setUp(self): super().setUp() try: self.driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.fermionic_transformation = FermionicTransformation( transformation=TransformationType.FULL, qubit_mapping=QubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=True, orbital_reduction=[], z2symmetry_reduction='auto') self.qubit_op, _ = self.fermionic_transformation.transform(self.driver) self.z2_symmetries = self.fermionic_transformation.molecule_info.pop( 'z2_symmetries') self.reference_energy = -7.882096489442 def test_symmetries(self): """ symmetries test """ labels = [symm.to_label() for symm in self.z2_symmetries.symmetries] self.assertSequenceEqual(labels, ['ZIZIZIZI', 'ZZIIZZII']) def test_sq_paulis(self): """ sq paulis test """ labels = [sq.to_label() for sq in self.z2_symmetries.sq_paulis] self.assertSequenceEqual(labels, ['IIIIIIXI', 'IIIIIXII']) def test_cliffords(self): """ clifford test """ self.assertEqual(2, len(self.z2_symmetries.cliffords)) def test_sq_list(self): """ sq list test """ self.assertSequenceEqual(self.z2_symmetries.sq_list, [1, 2]) 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.energy, self.reference_energy, places=6)
class TestMESGSCCalculation(QiskitChemistryTestCase): """ Test MinimumEigensovler ground state calculation """ def setUp(self): super().setUp() try: self.driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.reference_energy = -1.137306 self.transformation = FermionicTransformation( qubit_mapping=QubitMappingType.JORDAN_WIGNER) def test_npme(self): """ Test NumPyMinimumEigensolver """ solver = NumPyMinimumEigensolverFactory() calc = GroundStateEigensolver(self.transformation, solver) res = calc.solve(self.driver) self.assertAlmostEqual(res.energy, self.reference_energy, places=6) def test_vqe_uccsd(self): """ Test VQE UCCSD case """ solver = VQEUCCSDFactory( QuantumInstance(BasicAer.get_backend('statevector_simulator'))) calc = GroundStateEigensolver(self.transformation, solver) res = calc.solve(self.driver) self.assertAlmostEqual(res.energy, self.reference_energy, places=6) def _setup_evaluation_operators(self): # first we run a ground state calculation solver = VQEUCCSDFactory( QuantumInstance(BasicAer.get_backend('statevector_simulator'))) calc = GroundStateEigensolver(self.transformation, solver) res = calc.solve(self.driver) # now we decide that we want to evaluate another operator # for testing simplicity, we just use some pre-constructed auxiliary operators _, aux_ops = self.transformation.transform(self.driver) return calc, res, aux_ops def test_eval_op_single(self): """ Test evaluating a single additional operator """ calc, res, aux_ops = self._setup_evaluation_operators() # we filter the list because in this test we test a single operator evaluation add_aux_op = aux_ops[0][0] # now we have the ground state calculation evaluate it add_aux_op_res = calc.evaluate_operators(res.raw_result.eigenstate, add_aux_op) self.assertIsInstance(add_aux_op_res[0], complex) self.assertAlmostEqual(add_aux_op_res[0].real, 2, places=6) def test_eval_op_list(self): """ Test evaluating a list of additional operator """ calc, res, aux_ops = self._setup_evaluation_operators() # we filter the list because of simplicity expected_results = { 'number of particles': 2, 's^2': 0, 'magnetization': 0 } add_aux_op = aux_ops[0:3] # now we have the ground state calculation evaluate them add_aux_op_res = calc.evaluate_operators(res.raw_result.eigenstate, add_aux_op) self.assertIsInstance(add_aux_op_res, list) # in this list we require that the order of the results remains unchanged for idx, expected in enumerate(expected_results.values()): self.assertAlmostEqual(add_aux_op_res[idx][0].real, expected, places=6) def test_eval_op_dict(self): """ Test evaluating a dict of additional operator """ calc, res, aux_ops = self._setup_evaluation_operators() # we filter the list because of simplicity expected_results = { 'number of particles': 2, 's^2': 0, 'magnetization': 0 } add_aux_op = aux_ops[0:3] # now we convert it into a dictionary add_aux_op = dict(zip(expected_results.keys(), add_aux_op)) # now we have the ground state calculation evaluate them add_aux_op_res = calc.evaluate_operators(res.raw_result.eigenstate, add_aux_op) self.assertIsInstance(add_aux_op_res, dict) for name, expected in expected_results.items(): self.assertAlmostEqual(add_aux_op_res[name][0].real, expected, places=6)
class TestOOVQE(QiskitChemistryTestCase): """ Test OOVQE Ground State Calculation. """ def setUp(self): super().setUp() self.driver1 = HDF5Driver( hdf5_input=self.get_resource_path('test_oovqe_h4.hdf5')) self.driver2 = HDF5Driver( hdf5_input=self.get_resource_path('test_oovqe_lih.hdf5')) self.driver3 = HDF5Driver( hdf5_input=self.get_resource_path('test_oovqe_h4_uhf.hdf5')) self.energy1_rotation = -3.0104 self.energy1 = -2.77 # energy of the VQE with pUCCD ansatz and LBFGSB optimizer self.energy2 = -7.70 self.energy3 = -2.50 self.initial_point1 = [ 0.039374, -0.47225463, -0.61891996, 0.02598386, 0.79045546, -0.04134567, 0.04944946, -0.02971617, -0.00374005, 0.77542149 ] self.seed = 50 self.optimizer = COBYLA(maxiter=1) self.transformation1 = \ FermionicTransformation(qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False) self.transformation2 = \ FermionicTransformation(qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=True) self.quantum_instance = QuantumInstance( BasicAer.get_backend('statevector_simulator'), shots=1, seed_simulator=self.seed, seed_transpiler=self.seed) def test_orbital_rotations(self): """ Test that orbital rotations are performed correctly. """ optimizer = COBYLA(maxiter=1) solver = VQEUCCSDFactory(quantum_instance=self.quantum_instance, optimizer=optimizer, excitation_type='d', same_spin_doubles=False, method_doubles='pucc') calc = OrbitalOptimizationVQE(self.transformation1, solver, iterative_oo=False, initial_point=self.initial_point1) algo_result = calc.solve(self.driver1) self.assertAlmostEqual(algo_result.computed_electronic_energy, self.energy1_rotation, 4) def test_oovqe(self): """ Test the simultaneous optimization of orbitals and ansatz parameters with OOVQE using BasicAer's statevector_simulator. """ optimizer = COBYLA(maxiter=3, rhobeg=0.01) solver = VQEUCCSDFactory(quantum_instance=self.quantum_instance, optimizer=optimizer, excitation_type='d', same_spin_doubles=False, method_doubles='pucc') calc = OrbitalOptimizationVQE(self.transformation1, solver, iterative_oo=False, initial_point=self.initial_point1) algo_result = calc.solve(self.driver1) self.assertLessEqual(algo_result.computed_electronic_energy, self.energy1, 4) def test_iterative_oovqe(self): """ Test the iterative OOVQE using BasicAer's statevector_simulator. """ optimizer = COBYLA(maxiter=2, rhobeg=0.01) solver = VQEUCCSDFactory(quantum_instance=self.quantum_instance, optimizer=optimizer, excitation_type='d', same_spin_doubles=False, method_doubles='pucc') calc = OrbitalOptimizationVQE(self.transformation1, solver, iterative_oo=True, initial_point=self.initial_point1, iterative_oo_iterations=2) algo_result = calc.solve(self.driver1) self.assertLessEqual(algo_result.computed_electronic_energy, self.energy1) def test_oovqe_with_frozen_core(self): """ Test the OOVQE with frozen core approximation. """ optimizer = COBYLA(maxiter=2, rhobeg=1) solver = VQEUCCSDFactory(quantum_instance=self.quantum_instance, optimizer=optimizer, excitation_type='d', same_spin_doubles=False, method_doubles='pucc') calc = OrbitalOptimizationVQE(self.transformation2, solver, iterative_oo=False) algo_result = calc.solve(self.driver2) self.assertLessEqual( algo_result.computed_electronic_energy + self.transformation2._energy_shift + self.transformation2._nuclear_repulsion_energy, self.energy2) def test_oovqe_with_unrestricted_hf(self): """ Test the OOVQE with unrestricted HF method. """ optimizer = COBYLA(maxiter=2, rhobeg=0.01) solver = VQEUCCSDFactory(quantum_instance=self.quantum_instance, optimizer=optimizer, excitation_type='d', same_spin_doubles=False, method_doubles='pucc') calc = OrbitalOptimizationVQE(self.transformation1, solver, iterative_oo=False) algo_result = calc.solve(self.driver3) self.assertLessEqual(algo_result.computed_electronic_energy, self.energy3) def test_oovqe_with_unsupported_varform(self): """ Test the OOVQE with unsupported varform. """ optimizer = COBYLA(maxiter=2, rhobeg=0.01) solver = VQE(var_form=RealAmplitudes(), optimizer=optimizer, quantum_instance=self.quantum_instance) calc = OrbitalOptimizationVQE(self.transformation1, solver, iterative_oo=False) with self.assertRaises(AquaError): calc.solve(self.driver3) def test_oovqe_with_vqe_uccsd(self): """ Test the OOVQE with VQE + UCCSD instead of factory. """ optimizer = COBYLA(maxiter=3, rhobeg=0.01) solver_factory = VQEUCCSDFactory( quantum_instance=self.quantum_instance, optimizer=optimizer, excitation_type='d', same_spin_doubles=False, method_doubles='pucc') self.transformation1.transform(self.driver1) solver = solver_factory.get_solver(self.transformation1) calc = OrbitalOptimizationVQE(self.transformation1, solver, iterative_oo=False, initial_point=self.initial_point1) algo_result = calc.solve(self.driver1) self.assertLessEqual(algo_result.computed_electronic_energy, self.energy1, 4)
class TestGroundStateEigensolver(QiskitChemistryTestCase): """ Test GroundStateEigensolver """ def setUp(self): super().setUp() try: self.driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitChemistryError: self.skipTest('PYSCF driver does not appear to be installed') self.reference_energy = -1.137306 self.transformation = FermionicTransformation( qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER) def test_npme(self): """ Test NumPyMinimumEigensolver """ solver = NumPyMinimumEigensolverFactory() calc = GroundStateEigensolver(self.transformation, solver) res = calc.solve(self.driver) self.assertAlmostEqual(res.total_energies[0], self.reference_energy, places=6) def test_npme_with_default_filter(self): """ Test NumPyMinimumEigensolver with default filter """ solver = NumPyMinimumEigensolverFactory( use_default_filter_criterion=True) calc = GroundStateEigensolver(self.transformation, solver) res = calc.solve(self.driver) self.assertAlmostEqual(res.total_energies[0], self.reference_energy, places=6) def test_vqe_uccsd(self): """ Test VQE UCCSD case """ solver = VQEUCCSDFactory( QuantumInstance(BasicAer.get_backend('statevector_simulator'))) calc = GroundStateEigensolver(self.transformation, solver) res = calc.solve(self.driver) self.assertAlmostEqual(res.total_energies[0], self.reference_energy, places=6) def test_aux_ops_reusability(self): """ Test that the auxiliary operators can be reused """ # Regression test against #1475 solver = NumPyMinimumEigensolverFactory() calc = GroundStateEigensolver(self.transformation, solver) modes = 4 h_1 = np.eye(modes, dtype=np.complex) h_2 = np.zeros((modes, modes, modes, modes)) aux_ops = [FermionicOperator(h_1, h_2)] aux_ops_copy = copy.deepcopy(aux_ops) _ = calc.solve(self.driver, aux_ops) assert all([a == b for a, b in zip(aux_ops, aux_ops_copy)]) def _setup_evaluation_operators(self): # first we run a ground state calculation solver = VQEUCCSDFactory( QuantumInstance(BasicAer.get_backend('statevector_simulator'))) calc = GroundStateEigensolver(self.transformation, solver) res = calc.solve(self.driver) # now we decide that we want to evaluate another operator # for testing simplicity, we just use some pre-constructed auxiliary operators _, aux_ops = self.transformation.transform(self.driver) return calc, res, aux_ops def test_eval_op_single(self): """ Test evaluating a single additional operator """ calc, res, aux_ops = self._setup_evaluation_operators() # we filter the list because in this test we test a single operator evaluation add_aux_op = aux_ops[0][0] # now we have the ground state calculation evaluate it add_aux_op_res = calc.evaluate_operators(res.raw_result.eigenstate, add_aux_op) self.assertIsInstance(add_aux_op_res[0], complex) self.assertAlmostEqual(add_aux_op_res[0].real, 2, places=6) def test_eval_op_single_none(self): """ Test evaluating a single `None` operator """ calc, res, _ = self._setup_evaluation_operators() # we filter the list because in this test we test a single operator evaluation add_aux_op = None # now we have the ground state calculation evaluate it add_aux_op_res = calc.evaluate_operators(res.raw_result.eigenstate, add_aux_op) self.assertIsNone(add_aux_op_res) def test_eval_op_list(self): """ Test evaluating a list of additional operators """ calc, res, aux_ops = self._setup_evaluation_operators() # we filter the list because of simplicity expected_results = { 'number of particles': 2, 's^2': 0, 'magnetization': 0 } add_aux_op = aux_ops[0:3] # now we have the ground state calculation evaluate them add_aux_op_res = calc.evaluate_operators(res.raw_result.eigenstate, add_aux_op) self.assertIsInstance(add_aux_op_res, list) # in this list we require that the order of the results remains unchanged for idx, expected in enumerate(expected_results.values()): self.assertAlmostEqual(add_aux_op_res[idx][0].real, expected, places=6) def test_eval_op_list_none(self): """ Test evaluating a list of additional operators incl. `None` """ calc, res, aux_ops = self._setup_evaluation_operators() # we filter the list because of simplicity expected_results = { 'number of particles': 2, 's^2': 0, 'magnetization': 0 } add_aux_op = aux_ops[0:3] + [None] # now we have the ground state calculation evaluate them add_aux_op_res = calc.evaluate_operators(res.raw_result.eigenstate, add_aux_op) self.assertIsInstance(add_aux_op_res, list) # in this list we require that the order of the results remains unchanged for idx, expected in enumerate(expected_results.values()): self.assertAlmostEqual(add_aux_op_res[idx][0].real, expected, places=6) self.assertIsNone(add_aux_op_res[-1]) def test_eval_op_dict(self): """ Test evaluating a dict of additional operators """ calc, res, aux_ops = self._setup_evaluation_operators() # we filter the list because of simplicity expected_results = { 'number of particles': 2, 's^2': 0, 'magnetization': 0 } add_aux_op = aux_ops[0:3] # now we convert it into a dictionary add_aux_op = dict(zip(expected_results.keys(), add_aux_op)) # now we have the ground state calculation evaluate them add_aux_op_res = calc.evaluate_operators(res.raw_result.eigenstate, add_aux_op) self.assertIsInstance(add_aux_op_res, dict) for name, expected in expected_results.items(): self.assertAlmostEqual(add_aux_op_res[name][0].real, expected, places=6) def test_eval_op_dict_none(self): """ Test evaluating a dict of additional operators incl. `None` """ calc, res, aux_ops = self._setup_evaluation_operators() # we filter the list because of simplicity expected_results = { 'number of particles': 2, 's^2': 0, 'magnetization': 0 } add_aux_op = aux_ops[0:3] # now we convert it into a dictionary add_aux_op = dict(zip(expected_results.keys(), add_aux_op)) add_aux_op['None'] = None # now we have the ground state calculation evaluate them add_aux_op_res = calc.evaluate_operators(res.raw_result.eigenstate, add_aux_op) self.assertIsInstance(add_aux_op_res, dict) for name, expected in expected_results.items(): self.assertAlmostEqual(add_aux_op_res[name][0].real, expected, places=6) self.assertIsNone(add_aux_op_res['None'])