Beispiel #1
0
    def test_mapping_for_single_op(self):
        """Test for single register operator."""
        with self.subTest("test +"):
            op = FermionicOp("+")
            expected = PauliSumOp.from_list([("X", 0.5), ("Y", -0.5j)])
            self.assertEqual(ParityMapper().map(op), expected)

        with self.subTest("test -"):
            op = FermionicOp("-")
            expected = PauliSumOp.from_list([("X", 0.5), ("Y", 0.5j)])
            self.assertEqual(ParityMapper().map(op), expected)

        with self.subTest("test N"):
            op = FermionicOp("N")
            expected = PauliSumOp.from_list([("I", 0.5), ("Z", -0.5)])
            self.assertEqual(ParityMapper().map(op), expected)

        with self.subTest("test E"):
            op = FermionicOp("E")
            expected = PauliSumOp.from_list([("I", 0.5), ("Z", 0.5)])
            self.assertEqual(ParityMapper().map(op), expected)

        with self.subTest("test I"):
            op = FermionicOp("I")
            expected = PauliSumOp.from_list([("I", 1)])
            self.assertEqual(ParityMapper().map(op), expected)
Beispiel #2
0
    def test_mapping(self):
        """Test mapping to qubit operator"""
        driver = HDF5Driver(hdf5_input=self.get_resource_path(
            "test_driver_hdf5.hdf5", "drivers/second_quantization/hdf5d"))
        driver_result = driver.run()
        fermionic_op = driver_result.second_q_ops()["ElectronicEnergy"]
        mapper = ParityMapper()
        qubit_op = mapper.map(fermionic_op)

        # Note: The PauliSumOp equals, as used in the test below, use the equals of the
        #       SparsePauliOp which in turn uses np.allclose() to determine equality of
        #       coeffs. So the reference operator above will be matched on that basis so
        #       we don't need to worry about tiny precision changes for any reason.

        self.assertEqual(qubit_op, TestParityMapper.REF_H2)
    def test_mapping(self):
        """ Test mapping to qubit operator """
        driver = HDF5Driver(hdf5_input=self.get_resource_path('test_driver_hdf5.hdf5',
                                                              'drivers/hdf5d'))
        q_molecule = driver.run()
        fermionic_op = fermionic_op_builder._build_fermionic_op(q_molecule)
        mapper = ParityMapper()
        qubit_op = mapper.map(fermionic_op)

        # Note: The PauliSumOp equals, as used in the test below, use the equals of the
        #       SparsePauliOp which in turn uses np.allclose() to determine equality of
        #       coeffs. So the reference operator above will be matched on that basis so
        #       we don't need to worry about tiny precision changes for any reason.

        self.assertEqual(qubit_op, TestParityMapper.REF_H2)
Beispiel #4
0
    def test_two_qubit_reduction(self):
        """ Test mapping to qubit operator with two qubit reduction """
        mapper = ParityMapper()
        qubit_conv = QubitConverter(mapper, two_qubit_reduction=True)

        with self.subTest('Two qubit reduction ignored as no num particles given'):
            qubit_op = qubit_conv.convert(self.h2_op)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_PARITY)
            self.assertIsNone(qubit_conv.num_particles)

        with self.subTest('Two qubit reduction, num particles given'):
            qubit_op = qubit_conv.convert(self.h2_op, self.num_particles)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_PARITY_2Q_REDUCED)
            self.assertEqual(qubit_conv.num_particles, self.num_particles)

        with self.subTest('convert_match()'):
            qubit_op = qubit_conv.convert_match(self.h2_op)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_PARITY_2Q_REDUCED)
            self.assertEqual(qubit_conv.num_particles, self.num_particles)

        with self.subTest('State is reset (Num particles lost)'):
            qubit_op = qubit_conv.convert(self.h2_op)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_PARITY)
            self.assertIsNone(qubit_conv.num_particles)

        with self.subTest('Num particles given again'):
            qubit_op = qubit_conv.convert(self.h2_op, self.num_particles)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_PARITY_2Q_REDUCED)

        with self.subTest('Set for no two qubit reduction'):
            qubit_conv.two_qubit_reduction = False
            self.assertFalse(qubit_conv.two_qubit_reduction)
            qubit_op = qubit_conv.convert(self.h2_op)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_PARITY)
