예제 #1
0
    def test_bend(self):
        """ test bend """
        with self.subTest('pi/2 bend 1-0-2'):
            geom = Molecule.absolute_bending(atom_trio=(1, 0, 2),
                                             bend=np.pi / 2,
                                             geometry=[('H', [0., 0., 0.]),
                                                       ('H', [0., 0., 1.]),
                                                       ('Li', [0., 1., -1.])])
            self.assertListEqual(geom[1][1], [0., 1., 0.])

        with self.subTest('-pi/4 bend 1-0-2'):
            geom = Molecule.absolute_bending(atom_trio=(1, 0, 2),
                                             bend=-np.pi / 4,
                                             geometry=geom)
            np.testing.assert_array_almost_equal(
                geom[1][1],
                [0., np.sqrt(2) / 2, np.sqrt(2) / 2])

        with self.subTest('-pi/4 bend 2-0-1'):
            geom = Molecule.absolute_bending(atom_trio=(2, 0, 1),
                                             bend=-np.pi / 4,
                                             geometry=geom)
            np.testing.assert_array_almost_equal(geom[2][1],
                                                 [0., 0., -np.sqrt(2)])

        # Test linear case
        with self.subTest('Linear case'):
            geom = Molecule.absolute_bending(atom_trio=(1, 0, 2),
                                             bend=np.pi / 2,
                                             geometry=[('H', [0., 0., 0.]),
                                                       ('H', [0., 0., 1.]),
                                                       ('Li', [0., 0., -1.])])
            self.assertListEqual(geom[1][1], [1., 0., 0.])
예제 #2
0
    def test_stretch(self):
        """ test stretch """
        geom = None

        with self.subTest('From original'):
            geom = Molecule.absolute_stretching(atom_pair=(1, 0),
                                                perturbation=2,
                                                geometry=[('H', [0., 0., 0.]),
                                                          ('H', [0., 0., 1.])])
            self.assertListEqual(geom[1][1], [0., 0., 3.])

        with self.subTest('Reduce stretch'):
            geom = Molecule.absolute_stretching(atom_pair=(1, 0),
                                                perturbation=-.1,
                                                geometry=geom)
            self.assertListEqual(geom[1][1], [0., 0., 3. - .1])
예제 #3
0
    def test_perturbations(self):
        """ test perturbations """
        stretch1 = partial(Molecule.absolute_stretching, atom_pair=(1, 0))
        bend = partial(Molecule.absolute_bending, atom_trio=(1, 0, 2))
        stretch2 = partial(Molecule.absolute_stretching, atom_pair=(0, 1))

        mol = Molecule(geometry=[('H', [0., 0., 0.]), ('O', [0., 0., 1.]),
                                 ('Li', [0., 1., -1.])],
                       degrees_of_freedom=[stretch1, bend, stretch2],
                       masses=[1, 1, 1])

        with self.subTest('Before perturbing'):
            geom = mol.geometry
            self.assertEqual(geom[0][0], 'H')
            self.assertEqual(geom[1][0], 'O')
            self.assertEqual(geom[2][0], 'Li')
            np.testing.assert_array_almost_equal(geom[0][1], [0., 0., 0.])
            np.testing.assert_array_almost_equal(geom[1][1], [0., 0., 1.])
            np.testing.assert_array_almost_equal(geom[2][1], [0., 1., -1.])
            self.assertIsNone(mol.perturbations)

        with self.subTest('Perturbations: [2, np.pi / 2, -.5]'):
            mol.perturbations = [2, np.pi / 2, -.5]
            geom = mol.geometry
            self.assertEqual(geom[0][0], 'H')
            self.assertEqual(geom[1][0], 'O')
            self.assertEqual(geom[2][0], 'Li')
            np.testing.assert_array_almost_equal(geom[0][1], [0.0, 0.5, 0.0])
            np.testing.assert_array_almost_equal(geom[1][1], [0., 3., 0.])
            np.testing.assert_array_almost_equal(geom[2][1], [0., 1., -1.])
            self.assertListEqual(mol.perturbations, [2, np.pi / 2, -.5])

        with self.subTest('Perturbations: None'):
            mol.perturbations = None  # Should be original geometry
            geom = mol.geometry
            self.assertEqual(geom[0][0], 'H')
            self.assertEqual(geom[1][0], 'O')
            self.assertEqual(geom[2][0], 'Li')
            np.testing.assert_array_almost_equal(geom[0][1], [0., 0., 0.])
            np.testing.assert_array_almost_equal(geom[1][1], [0., 0., 1.])
            np.testing.assert_array_almost_equal(geom[2][1], [0., 1., -1.])
            self.assertIsNone(mol.perturbations)
예제 #4
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.]), ('H', [0., 0., 1.])],
                           degrees_of_freedom=[stretch],
                           masses=[1, 1])
            self.assertListEqual(mol.geometry, [('H', [0., 0., 0.]),
                                                ('H', [0., 0., 1.])])
            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.]), ('H', [0., 0., 1.])],
                           degrees_of_freedom=[stretch])
            self.assertIsNone(mol.masses)

        with self.subTest('All params'):
            mol = Molecule(geometry=[('H', [0., 0., 0.]), ('H', [0., 0., 1.])],
                           multiplicity=2,
                           charge=1,
                           degrees_of_freedom=[stretch],
                           masses=[0.7, 0.8])
            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.]), ('H', [0., 0., 1.])],
                         masses=[1, 1, 1])
