コード例 #1
0
    def test_driver_molecule(self):
        """Test the driver works with Molecule"""
        try:
            driver = GaussianForcesDriver(
                molecule=Molecule(
                    geometry=[
                        ("C", [-0.848629, 2.067624, 0.160992]),
                        ("O", [0.098816, 2.655801, -0.159738]),
                        ("O", [-1.796073, 1.479446, 0.481721]),
                    ],
                    multiplicity=1,
                    charge=0,
                ),
                basis="6-31g",
            )
            result = driver.run()
            self._check_driver_result(result)

        except QiskitNatureError:
            self.skipTest("GAUSSIAN driver does not appear to be installed")
コード例 #2
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)
コード例 #3
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)
コード例 #4
0
 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])
コード例 #5
0
    def test_vqe_bootstrap(self):
        """Test with VQE and bootstrapping."""
        qubit_converter = QubitConverter(JordanWignerMapper())
        quantum_instance = QuantumInstance(
            backend=qiskit.providers.aer.Aer.get_backend(
                "aer_simulator_statevector"),
            seed_simulator=self.seed,
            seed_transpiler=self.seed,
        )
        solver = VQE(quantum_instance=quantum_instance)

        vqe_gse = GroundStateEigensolver(qubit_converter, solver)

        distance1 = partial(Molecule.absolute_distance, atom_pair=(1, 0))
        mol = Molecule(
            geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 0.6])],
            degrees_of_freedom=[distance1],
        )

        driver = ElectronicStructureMoleculeDriver(
            mol, driver_type=ElectronicStructureDriverType.PYSCF)
        es_problem = ElectronicStructureProblem(driver)
        points = list(np.linspace(0.6, 0.8, 4))
        bopes = BOPESSampler(vqe_gse,
                             bootstrap=True,
                             num_bootstrap=None,
                             extrapolator=None)
        result = bopes.sample(es_problem, points)
        ref_points = [0.6, 0.6666666666666666, 0.7333333333333334, 0.8]
        ref_energies = [
            -1.1162738,
            -1.1326904,
            -1.1372876,
            -1.1341292,
        ]
        np.testing.assert_almost_equal(result.points, ref_points)
        np.testing.assert_almost_equal(result.energies, ref_energies)