Beispiel #5
0
    def test_h2_bopes_sampler(self):
        """Test BOPES Sampler on H2"""
        # Molecule
        dof = partial(Molecule.absolute_distance, atom_pair=(1, 0))
        m = Molecule(
            geometry=[["H", [0.0, 0.0, 1.0]], ["H", [0.0, 0.45, 1.0]]],
            degrees_of_freedom=[dof],
        )

        mapper = ParityMapper()
        converter = QubitConverter(mapper=mapper, two_qubit_reduction=True)

        driver = ElectronicStructureMoleculeDriver(
            m, driver_type=ElectronicStructureDriverType.PYSCF)
        problem = ElectronicStructureProblem(driver)

        solver = NumPyMinimumEigensolver()
        me_gss = GroundStateEigensolver(converter, solver)

        # BOPES sampler
        sampler = BOPESSampler(gss=me_gss)

        # absolute internuclear distance in Angstrom
        points = [0.7, 1.0, 1.3]
        results = sampler.sample(problem, 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 setUp(self):
        super().setUp()
        self.driver = PySCFDriver(atom='H 0 0 0.735; H 0 0 0', basis='631g')

        self.qubit_converter = QubitConverter(ParityMapper(), two_qubit_reduction=True)

        self.electronic_structure_problem = ElectronicStructureProblem(self.driver,
                                                                       [FreezeCoreTransformer()])

        self.num_spin_orbitals = 8
        self.num_particles = (1, 1)

        # because we create the initial state and ansatzes early, we need to ensure the qubit
        # converter already ran such that convert_match works as expected
        _ = self.qubit_converter.convert(self.electronic_structure_problem.second_q_ops()[0],
                                         self.num_particles)

        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]]]
    def test_two_qubit_reduction_and_z2_symmetry(self):
        """Test mapping to qubit operator with z2 symmetry tapering and two qubit reduction"""
        z2_sector = [-1]

        def cb_finder(z2_symmetries: Z2Symmetries,
                      converter: QubitConverter) -> Optional[List[int]]:
            return z2_sector if not z2_symmetries.is_empty() else None

        mapper = ParityMapper()
        qubit_conv = QubitConverter(mapper,
                                    two_qubit_reduction=True,
                                    z2symmetry_reduction="auto")
        qubit_op = qubit_conv.convert(self.h2_op,
                                      self.num_particles,
                                      sector_locator=cb_finder)
        self.assertEqual(qubit_op,
                         TestQubitConverter.REF_H2_PARITY_2Q_REDUCED_TAPER)
        self.assertEqual(qubit_conv.num_particles, self.num_particles)
        self.assertListEqual(qubit_conv.z2symmetries.tapering_values,
                             z2_sector)

        with self.subTest("convert_match()"):
            qubit_op = qubit_conv.convert_match(self.h2_op)
            self.assertEqual(qubit_op,
                             TestQubitConverter.REF_H2_PARITY_2Q_REDUCED_TAPER)
            self.assertEqual(qubit_conv.num_particles, self.num_particles)
            self.assertListEqual(qubit_conv.z2symmetries.tapering_values,
                                 z2_sector)

        with self.subTest("Change setting"):
            qubit_conv.z2symmetry_reduction = [1]
            qubit_op = qubit_conv.convert(self.h2_op, self.num_particles)
            self.assertNotEqual(
                qubit_op, TestQubitConverter.REF_H2_PARITY_2Q_REDUCED_TAPER)
            qubit_conv.z2symmetry_reduction = [-1]
            qubit_op = qubit_conv.convert(self.h2_op, self.num_particles)
            self.assertEqual(qubit_op,
                             TestQubitConverter.REF_H2_PARITY_2Q_REDUCED_TAPER)

        with self.subTest("Specify sector upfront"):
            qubit_conv = QubitConverter(mapper,
                                        two_qubit_reduction=True,
                                        z2symmetry_reduction=z2_sector)
            qubit_op = qubit_conv.convert(self.h2_op, self.num_particles)
            self.assertEqual(qubit_op,
                             TestQubitConverter.REF_H2_PARITY_2Q_REDUCED_TAPER)

        with self.subTest("Specify sector upfront, but invalid content"):
            with self.assertRaises(ValueError):
                _ = QubitConverter(mapper,
                                   two_qubit_reduction=True,
                                   z2symmetry_reduction=[5])

        with self.subTest("Specify sector upfront, but invalid length"):
            qubit_conv = QubitConverter(mapper,
                                        two_qubit_reduction=True,
                                        z2symmetry_reduction=[-1, 1])
            with self.assertRaises(QiskitNatureError):
                _ = qubit_conv.convert(self.h2_op, self.num_particles)
 def test_vqe_mes_parity_auto(self):
     """Test VQEUCCSDFactory with QEOM + Parity mapping + auto symmetry"""
     self.skipTest(
         "Temporarily skip test until the changes done by "
         "https://github.com/Qiskit/qiskit-terra/pull/7551 are handled properly."
     )
     converter = QubitConverter(ParityMapper(), z2symmetry_reduction="auto")
     self._solve_with_vqe_mes(converter)
 def test_oh_uhf_parity(self):
     """ oh uhf parity test """
     driver = PySCFDriver(atom=self.o_h, unit=UnitsType.ANGSTROM,
                          charge=0, spin=1, basis='sto-3g',
                          hf_method=HFMethodType.UHF)
     result = self._run_driver(driver,
                               converter=QubitConverter(ParityMapper()))
     self._assert_energy_and_dipole(result, 'oh')