예제 #5
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 QiskitChemistryError:
            self.skipTest('GAUSSIAN driver does not appear to be installed')
    def test_potential_interface(self):
        """Tests potential interface."""
        seed = 50
        aqua_globals.random_seed = seed

        stretch = partial(Molecule.absolute_distance, atom_pair=(1, 0))
        # H-H molecule near equilibrium geometry
        m = Molecule(geometry=[
            ['H', [0., 0., 0.]],
            ['H', [1., 0., 0.]],
        ],
                     degrees_of_freedom=[stretch],
                     masses=[1.6735328E-27, 1.6735328E-27])

        f_t = FermionicTransformation()
        driver = PySCFDriver(molecule=m)

        f_t.transform(driver)

        solver = NumPyMinimumEigensolver()

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

        res = sampler.sample(driver, points)

        # Testing Potential interface
        pot = MorsePotential(m)
        pot.fit(res.points, res.energies)

        np.testing.assert_array_almost_equal([pot.alpha, pot.r_0],
                                             [2.235, 0.720],
                                             decimal=3)
        np.testing.assert_array_almost_equal([pot.d_e, pot.m_shift],
                                             [0.2107, -1.1419],
                                             decimal=3)
예제 #7
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)
예제 #8
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)
    def test_h2_bopes_sampler(self):
        """Test BOPES Sampler on H2"""
        seed = 50
        aqua_globals.random_seed = seed

        # Molecule
        dof = partial(Molecule.absolute_distance, atom_pair=(1, 0))
        m = Molecule(geometry=[['H', [0., 0., 1.]], ['H', [0., 0.45, 1.]]],
                     degrees_of_freedom=[dof])

        f_t = FermionicTransformation()
        driver = PySCFDriver(molecule=m)

        qubitop, _ = f_t.transform(driver)

        # Quantum Instance:
        shots = 1
        backend = 'statevector_simulator'
        quantum_instance = QuantumInstance(BasicAer.get_backend(backend),
                                           shots=shots)
        quantum_instance.run_config.seed_simulator = seed
        quantum_instance.compile_config['seed_transpiler'] = seed

        # Variational form
        i_state = HartreeFock(
            num_orbitals=f_t._molecule_info['num_orbitals'],
            qubit_mapping=f_t._qubit_mapping,
            two_qubit_reduction=f_t._two_qubit_reduction,
            num_particles=f_t._molecule_info['num_particles'],
            sq_list=f_t._molecule_info['z2_symmetries'].sq_list)
        var_form = RealAmplitudes(qubitop.num_qubits,
                                  reps=1,
                                  entanglement='full',
                                  skip_unentangled_qubits=False)
        var_form.compose(i_state, front=True)

        # Classical optimizer:
        # Analytic Quantum Gradient Descent (AQGD) (with Epochs)
        aqgd_max_iter = [10] + [1] * 100
        aqgd_eta = [1e0] + [1.0 / k for k in range(1, 101)]
        aqgd_momentum = [0.5] + [0.5] * 100
        optimizer = AQGD(maxiter=aqgd_max_iter,
                         eta=aqgd_eta,
                         momentum=aqgd_momentum,
                         tol=1e-6,
                         averaging=4)

        # Min Eigensolver: VQE
        solver = VQE(var_form=var_form,
                     optimizer=optimizer,
                     quantum_instance=quantum_instance,
                     expectation=PauliExpectation())

        me_gss = GroundStateEigensolver(f_t, solver)

        # BOPES sampler
        sampler = BOPESSampler(gss=me_gss)

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

        points_run = results.points
        energies = results.energies

        np.testing.assert_array_almost_equal(points_run, [0.7, 1.0, 1.3])
        np.testing.assert_array_almost_equal(
            energies, [-1.13618945, -1.10115033, -1.03518627], decimal=2)
예제 #10
0
class TestDriver(ABC):
    """Common driver tests. For H2 @ 0.735, sto3g"""

    MOLECULE = Molecule(geometry=[('H', [.0, .0, .0]), ('H', [.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: {}'.format(
            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: {}'.format(
            self.qmolecule.nuclear_repulsion_energy))
        self.assertAlmostEqual(self.qmolecule.nuclear_repulsion_energy,
                               0.72,
                               places=2)

    def test_driver_num_orbitals(self):
        """ driver num orbitals test """
        self.log.debug('QMolecule Number of orbitals is {}'.format(
            self.qmolecule.num_orbitals))
        self.assertEqual(self.qmolecule.num_orbitals, 2)

    def test_driver_num_alpha(self):
        """ driver num alpha test """
        self.log.debug('QMolecule Number of alpha electrons is {}'.format(
            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 {}'.format(
            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 {}'.format(
            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 {}'.format(
            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 {}'.format(
            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 {}'.format(
            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 {}'.format(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 {}'.format(
            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 {}'.format(
            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 {}'.format(
            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 {}'.format(
            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 {}'.format(
            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)