コード例 #6
0
class TestDriver(ABC):
    """Common driver tests. For H2 @ 0.735, sto3g"""

    MOLECULE = Molecule(
        geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 0.735])],
        multiplicity=1,
        charge=0,
    )

    def __init__(self):
        self.log = None
        self.qmolecule = None

    @abstractmethod
    def assertAlmostEqual(self,
                          first,
                          second,
                          places=None,
                          msg=None,
                          delta=None):
        """assert Almost Equal"""
        raise Exception("Abstract method")

    @abstractmethod
    def assertEqual(self, first, second, msg=None):
        """assert equal"""
        raise Exception("Abstract method")

    @abstractmethod
    def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
        """assert Sequence Equal"""
        raise Exception("Abstract method")

    def test_driver_hf_energy(self):
        """driver hf energy test"""
        self.log.debug("QMolecule HF energy: %s", self.qmolecule.hf_energy)
        self.assertAlmostEqual(self.qmolecule.hf_energy, -1.117, places=3)

    def test_driver_nuclear_repulsion_energy(self):
        """driver nuclear repulsion energy test"""
        self.log.debug("QMolecule Nuclear repulsion energy: %s",
                       self.qmolecule.nuclear_repulsion_energy)
        self.assertAlmostEqual(self.qmolecule.nuclear_repulsion_energy,
                               0.72,
                               places=2)

    def test_driver_num_molecular_orbitals(self):
        """driver num molecular orbitals test"""
        self.log.debug("QMolecule Number of orbitals is %s",
                       self.qmolecule.num_molecular_orbitals)
        self.assertEqual(self.qmolecule.num_molecular_orbitals, 2)

    def test_driver_num_alpha(self):
        """driver num alpha test"""
        self.log.debug("QMolecule Number of alpha electrons is %s",
                       self.qmolecule.num_alpha)
        self.assertEqual(self.qmolecule.num_alpha, 1)

    def test_driver_num_beta(self):
        """driver num beta test"""
        self.log.debug("QMolecule Number of beta electrons is %s",
                       self.qmolecule.num_beta)
        self.assertEqual(self.qmolecule.num_beta, 1)

    def test_driver_molecular_charge(self):
        """driver molecular charge test"""
        self.log.debug("QMolecule molecular charge is %s",
                       self.qmolecule.molecular_charge)
        self.assertEqual(self.qmolecule.molecular_charge, 0)

    def test_driver_multiplicity(self):
        """driver multiplicity test"""
        self.log.debug("QMolecule multiplicity is %s",
                       self.qmolecule.multiplicity)
        self.assertEqual(self.qmolecule.multiplicity, 1)

    def test_driver_num_atoms(self):
        """driver num atoms test"""
        self.log.debug("QMolecule num atoms %s", self.qmolecule.num_atoms)
        self.assertEqual(self.qmolecule.num_atoms, 2)

    def test_driver_atom_symbol(self):
        """driver atom symbol test"""
        self.log.debug("QMolecule atom symbol %s", self.qmolecule.atom_symbol)
        self.assertSequenceEqual(self.qmolecule.atom_symbol, ["H", "H"])

    def test_driver_atom_xyz(self):
        """driver atom xyz test"""
        self.log.debug("QMolecule atom xyz %s", self.qmolecule.atom_xyz)
        np.testing.assert_array_almost_equal(
            self.qmolecule.atom_xyz, [[0.0, 0.0, 0.0], [0.0, 0.0, 1.3889]],
            decimal=4)

    def test_driver_mo_coeff(self):
        """driver mo coeff test"""
        self.log.debug("QMolecule MO coeffs xyz %s", self.qmolecule.mo_coeff)
        self.assertEqual(self.qmolecule.mo_coeff.shape, (2, 2))
        np.testing.assert_array_almost_equal(
            np.absolute(self.qmolecule.mo_coeff),
            [[0.5483, 1.2183], [0.5483, 1.2183]],
            decimal=4,
        )

    def test_driver_orbital_energies(self):
        """driver orbital energies test"""
        self.log.debug("QMolecule orbital energies %s",
                       self.qmolecule.orbital_energies)
        np.testing.assert_array_almost_equal(self.qmolecule.orbital_energies,
                                             [-0.5806, 0.6763],
                                             decimal=4)

    def test_driver_mo_onee_ints(self):
        """driver mo onee ints test"""
        self.log.debug("QMolecule MO one electron integrals %s",
                       self.qmolecule.mo_onee_ints)
        self.assertEqual(self.qmolecule.mo_onee_ints.shape, (2, 2))
        np.testing.assert_array_almost_equal(
            np.absolute(self.qmolecule.mo_onee_ints),
            [[1.2563, 0.0], [0.0, 0.4719]],
            decimal=4,
        )

    def test_driver_mo_eri_ints(self):
        """driver mo eri ints test"""
        self.log.debug("QMolecule MO two electron integrals %s",
                       self.qmolecule.mo_eri_ints)
        self.assertEqual(self.qmolecule.mo_eri_ints.shape, (2, 2, 2, 2))
        np.testing.assert_array_almost_equal(
            np.absolute(self.qmolecule.mo_eri_ints),
            [
                [[[0.6757, 0.0], [0.0, 0.6646]], [[0.0, 0.1809], [0.1809, 0.0]]
                 ],
                [[[0.0, 0.1809], [0.1809, 0.0]], [[0.6646, 0.0], [0.0, 0.6986]]
                 ],
            ],
            decimal=4,
        )

    def test_driver_dipole_integrals(self):
        """driver dipole integrals test"""
        self.log.debug("QMolecule has dipole integrals %s",
                       self.qmolecule.has_dipole_integrals())
        if self.qmolecule.has_dipole_integrals():
            self.assertEqual(self.qmolecule.x_dip_mo_ints.shape, (2, 2))
            self.assertEqual(self.qmolecule.y_dip_mo_ints.shape, (2, 2))
            self.assertEqual(self.qmolecule.z_dip_mo_ints.shape, (2, 2))
            np.testing.assert_array_almost_equal(
                np.absolute(self.qmolecule.x_dip_mo_ints),
                [[0.0, 0.0], [0.0, 0.0]],
                decimal=4,
            )
            np.testing.assert_array_almost_equal(
                np.absolute(self.qmolecule.y_dip_mo_ints),
                [[0.0, 0.0], [0.0, 0.0]],
                decimal=4,
            )
            np.testing.assert_array_almost_equal(
                np.absolute(self.qmolecule.z_dip_mo_ints),
                [[0.6945, 0.9278], [0.9278, 0.6945]],
                decimal=4,
            )
            np.testing.assert_array_almost_equal(
                np.absolute(self.qmolecule.nuclear_dipole_moment),
                [0.0, 0.0, 1.3889],
                decimal=4,
            )
