def test_excitation_preserving(self): """Test the excitation preserving wavefunction on a chemistry example.""" driver = HDF5Driver( self.get_resource_path('test_driver_hdf5.hdf5', 'drivers/hdf5d')) fermionic_transformation = \ FermionicTransformation(qubit_mapping=FermionicQubitMappingType.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=algorithm_globals.random_seed, seed_transpiler=algorithm_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() self.driver1 = HDF5Driver(hdf5_input=self.get_resource_path( 'test_oovqe_h4.hdf5', 'algorithms/ground_state_solvers')) self.driver2 = HDF5Driver(hdf5_input=self.get_resource_path( 'test_oovqe_lih.hdf5', 'algorithms/ground_state_solvers')) self.driver3 = HDF5Driver(hdf5_input=self.get_resource_path( 'test_oovqe_h4_uhf.hdf5', 'algorithms/ground_state_solvers')) 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 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=FermionicTransformationType.FULL, qubit_mapping=FermionicQubitMappingType.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 QiskitNatureError: self.skipTest('PYSCF driver does not appear to be installed')
def test_potential_interface(self): """Tests potential interface.""" seed = 50 algorithm_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 setUp(self): super().setUp() self.skipTest("Skip test until refactored.") self.reference_energy = -1.1373060356951838 self.seed = 700 algorithm_globals.random_seed = self.seed self.driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5', 'drivers/hdf5d')) fermionic_transformation = \ FermionicTransformation(qubit_mapping=FermionicQubitMappingType.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 setUp(self): super().setUp() driver = HDF5Driver(hdf5_input=self.get_resource_path('test_driver_hdf5.hdf5', 'drivers/hdf5d')) fermionic_transformation = \ FermionicTransformation(transformation=FermionicTransformationType.FULL, qubit_mapping=FermionicQubitMappingType.PARITY, two_qubit_reduction=True, freeze_core=False, orbital_reduction=[]) self.qubit_op, self.aux_ops = fermionic_transformation.transform(driver) self.reference_energy = -1.857275027031588
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 QiskitNatureError: 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_vqe_adapt(self): """ AdaptVQE test """ try: # pylint: disable=import-outside-toplevel from qiskit import Aer backend = Aer.get_backend('statevector_simulator') except ImportError as ex: # pylint: disable=broad-except self.skipTest( "Aer doesn't appear to be installed. Error: '{}'".format( str(ex))) return class CustomFactory(VQEUCCSDFactory): """A custom MESFactory""" def get_solver(self, transformation): num_orbitals = transformation.molecule_info['num_orbitals'] num_particles = transformation.molecule_info['num_particles'] initial_state = HartreeFock(num_orbitals, num_particles) var_form = UCCSD(num_orbitals, num_particles, initial_state=initial_state) vqe = VQE(var_form=var_form, quantum_instance=self._quantum_instance, optimizer=L_BFGS_B()) return vqe algorithm = AdaptVQE(FermionicTransformation(), solver=CustomFactory(QuantumInstance(backend)), threshold=0.00001, delta=0.1, max_iterations=1) result = algorithm.solve(driver=self.driver) self.assertEqual(result.num_iterations, 1) self.assertEqual(result.finishing_criterion, 'Maximum number of iterations reached') algorithm = AdaptVQE(FermionicTransformation(), solver=CustomFactory(QuantumInstance(backend)), threshold=0.00001, delta=0.1) result = algorithm.solve(driver=self.driver) self.assertAlmostEqual(result.electronic_energies[0], -1.85727503, places=2) self.assertEqual(result.num_iterations, 2) self.assertAlmostEqual(result.final_max_gradient, 0.0, places=5) self.assertEqual(result.finishing_criterion, 'Threshold converged')
def test_uccsd_hf_qUCCSD(self): """ uccsd tapering test using all double excitations """ fermionic_transformation = FermionicTransformation( transformation=FermionicTransformationType.FULL, qubit_mapping=FermionicQubitMappingType.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 setUp(self): super().setUp() try: self.driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.735', unit=UnitsType.ANGSTROM, basis='sto3g') except QiskitNatureError: self.skipTest('PYSCF driver does not appear to be installed') return self.expected = -1.85727503 self.transformation = FermionicTransformation()
def _run_driver(driver, transformation=FermionicTransformationType.FULL, qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False, freeze_core=True): fermionic_transformation = \ FermionicTransformation(transformation=transformation, qubit_mapping=qubit_mapping, two_qubit_reduction=two_qubit_reduction, freeze_core=freeze_core, orbital_reduction=[]) solver = NumPyMinimumEigensolver() gsc = GroundStateEigensolver(fermionic_transformation, solver) result = gsc.solve(driver) return result
def setUp(self): super().setUp() algorithm_globals.random_seed = 8 try: self.driver = PySCFDriver(atom='H .0 .0 .0; H .0 .0 0.75', unit=UnitsType.ANGSTROM, charge=0, spin=0, basis='sto3g') except QiskitNatureError: self.skipTest('PYSCF driver does not appear to be installed') self.reference_energies = [-1.8427016, -1.8427016 + 0.5943372, -1.8427016 + 0.95788352, -1.8427016 + 1.5969296] self.transformation = \ FermionicTransformation(qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER) solver = NumPyEigensolver() self.ref = solver self.quantum_instance = QuantumInstance(BasicAer.get_backend('statevector_simulator'), seed_transpiler=90, seed_simulator=12)
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 QiskitNatureError: self.skipTest('PYSCF driver does not appear to be installed') self.reference_energy = -1.137306 self.transformation = \ FermionicTransformation(qubit_mapping=FermionicQubitMappingType.JORDAN_WIGNER) self.seed = 50 self.quantum_instance = QuantumInstance( BasicAer.get_backend('statevector_simulator'), shots=1, seed_simulator=self.seed, seed_transpiler=self.seed) self._vqe_uccsd_factory = VQEUCCSDFactory(self.quantum_instance)
class TestGroundStateEigensolver(QiskitNatureTestCase): """ 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 QiskitNatureError: 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=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'])
class TestUCCSDHartreeFock(QiskitNatureTestCase): """Test for these 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=FermionicTransformationType.FULL, qubit_mapping=FermionicQubitMappingType.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 QiskitNatureError: 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=FermionicTransformationType.FULL, qubit_mapping=FermionicQubitMappingType.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 algorithm_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 TestOOVQE(QiskitNatureTestCase): """ Test OOVQE Ground State Calculation. """ def setUp(self): super().setUp() self.driver1 = HDF5Driver(hdf5_input=self.get_resource_path( 'test_oovqe_h4.hdf5', 'algorithms/ground_state_solvers')) self.driver2 = HDF5Driver(hdf5_input=self.get_resource_path( 'test_oovqe_lih.hdf5', 'algorithms/ground_state_solvers')) self.driver3 = HDF5Driver(hdf5_input=self.get_resource_path( 'test_oovqe_h4_uhf.hdf5', 'algorithms/ground_state_solvers')) 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(QiskitNatureError): 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)