Beispiel #10
0
 def test_qubits_2_py_h2(self):
     """ qubits 2 py h2 test """
     num_particles = (1, 1)
     converter = QubitConverter(ParityMapper(), two_qubit_reduction=True)
     converter.force_match(num_particles=num_particles)
     state = HartreeFock(4, num_particles, converter)
     ref = QuantumCircuit(2)
     ref.x(0)
     self.assertEqual(state, ref)
 def test_lih_rhf_parity(self):
     """ lih rhf parity test """
     driver = PySCFDriver(atom=self.lih, unit=UnitsType.ANGSTROM,
                          charge=0, spin=0, basis='sto-3g',
                          hf_method=HFMethodType.RHF)
     result = self._run_driver(driver,
                               converter=QubitConverter(ParityMapper()),
                               transformers=[FreezeCoreTransformer()])
     self._assert_energy_and_dipole(result, 'lih')
 def test_oh_rohf_parity_2q(self):
     """ oh rohf parity 2q test """
     driver = PySCFDriver(atom=self.o_h, unit=UnitsType.ANGSTROM,
                          charge=0, spin=1, basis='sto-3g',
                          hf_method=HFMethodType.ROHF)
     result = self._run_driver(driver,
                               converter=QubitConverter(ParityMapper(),
                                                        two_qubit_reduction=True))
     self._assert_energy_and_dipole(result, 'oh')