コード例 #7
0
    def test_h2_bopes_sampler_auxiliaries(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],
        )
        driver = ElectronicStructureMoleculeDriver(
            m, driver_type=ElectronicStructureDriverType.PYSCF)
        problem = ElectronicStructureProblem(driver)

        qubit_converter = QubitConverter(JordanWignerMapper(),
                                         z2symmetry_reduction=None)
        quantum_instance = QuantumInstance(
            backend=qiskit.providers.aer.Aer.get_backend(
                "aer_simulator_statevector"),
            seed_simulator=self.seed,
            seed_transpiler=self.seed,
        )
        solver = VQE(quantum_instance=quantum_instance)
        me_gsc = GroundStateEigensolver(qubit_converter, solver)

        # Sets up the auxiliary operators

        def build_hamiltonian(
                current_problem: BaseProblem) -> SecondQuantizedOp:
            """Returns the SecondQuantizedOp H(R) where H is the electronic hamiltonian and R is
            the current nuclear coordinates. This gives the electronic energies."""
            hamiltonian_name = current_problem.main_property_name
            hamiltonian_op = current_problem.second_q_ops().get(
                hamiltonian_name, None)
            return hamiltonian_op

        aux = {
            "PN":
            problem.second_q_ops()["ParticleNumber"],  # SecondQuantizedOp
            "EN": build_hamiltonian,  # Callable
            "IN": PauliOp(Pauli("IIII"), 1.0),  # PauliOp
        }
        # Note that the first item is defined once for R=0.45.
        # The second item is a function of the problem giving the electronic energy.
        # At each step, a perturbation is applied to the molecule degrees of freedom which updates
        # the aux_operators.
        # The third item is the identity written as a PauliOp, yielding the norm of the eigenstates.

        # Sets up the BOPESSampler
        sampler = BOPESSampler(me_gsc)

        # absolute internuclear distance in Angstrom
        points = [0.7, 1.0, 1.3]
        results = sampler.sample(problem, points, aux_operators=aux)
        points_run = results.points

        particle_numbers = []
        total_energies = []
        norm_eigenstates = []

        for results_point in list(results.raw_results.values()):
            aux_op_dict = results_point.raw_result.aux_operator_eigenvalues
            particle_numbers.append(aux_op_dict["PN"][0])
            total_energies.append(aux_op_dict["EN"][0] +
                                  results_point.nuclear_repulsion_energy)
            norm_eigenstates.append(aux_op_dict["IN"][0])

        points_run_reference = [0.7, 1.0, 1.3]
        particle_numbers_reference = [2, 2, 2]
        total_energies_reference = [-1.136, -1.101, -1.035]
        norm_eigenstates_reference = [1, 1, 1]

        np.testing.assert_array_almost_equal(points_run, points_run_reference)
        np.testing.assert_array_almost_equal(particle_numbers,
                                             particle_numbers_reference,
                                             decimal=2)
        np.testing.assert_array_almost_equal(
            total_energies,
            total_energies_reference,
            decimal=2,
        )
        np.testing.assert_array_almost_equal(
            norm_eigenstates,
            norm_eigenstates_reference,
            decimal=2,
        )
コード例 #8
0
class TestDriver(ABC):
    """Common driver tests. For H2 @ 0.735, sto3g"""

    MOLECULE = Molecule(
        geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 0.735])],
        multiplicity=1,
        charge=0,
    )

    def __init__(self):
        self.log = None
        self.driver_result: ElectronicStructureDriverResult = None

    @abstractmethod
    def subTest(self, msg, **kwargs):
        # pylint: disable=invalid-name
        """subtest"""
        raise Exception("Abstract method")

    @abstractmethod
    def assertAlmostEqual(self,
                          first,
                          second,
                          places=None,
                          msg=None,
                          delta=None):
        """assert Almost Equal"""
        raise Exception("Abstract method")

    @abstractmethod
    def assertEqual(self, first, second, msg=None):
        """assert equal"""
        raise Exception("Abstract method")

    @abstractmethod
    def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
        """assert Sequence Equal"""
        raise Exception("Abstract method")

    def test_driver_result_electronic_energy(self):
        """Test the ElectronicEnergy property."""
        electronic_energy = cast(
            ElectronicEnergy,
            self.driver_result.get_property(ElectronicEnergy))

        with self.subTest("reference energy"):
            self.log.debug("HF energy: %s", electronic_energy.reference_energy)
            self.assertAlmostEqual(electronic_energy.reference_energy,
                                   -1.117,
                                   places=3)

        with self.subTest("nuclear repulsion energy"):
            self.log.debug("Nuclear repulsion energy: %s",
                           electronic_energy.nuclear_repulsion_energy)
            self.assertAlmostEqual(electronic_energy.nuclear_repulsion_energy,
                                   0.72,
                                   places=2)

        with self.subTest("orbital energies"):
            self.log.debug("orbital energies %s",
                           electronic_energy.orbital_energies)
            np.testing.assert_array_almost_equal(
                electronic_energy.orbital_energies, [-0.5806, 0.6763],
                decimal=4)

        with self.subTest("1-body integrals"):
            mo_onee_ints = electronic_energy.get_electronic_integral(
                ElectronicBasis.MO, 1)
            self.log.debug("MO one electron integrals %s", mo_onee_ints)
            self.assertEqual(mo_onee_ints._matrices[0].shape, (2, 2))
            np.testing.assert_array_almost_equal(
                np.absolute(mo_onee_ints._matrices[0]),
                [[1.2563, 0.0], [0.0, 0.4719]],
                decimal=4,
            )

        with self.subTest("2-body integrals"):
            mo_eri_ints = electronic_energy.get_electronic_integral(
                ElectronicBasis.MO, 2)
            self.log.debug("MO two electron integrals %s", mo_eri_ints)
            self.assertEqual(mo_eri_ints._matrices[0].shape, (2, 2, 2, 2))
            np.testing.assert_array_almost_equal(
                np.absolute(mo_eri_ints._matrices[0]),
                [
                    [[[0.6757, 0.0], [0.0, 0.6646]],
                     [[0.0, 0.1809], [0.1809, 0.0]]],
                    [[[0.0, 0.1809], [0.1809, 0.0]],
                     [[0.6646, 0.0], [0.0, 0.6986]]],
                ],
                decimal=4,
            )

    def test_driver_result_particle_number(self):
        """Test the ParticleNumber property."""
        particle_number = cast(ParticleNumber,
                               self.driver_result.get_property(ParticleNumber))

        with self.subTest("orbital number"):
            self.log.debug("Number of orbitals is %s",
                           particle_number.num_spin_orbitals)
            self.assertEqual(particle_number.num_spin_orbitals, 4)

        with self.subTest("alpha electron number"):
            self.log.debug("Number of alpha electrons is %s",
                           particle_number.num_alpha)
            self.assertEqual(particle_number.num_alpha, 1)

        with self.subTest("beta electron number"):
            self.log.debug("Number of beta electrons is %s",
                           particle_number.num_beta)
            self.assertEqual(particle_number.num_beta, 1)

    def test_driver_result_molecule(self):
        """Test the Molecule object."""
        molecule = self.driver_result.molecule

        with self.subTest("molecular charge"):
            self.log.debug("molecular charge is %s", molecule.charge)
            self.assertEqual(molecule.charge, 0)

        with self.subTest("multiplicity"):
            self.log.debug("multiplicity is %s", molecule.multiplicity)
            self.assertEqual(molecule.multiplicity, 1)

        with self.subTest("atom number"):
            self.log.debug("num atoms %s", len(molecule.geometry))
            self.assertEqual(len(molecule.geometry), 2)

        with self.subTest("atoms"):
            self.log.debug("atom symbol %s", molecule.atoms)
            self.assertSequenceEqual(molecule.atoms, ["H", "H"])

        with self.subTest("coordinates"):
            coords = [coord for _, coord in molecule.geometry]
            self.log.debug("atom xyz %s", coords)
            np.testing.assert_array_almost_equal(
                coords, [[0.0, 0.0, 0.0], [0.0, 0.0, 0.735]], decimal=4)

    def test_driver_result_basis_transform(self):
        """Test the ElectronicBasisTransform object."""
        basis_transform = cast(
            ElectronicBasisTransform,
            self.driver_result.get_property(ElectronicBasisTransform))

        self.log.debug("MO coeffs xyz %s", basis_transform.coeff_alpha)
        self.assertEqual(basis_transform.coeff_alpha.shape, (2, 2))
        np.testing.assert_array_almost_equal(
            np.absolute(basis_transform.coeff_alpha),
            [[0.5483, 1.2183], [0.5483, 1.2183]],
            decimal=4,
        )

    def test_driver_result_electronic_dipole(self):
        """Test the ElectronicDipoleMoment property."""
        dipole = self.driver_result.get_property(ElectronicDipoleMoment)

        self.log.debug("has dipole integrals %s", dipole is not None)
        if dipole is not None:
            dipole = cast(ElectronicDipoleMoment, dipole)

            with self.subTest("x axis"):
                mo_x_dip_ints = dipole.get_property(
                    "DipoleMomentX").get_electronic_integral(
                        ElectronicBasis.MO, 1)
                self.assertEqual(mo_x_dip_ints._matrices[0].shape, (2, 2))
                np.testing.assert_array_almost_equal(np.absolute(
                    mo_x_dip_ints._matrices[0]), [[0.0, 0.0], [0.0, 0.0]],
                                                     decimal=4)

            with self.subTest("y axis"):
                mo_y_dip_ints = dipole.get_property(
                    "DipoleMomentY").get_electronic_integral(
                        ElectronicBasis.MO, 1)
                self.assertEqual(mo_y_dip_ints._matrices[0].shape, (2, 2))
                np.testing.assert_array_almost_equal(np.absolute(
                    mo_y_dip_ints._matrices[0]), [[0.0, 0.0], [0.0, 0.0]],
                                                     decimal=4)

            with self.subTest("z axis"):
                mo_z_dip_ints = dipole.get_property(
                    "DipoleMomentZ").get_electronic_integral(
                        ElectronicBasis.MO, 1)
                self.assertEqual(mo_z_dip_ints._matrices[0].shape, (2, 2))
                np.testing.assert_array_almost_equal(
                    np.absolute(mo_z_dip_ints._matrices[0]),
                    [[0.6945, 0.9278], [0.9278, 0.6945]],
                    decimal=4,
                )

            with self.subTest("nuclear dipole moment"):
                np.testing.assert_array_almost_equal(np.absolute(
                    dipole.nuclear_dipole_moment), [0.0, 0.0, 1.3889],
                                                     decimal=4)