Beispiel #13
0
 def test_hf_bitstring_mapped(self):
     """Mapped bitstring test for water"""
     # Original driver config when creating operator that resulted in symmetries coded
     # below. The sector [1, -1] is the correct ground sector.
     # PySCFDriver(
     #    atom="O 0.0000 0.0000 0.1173; H 0.0000 0.07572 -0.4692;H 0.0000 -0.07572 -0.4692",
     #    unit=UnitsType.ANGSTROM,
     #    charge=0,
     #    spin=0,
     #    basis='sto-3g',
     #    hf_method=HFMethodType.RHF)
     num_spin_orbitals = 14
     num_particles = (5, 5)
     converter = QubitConverter(ParityMapper(), two_qubit_reduction=True)
     z2symmetries = Z2Symmetries(
         symmetries=[Pauli("IZZIIIIZZIII"),
                     Pauli("ZZIZIIZZIZII")],
         sq_paulis=[Pauli("IIIIIIIIXIII"),
                    Pauli("IIIIIIIIIXII")],
         sq_list=[3, 2],
         tapering_values=[1, -1],
     )
     with self.subTest("Matched bitsring creation"):
         converter.force_match(num_particles=num_particles,
                               z2symmetries=z2symmetries)
         bitstr = hartree_fock_bitstring_mapped(
             num_spin_orbitals=num_spin_orbitals,
             num_particles=num_particles,
             qubit_converter=converter,
         )
         ref_matched = [
             True, False, True, True, False, True, False, True, False, False
         ]
         self.assertListEqual(bitstr, ref_matched)
     with self.subTest("Bitsring creation with no tapering"):
         bitstr = hartree_fock_bitstring_mapped(
             num_spin_orbitals=num_spin_orbitals,
             num_particles=num_particles,
             qubit_converter=converter,
             match_convert=False,
         )
         ref_notaper = [
             True,
             False,
             True,
             False,
             True,
             True,
             False,
             True,
             False,
             True,
             False,
             False,
         ]
         self.assertListEqual(bitstr, ref_notaper)
    def test_two_qubit_reduction(self):
        """Test mapping to qubit operator with two qubit reduction"""
        mapper = ParityMapper()
        qubit_conv = QubitConverter(mapper, two_qubit_reduction=True)

        with self.subTest(
                "Two qubit reduction ignored as no num particles given"):
            qubit_op = qubit_conv.convert(self.h2_op)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_PARITY)
            self.assertIsNone(qubit_conv.num_particles)

        with self.subTest("Two qubit reduction, num particles given"):
            qubit_op = qubit_conv.convert(self.h2_op, self.num_particles)
            self.assertEqual(qubit_op,
                             TestQubitConverter.REF_H2_PARITY_2Q_REDUCED)
            self.assertEqual(qubit_conv.num_particles, self.num_particles)

        with self.subTest("convert_match()"):
            qubit_op = qubit_conv.convert_match(self.h2_op)
            self.assertEqual(qubit_op,
                             TestQubitConverter.REF_H2_PARITY_2Q_REDUCED)
            self.assertEqual(qubit_conv.num_particles, self.num_particles)

        with self.subTest("State is reset (Num particles lost)"):
            qubit_op = qubit_conv.convert(self.h2_op)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_PARITY)
            self.assertIsNone(qubit_conv.num_particles)

        with self.subTest("Num particles given again"):
            qubit_op = qubit_conv.convert(self.h2_op, self.num_particles)
            self.assertEqual(qubit_op,
                             TestQubitConverter.REF_H2_PARITY_2Q_REDUCED)

        with self.subTest("Set for no two qubit reduction"):
            qubit_conv.two_qubit_reduction = False
            self.assertFalse(qubit_conv.two_qubit_reduction)
            qubit_op = qubit_conv.convert(self.h2_op)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_PARITY)

        # Regression test against https://github.com/Qiskit/qiskit-nature/issues/271
        with self.subTest(
                "Two qubit reduction skipped when operator too small"):
            qubit_conv.two_qubit_reduction = True
            small_op = FermionicOp([("N_0", 1.0), ("E_1", 1.0)],
                                   register_length=2,
                                   display_format="sparse")
            expected_op = 1.0 * (I ^ I) - 0.5 * (I ^ Z) + 0.5 * (Z ^ Z)
            with contextlib.redirect_stderr(io.StringIO()) as out:
                qubit_op = qubit_conv.convert(small_op,
                                              num_particles=self.num_particles)
            self.assertEqual(qubit_op, expected_op)
            self.assertTrue(out.getvalue().strip().startswith(
                "The original qubit operator only contains 2 qubits! "
                "Skipping the requested two-qubit reduction!"))
Beispiel #15
0
    def setUp(self):
        super().setUp()

        self.driver = PySCFDriver(atom="H .0 .0 .0; H .0 .0 0.735",
                                  unit=UnitsType.ANGSTROM,
                                  basis="sto3g")

        self.problem = ElectronicStructureProblem(self.driver)

        self.expected = -1.85727503

        self.qubit_converter = QubitConverter(ParityMapper())
 def test_oh_rohf_parity(self):
     """oh rohf parity test"""
     driver = PySCFDriver(
         atom=self.o_h,
         unit=UnitsType.ANGSTROM,
         charge=0,
         spin=1,
         basis="sto-3g",
         method=MethodType.ROHF,
     )
     result = self._run_driver(driver,
                               converter=QubitConverter(ParityMapper()))
     self._assert_energy_and_dipole(result, "oh")
Beispiel #17
0
    def setUp(self):
        super().setUp()
        algorithm_globals.random_seed = 42

        driver = HDF5Driver(hdf5_input=self.get_resource_path('test_driver_hdf5.hdf5',
                                                              'drivers/hdf5d'))
        problem = ElectronicStructureProblem(driver)
        second_q_ops = problem.second_q_ops()
        converter = QubitConverter(mapper=ParityMapper(), two_qubit_reduction=True)
        num_particles = (problem.molecule_data_transformed.num_alpha,
                         problem.molecule_data_transformed.num_beta)
        self.qubit_op = converter.convert(second_q_ops[0], num_particles)
        self.aux_ops = converter.convert_match(second_q_ops[1:])
        self.reference_energy = -1.857275027031588
 def test_lih_rhf_parity_2q(self):
     """lih rhf parity 2q test"""
     driver = PySCFDriver(
         atom=self.lih,
         unit=UnitsType.ANGSTROM,
         charge=0,
         spin=0,
         basis="sto-3g",
         method=MethodType.RHF,
     )
     result = self._run_driver(
         driver,
         converter=QubitConverter(ParityMapper(), two_qubit_reduction=True),
         transformers=[FreezeCoreTransformer()],
     )
     self._assert_energy_and_dipole(result, "lih")
Beispiel #19
0
    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.problem = ElectronicStructureProblem(self.driver)

        self.expected = -1.85727503

        self.qubit_converter = QubitConverter(ParityMapper())
Beispiel #20
0
    def test_h2_bopes_sampler_excited_eigensolver(self):
        """Test BOPES Sampler on H2"""
        # Molecule
        dof = partial(Molecule.absolute_distance, atom_pair=(1, 0))
        m = Molecule(
            geometry=[["H", [0.0, 0.0, 1.0]], ["H", [0.0, 0.45, 1.0]]],
            degrees_of_freedom=[dof],
        )

        mapper = ParityMapper()
        converter = QubitConverter(mapper=mapper)

        driver = ElectronicStructureMoleculeDriver(
            m, driver_type=ElectronicStructureDriverType.PYSCF)
        problem = ElectronicStructureProblem(driver)

        # pylint: disable=unused-argument
        def filter_criterion(eigenstate, eigenvalue, aux_values):
            particle_number_filter = np.isclose(
                aux_values["ParticleNumber"][0], 2.0)
            magnetization_filter = np.isclose(aux_values["Magnetization"][0],
                                              0.0)
            return particle_number_filter and magnetization_filter

        solver = NumPyEigensolverFactory(filter_criterion=filter_criterion)
        np_excited_solver = ExcitedStatesEigensolver(converter, solver)

        # BOPES sampler
        sampler = BOPESSampler(np_excited_solver)

        # absolute internuclear distance in Angstrom
        points = [0.7, 1.0, 1.3]
        results = sampler.sample(problem, 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, -0.47845306, -0.1204519, 0.5833141],
                [-1.10115033, -0.74587179, -0.35229063, 0.03904763],
                [-1.03518627, -0.85523694, -0.42240202, -0.21860355],
            ],
            decimal=2,
        )
 def test_sector_locator_h2o(self):
     """Test sector locator."""
     driver = PySCFDriver(
         atom=
         "O 0.0000 0.0000 0.1173; H 0.0000 0.07572 -0.4692;H 0.0000 -0.07572 -0.4692",
         basis="sto-3g",
     )
     es_problem = ElectronicStructureProblem(driver)
     qubit_conv = QubitConverter(mapper=ParityMapper(),
                                 two_qubit_reduction=True,
                                 z2symmetry_reduction="auto")
     qubit_conv.convert(
         es_problem.second_q_ops()[0],
         num_particles=es_problem.num_particles,
         sector_locator=es_problem.symmetry_sector_locator,
     )
     self.assertListEqual(qubit_conv.z2symmetries.tapering_values, [1, -1])