コード例 #9
0
    def test_construct(self):
        """test construct"""
        stretch = partial(Molecule.absolute_stretching,
                          kwargs={"atom_pair": (1, 0)})

        with self.subTest("Masses supplied"):
            mol = Molecule(
                geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 1.0])],
                degrees_of_freedom=[stretch],
                masses=[1, 1],
            )
            self.assertEqual(mol.units, UnitsType.ANGSTROM)
            self.assertListEqual(mol.geometry, [("H", [0.0, 0.0, 0.0]),
                                                ("H", [0.0, 0.0, 1.0])])
            self.assertEqual(mol.multiplicity, 1)
            self.assertEqual(mol.charge, 0)
            self.assertIsNone(mol.perturbations)
            self.assertListEqual(mol.masses, [1, 1])

        with self.subTest("No masses"):
            mol = Molecule(
                geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 1.0])],
                degrees_of_freedom=[stretch],
            )
            self.assertEqual(mol.units, UnitsType.ANGSTROM)
            self.assertIsNone(mol.masses)

        with self.subTest("All params"):
            mol = Molecule(
                geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 1.0])],
                multiplicity=2,
                charge=1,
                degrees_of_freedom=[stretch],
                masses=[0.7, 0.8],
            )
            self.assertEqual(mol.units, UnitsType.ANGSTROM)
            self.assertEqual(mol.multiplicity, 2)
            self.assertEqual(mol.charge, 1)
            self.assertIsNone(mol.perturbations)
            self.assertListEqual(mol.masses, [0.7, 0.8])

        with self.subTest("Mismatched masses length"):
            with self.assertRaises(ValueError):
                Molecule(
                    geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 1.0])],
                    masses=[1, 1, 1],
                )

        with self.subTest("Explicit Angstrom units"):
            mol = Molecule(
                geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 1.0])],
                units=UnitsType.ANGSTROM,
            )
            self.assertEqual(mol.units, UnitsType.ANGSTROM)
            self.assertListEqual(mol.geometry, [("H", [0.0, 0.0, 0.0]),
                                                ("H", [0.0, 0.0, 1.0])])

        with self.subTest("Bohr units"):
            mol = Molecule(
                geometry=[("H", [0.0, 0.0, 0.0]), ("H", [0.0, 0.0, 1.0])],
                units=UnitsType.BOHR,
            )
            self.assertEqual(mol.units, UnitsType.BOHR)
            self.assertListEqual(mol.geometry, [("H", [0.0, 0.0, 0.0]),
                                                ("H", [0.0, 0.0, 1.0])])
コード例 #10
0
 def test_multiplicity(self):
     """ test multiplicity """
     mol = Molecule(geometry=[('H', [0., 0., 0.]), ('H', [0., 0., 1.])])
     self.assertEqual(mol.multiplicity, 1)
     mol.multiplicity = 0
     self.assertEqual(mol.multiplicity, 0)
コード例 #11
0
 def test_charge(self):
     """ test charge """
     mol = Molecule(geometry=[('H', [0., 0., 0.]), ('H', [0., 0., 1.])])
     self.assertEqual(mol.charge, 0)
     mol.charge = 1
     self.assertEqual(mol.charge, 1)
コード例 #12
0
    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)