Beispiel #22
0
 def test_qubits_6_py_lih(self):
     """ qubits 6 py lih test """
     num_particles = (1, 1)
     converter = QubitConverter(ParityMapper(), two_qubit_reduction=True)
     z2symmetries = Z2Symmetries(
         symmetries=[Pauli('ZIZIZIZI'),
                     Pauli('ZZIIZZII')],
         sq_paulis=[Pauli('IIIIIIXI'), Pauli('IIIIIXII')],
         sq_list=[2, 3],
         tapering_values=[1, 1],
     )
     converter.force_match(num_particles=num_particles,
                           z2symmetries=z2symmetries)
     state = HartreeFock(10, num_particles, converter)
     ref = QuantumCircuit(6)
     ref.x([0, 1])
     self.assertEqual(state, ref)
    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"))

        converter = QubitConverter(ParityMapper())

        problem = ElectronicStructureProblem(driver)

        _ = problem.second_q_ops()

        num_particles = (
            problem.molecule_data_transformed.num_alpha,
            problem.molecule_data_transformed.num_beta,
        )

        num_spin_orbitals = problem.molecule_data_transformed.num_molecular_orbitals * 2

        optimizer = SLSQP(maxiter=100)

        initial_state = HartreeFock(num_spin_orbitals, num_particles,
                                    converter)

        wavefunction = ExcitationPreserving(num_spin_orbitals)
        wavefunction.compose(initial_state, front=True, inplace=True)

        solver = VQE(
            ansatz=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(converter, solver)

        result = gsc.solve(problem)
        self.assertAlmostEqual(result.total_energies[0],
                               self.reference_energy,
                               places=4)
Beispiel #24
0
    def test_uccsd_hf_qasm(self):
        """ uccsd hf test with qasm_simulator. """
        qubit_converter = QubitConverter(ParityMapper())
        ansatz = self._prepare_uccsd_hf(qubit_converter)

        backend = BasicAer.get_backend('qasm_simulator')

        optimizer = SPSA(maxiter=200, last_avg=5)
        solver = VQE(ansatz=ansatz, optimizer=optimizer,
                     expectation=PauliExpectation(),
                     quantum_instance=QuantumInstance(
                         backend=backend,
                         seed_simulator=algorithm_globals.random_seed,
                         seed_transpiler=algorithm_globals.random_seed))

        gsc = GroundStateEigensolver(qubit_converter, solver)

        result = gsc.solve(self.electronic_structure_problem)
        self.assertAlmostEqual(result.total_energies[0], -1.138, places=2)
    def setUp(self):
        super().setUp()
        algorithm_globals.random_seed = 42

        driver = HDF5Driver(hdf5_input=self.get_resource_path(
            "test_driver_hdf5.hdf5", "drivers/second_quantization/hdf5d"))
        problem = ElectronicStructureProblem(driver)
        second_q_ops = [problem.second_q_ops()[problem.main_property_name]]
        converter = QubitConverter(mapper=ParityMapper(),
                                   two_qubit_reduction=True)
        num_particles = (
            problem.grouped_property_transformed.get_property(
                "ParticleNumber").num_alpha,
            problem.grouped_property_transformed.get_property(
                "ParticleNumber").num_beta,
        )
        self.qubit_op = converter.convert(second_q_ops[0], num_particles)
        self.aux_ops = converter.convert_match(second_q_ops[1:])
        self.reference_energy = -1.857275027031588
    def test_freeze_core_z2_symmetry_compatibility(self):
        """Regression test against #192.

        An issue arose when the FreezeCoreTransformer was combined with the automatic Z2Symmetry
        reduction. This regression test ensures that this behavior remains fixed.
        """
        driver = HDF5Driver(hdf5_input=self.get_resource_path(
            "LiH_sto3g.hdf5", "transformers/second_quantization/electronic"))
        problem = ElectronicStructureProblem(driver, [FreezeCoreTransformer()])
        qubit_converter = QubitConverter(
            ParityMapper(),
            two_qubit_reduction=True,
            z2symmetry_reduction="auto",
        )

        solver = NumPyMinimumEigensolverFactory()
        gsc = GroundStateEigensolver(qubit_converter, solver)

        result = gsc.solve(problem)
        self.assertAlmostEqual(result.total_energies[0], -7.882, places=2)
Beispiel #27
0
    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.0, 0.0]],
                ["H", [1.0, 0.0, 0.0]],
            ],
            degrees_of_freedom=[stretch],
            masses=[1.6735328e-27, 1.6735328e-27],
        )

        mapper = ParityMapper()
        converter = QubitConverter(mapper=mapper)

        driver = PySCFDriver(molecule=m)
        problem = ElectronicStructureProblem(driver)

        solver = NumPyMinimumEigensolver()

        me_gss = GroundStateEigensolver(converter, solver)
        # Run BOPESSampler with exact eigensolution
        points = np.arange(0.45, 5.3, 0.3)
        sampler = BOPESSampler(gss=me_gss)

        res = sampler.sample(problem, 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)
Beispiel #28
0
    def test_h2_bopes_sampler_with_factory(self):
        """Test BOPES Sampler with Factory"""
        quantum_instance = QuantumInstance(
            backend=qiskit.providers.aer.Aer.get_backend(
                "aer_simulator_statevector"),
            seed_simulator=self.seed,
            seed_transpiler=self.seed,
        )
        # Molecule
        distance1 = partial(Molecule.absolute_distance, atom_pair=(1, 0))
        molecule = Molecule(
            geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 0.6])],
            degrees_of_freedom=[distance1],
        )

        driver = ElectronicStructureMoleculeDriver(
            molecule, driver_type=ElectronicStructureDriverType.PYSCF)
        problem = ElectronicStructureProblem(driver)
        converter = QubitConverter(ParityMapper())
        solver = GroundStateEigensolver(
            converter, VQEUCCFactory(quantum_instance=quantum_instance))
        sampler = BOPESSampler(solver,
                               bootstrap=True,
                               num_bootstrap=None,
                               extrapolator=None)

        result = sampler.sample(problem, list(np.linspace(0.6, 0.8, 4)))

        ref_points = [0.6, 0.6666666666666666, 0.7333333333333334, 0.8]
        ref_energies = [
            -1.1162853926251162,
            -1.1327033478688526,
            -1.137302817836066,
            -1.1341458916990401,
        ]
        np.testing.assert_almost_equal(result.points, ref_points, decimal=3)
        np.testing.assert_almost_equal(result.energies,
                                       ref_energies,
                                       decimal=3)
 def test_sector_locator_homonuclear(self):
     """Test sector locator."""
     molecule = Molecule(geometry=[("Li", [0.0, 0.0, 0.0]),
                                   ("Li", [0.0, 0.0, 2.771])],
                         charge=0,
                         multiplicity=1)
     freeze_core_transformer = FreezeCoreTransformer(True)
     driver = ElectronicStructureMoleculeDriver(
         molecule,
         basis="sto3g",
         driver_type=ElectronicStructureDriverType.PYSCF)
     es_problem = ElectronicStructureProblem(
         driver, transformers=[freeze_core_transformer])
     qubit_conv = QubitConverter(mapper=ParityMapper(),
                                 two_qubit_reduction=True,
                                 z2symmetry_reduction="auto")
     qubit_conv.convert(
         es_problem.second_q_ops()[0],
         num_particles=es_problem.num_particles,
         sector_locator=es_problem.symmetry_sector_locator,
     )
     self.assertListEqual(qubit_conv.z2symmetries.tapering_values, [-1, 1])
    def test_mapping_basic(self):
        """Test mapping to qubit operator"""
        mapper = JordanWignerMapper()
        qubit_conv = QubitConverter(mapper)
        qubit_op = qubit_conv.convert(self.h2_op)

        self.assertIsInstance(qubit_op, PauliSumOp)

        # Note: The PauliSumOp equals, as used in the test below, use the equals of the
        #       SparsePauliOp which in turn uses np.allclose() to determine equality of
        #       coeffs. So the reference operator above will be matched on that basis so
        #       we don't need to worry about tiny precision changes for any reason.

        self.assertEqual(qubit_op, TestQubitConverter.REF_H2_JW)

        with self.subTest("Re-use test"):
            qubit_op = qubit_conv.convert(self.h2_op)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_JW)

        with self.subTest("convert_match()"):
            qubit_op = qubit_conv.convert_match(self.h2_op)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_JW)

        with self.subTest("Re-use with different mapper"):
            qubit_conv.mapper = ParityMapper()
            qubit_op = qubit_conv.convert(self.h2_op)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_PARITY)

        with self.subTest(
                "Set two qubit reduction - no effect without num particles"):
            qubit_conv.two_qubit_reduction = True
            qubit_op = qubit_conv.convert_match(self.h2_op)
            self.assertEqual(qubit_op, TestQubitConverter.REF_H2_PARITY)

        with self.subTest("Force match set num particles"):
            qubit_conv.force_match(self.num_particles)
            qubit_op = qubit_conv.convert_match(self.h2_op)
            self.assertEqual(qubit_op,
                             TestQubitConverter.REF_H2_PARITY_2Q_REDUCED)