Exemple #1
0
    def test_mgse_callback_vqe_uccsd_z2(self):
        """ Callback test setting up Hartree Fock with UCCSD and VQE, plus z2 symmetries """

        def cb_create_solver(num_particles, num_orbitals,
                             qubit_mapping, two_qubit_reduction, z2_symmetries):
            initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping,
                                        two_qubit_reduction, z2_symmetries.sq_list)
            var_form = UCCSD(num_orbitals=num_orbitals,
                             num_particles=num_particles,
                             initial_state=initial_state,
                             qubit_mapping=qubit_mapping,
                             two_qubit_reduction=two_qubit_reduction,
                             z2_symmetries=z2_symmetries)
            vqe = VQE(var_form=var_form, optimizer=SLSQP(maxiter=500))
            vqe.quantum_instance = BasicAer.get_backend('statevector_simulator')
            return vqe

        driver = PySCFDriver(atom='Li .0 .0 -0.8; H .0 .0 0.8')
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        mgse = MolecularGroundStateEnergy(driver, qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                                          two_qubit_reduction=False, freeze_core=True,
                                          z2symmetry_reduction='auto')
        result = mgse.compute_energy(cb_create_solver)
        self.assertAlmostEqual(result.energy, -7.882, places=3)
        warnings.filterwarnings('always', category=DeprecationWarning)
Exemple #2
0
 def test_mgse_vqe(self):
     """ Test Molecular Ground State Energy VQE solver """
     warnings.filterwarnings('ignore', category=DeprecationWarning)
     mgse = MolecularGroundStateEnergy(self.driver, self.vqe)
     result = mgse.compute_energy()
     self.assertAlmostEqual(result.energy, self.reference_energy, places=5)
     warnings.filterwarnings('always', category=DeprecationWarning)
Exemple #3
0
    def _run_uccsd_vqe(self, mol_string, method, threads):
        driver = PySCFDriver(atom=mol_string,
                             unit=UnitsType.ANGSTROM,
                             charge=0,
                             spin=0,
                             basis='sto3g')

        def cb_create_solver(num_particles, num_orbitals, qubit_mapping,
                             two_qubit_reduction, z2_symmetries):
            initial_state = HartreeFock(num_orbitals, num_particles,
                                        qubit_mapping, two_qubit_reduction,
                                        z2_symmetries.sq_list)
            var_form = UCCSD(num_orbitals=num_orbitals,
                             num_particles=num_particles,
                             initial_state=initial_state,
                             qubit_mapping=qubit_mapping,
                             two_qubit_reduction=two_qubit_reduction,
                             z2_symmetries=z2_symmetries)
            vqe = VQE(var_form=var_form,
                      include_custom=True,
                      optimizer=SLSQP(maxiter=5000),
                      max_evals_grouped=256)
            vqe.quantum_instance = Aer.get_backend('qasm_simulator')
            vqe.quantum_instance.backend_options['backend_options'] = {
                'max_parallel_experiments': threads,
                'method': method
            }

            return vqe

        mgse = MolecularGroundStateEnergy(driver)
        result = mgse.compute_energy(cb_create_solver)
    def test_mgse_npme(self):
        """ Test Molecular Ground State Energy NumPy classical solver """
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        mgse = MolecularGroundStateEnergy(self.driver, self.npme)
        result = mgse.compute_energy()
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)

        formatted = result.formatted
        # Check formatted output conforms, some substrings to avoid numbers whose digits may
        # vary slightly
        self.assertEqual(len(formatted), 19)
        self.assertEqual(formatted[0], '=== GROUND STATE ENERGY ===')
        self.assertEqual(formatted[4], '  - frozen energy part: 0.0')
        self.assertEqual(formatted[5], '  - particle hole part: 0.0')
        self.assertEqual(formatted[7][0:44],
                         '> Total ground state energy (Hartree): -1.13')
        self.assertEqual(
            formatted[8],
            '  Measured:: # Particles: 2.000 S: 0.000 S^2: 0.000 M: 0.00000')
        self.assertEqual(formatted[10], '=== DIPOLE MOMENT ===')
        self.assertEqual(formatted[14],
                         '  - frozen energy part: [0.0  0.0  0.0]')
        self.assertEqual(formatted[15],
                         '  - particle hole part: [0.0  0.0  0.0]')
        self.assertEqual(formatted[18],
                         '               (debye): [0.0  0.0  0.0]  Total: 0.')
        warnings.filterwarnings('always', category=DeprecationWarning)
Exemple #5
0
    def test_mgse_callback(self):
        """ Callback testing """
        mgse = MolecularGroundStateEnergy(self.driver)

        result = mgse.compute_energy(lambda *args: NumPyMinimumEigensolver())
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)

        result = mgse.compute_energy(lambda *args: self.vqe)
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)
Exemple #6
0
    def test_mgse_callback(self):
        """ Callback testing """
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        mgse = MolecularGroundStateEnergy(self.driver)

        result = mgse.compute_energy(lambda *args: NumPyMinimumEigensolver())
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)

        result = mgse.compute_energy(lambda *args: self.vqe)
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)
        warnings.filterwarnings('always', category=DeprecationWarning)
Exemple #7
0
    def test_mgse_callback_ipqe(self):
        """ Callback test setting up Hartree Fock with IQPE """

        def cb_create_solver(num_particles, num_orbitals,
                             qubit_mapping, two_qubit_reduction, z2_symmetries):
            state_in = HartreeFock(num_orbitals, num_particles, qubit_mapping,
                                   two_qubit_reduction, z2_symmetries.sq_list)
            iqpe = IQPE(None, state_in, num_time_slices=1, num_iterations=6,
                        expansion_mode='suzuki', expansion_order=2,
                        shallow_circuit_concat=True)
            iqpe.quantum_instance = QuantumInstance(BasicAer.get_backend('qasm_simulator'),
                                                    shots=100)
            return iqpe

        mgse = MolecularGroundStateEnergy(self.driver)
        result = mgse.compute_energy(cb_create_solver)
        np.testing.assert_approx_equal(result.energy, self.reference_energy, significant=2)
Exemple #8
0
    def test_mgse_callback_vqe_uccsd(self):
        """ Callback test setting up Hartree Fock with UCCSD and VQE """

        def cb_create_solver(num_particles, num_orbitals,
                             qubit_mapping, two_qubit_reduction, z2_symmetries):
            initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping,
                                        two_qubit_reduction, z2_symmetries.sq_list)
            var_form = UCCSD(num_orbitals=num_orbitals,
                             num_particles=num_particles,
                             initial_state=initial_state,
                             qubit_mapping=qubit_mapping,
                             two_qubit_reduction=two_qubit_reduction,
                             z2_symmetries=z2_symmetries)
            vqe = VQE(var_form=var_form, optimizer=SLSQP(maxiter=500))
            vqe.quantum_instance = BasicAer.get_backend('statevector_simulator')
            return vqe

        mgse = MolecularGroundStateEnergy(self.driver)
        result = mgse.compute_energy(cb_create_solver)
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)
Exemple #9
0
    def test_mgse_solver(self):
        """ Test Molecular Ground State Energy setting solver """
        mgse = MolecularGroundStateEnergy(self.driver)
        with self.assertRaises(QiskitChemistryError):
            _ = mgse.compute_energy()

        mgse.solver = self.npme
        result = mgse.compute_energy()
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)

        mgse.solver = self.vqe
        result = mgse.compute_energy()
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)
Exemple #10
0
    def test_mgse_default_solver(self):
        """ Callback testing using default solver """
        mgse = MolecularGroundStateEnergy(self.driver)

        result = mgse.compute_energy(mgse.get_default_solver(
            BasicAer.get_backend('statevector_simulator')))
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)

        q_inst = QuantumInstance(BasicAer.get_backend('statevector_simulator'))
        result = mgse.compute_energy(mgse.get_default_solver(q_inst))
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)
Exemple #11
0
    def test_mgse_solver(self):
        """ Test Molecular Ground State Energy setting solver """
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        mgse = MolecularGroundStateEnergy(self.driver)
        with self.assertRaises(QiskitChemistryError):
            _ = mgse.compute_energy()

        mgse.solver = self.npme
        result = mgse.compute_energy()
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)

        mgse.solver = self.vqe
        result = mgse.compute_energy()
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)
        warnings.filterwarnings('always', category=DeprecationWarning)
Exemple #12
0
    def test_mgse_default_solver(self):
        """ Callback testing using default solver """
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        mgse = MolecularGroundStateEnergy(self.driver)

        result = mgse.compute_energy(mgse.get_default_solver(
            BasicAer.get_backend('statevector_simulator')))
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)

        q_inst = QuantumInstance(BasicAer.get_backend('statevector_simulator'))
        result = mgse.compute_energy(mgse.get_default_solver(q_inst))
        self.assertAlmostEqual(result.energy, self.reference_energy, places=5)
        warnings.filterwarnings('always', category=DeprecationWarning)
    def test_mgse_callback_vqe_uccsd_z2_nosymm(self):
        """ This time we reduce the operator so it has symmetries left. Whether z2 symmetry
            reduction is set to auto, or left turned off, the results should be same. We
            explicitly check the Z2 symmetry to ensure it empty and use classical solver
            to ensure the operators via the subsequent result computation are correct. """

        z2_symm = None

        def cb_create_solver(num_particles, num_orbitals, qubit_mapping,
                             two_qubit_reduction, z2_symmetries):

            nonlocal z2_symm
            z2_symm = z2_symmetries
            return NumPyMinimumEigensolver()

        driver = PySCFDriver(atom='Li .0 .0 -0.8; H .0 .0 0.8')
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        mgse = MolecularGroundStateEnergy(
            driver,
            qubit_mapping=QubitMappingType.PARITY,
            two_qubit_reduction=True,
            freeze_core=True,
            orbital_reduction=[-3, -2],
            z2symmetry_reduction='auto')
        result = mgse.compute_energy(cb_create_solver)

        # Check a couple of values are as expected, energy for main operator and number of
        # particles and dipole from auxiliary operators.
        self.assertEqual(z2_symm.is_empty(), True)
        self.assertAlmostEqual(result.energy, -7.881, places=3)
        self.assertAlmostEqual(result.num_particles, 2)
        self.assertAlmostEqual(result.total_dipole_moment_in_debye,
                               4.667,
                               places=3)

        # Run with no symmetry reduction, which should match the prior result since there
        # are no symmetries to be found.
        mgse1 = MolecularGroundStateEnergy(
            driver,
            qubit_mapping=QubitMappingType.PARITY,
            two_qubit_reduction=True,
            freeze_core=True,
            orbital_reduction=[-3, -2])
        result1 = mgse1.compute_energy(cb_create_solver)

        self.assertEqual(z2_symm.is_empty(), True)
        self.assertEqual(str(result),
                         str(result1))  # Compare string form of results
        warnings.filterwarnings('always', category=DeprecationWarning)
Exemple #14
0
 def test_mgse_vqe(self):
     """ Test Molecular Ground State Energy VQE solver """
     mgse = MolecularGroundStateEnergy(self.driver, self.vqe)
     result = mgse.compute_energy()
     self.assertAlmostEqual(result.energy, self.reference_energy, places=5)
Exemple #15
0
def run_simulation (system, indx, commandprinter = False, noise = False):

    def vqe_create_solver(num_particles, num_orbitals, qubit_mapping,
                          two_qubit_reduction, z2_symmetries,
                          initial_point = system.opt_amplitudes,
                          noise = noise):

        initial_state = HartreeFock(num_orbitals, num_particles, qubit_mapping,
                                    two_qubit_reduction, z2_symmetries.sq_list)

        var_form = UCCSD(num_orbitals=num_orbitals,
                         num_particles=num_particles,
                         initial_state=initial_state,
                         qubit_mapping=qubit_mapping,
                         two_qubit_reduction=two_qubit_reduction,
                         z2_symmetries=z2_symmetries)

        if noise:
            var_form = EfficientSU2(num_qubits = no_qubits, entanglement="linear")
        else:
            var_form = UCCSD(num_orbitals=num_orbitals,
                             num_particles=num_particles,
                             initial_state=initial_state,
                             qubit_mapping=qubit_mapping,
                             two_qubit_reduction=two_qubit_reduction,
                             z2_symmetries=z2_symmetries)

        vqe = VQE(var_form=var_form, optimizer=SLSQP(maxiter=500),
                  include_custom=True, initial_point = initial_point)
        vqe.quantum_instance = backend
        return vqe

    basis_string = 'sto-3g'
    charge = 0
    spin = 1

    no_qubits = 6


    if noise:
        optimizer = SPSA(maxiter=100)
        IBMQ.load_account()
        provider = IBMQ.get_provider(hub='ibm-q')
        qasm = Aer.get_backend("qasm_simulator")
        device = provider.get_backend("ibmq_16_melbourne")
        coupling_map = device.configuration().coupling_map
        noise_model = NoiseModel.from_backend(device.properties())
        backend = QuantumInstance(backend=qasm,
                                  shots=10000,
                                  noise_model=noise_model,
                                  coupling_map=coupling_map,
                                  measurement_error_mitigation_cls=CompleteMeasFitter,
                                  cals_matrix_refresh_period=30)
    else:
        optimizer = SLSQP(maxiter=500)
        backend = Aer.get_backend('qasm_simulator')

    ########################################################################

    # Begin Running Simulation, Convert distance_counter to angstroms
    geometry = ['H 0. 0. ' + str(system.atoms[0].position[-1] * 0.529177249),
                'H 0. 0. ' + str(system.atoms[1].position[-1] * 0.529177249),
                'H 0. 0. ' + str(system.atoms[2].position[-1] * 0.529177249)]

    if indx is not None:
        geometry[indx] = 'H 0. 0. ' + str(system.atoms[indx].stand_by_position * 0.529177249)

    print(geometry)

    driver = PySCFDriver(atom=geometry,
                         unit=UnitsType.ANGSTROM, charge=charge, spin=spin, basis=basis_string)


    # # # # # # # # # # # # # # # # # # # # # #
    # VQE Result
    # # # # # # # # # # # # # # # # # # # # # #
    mgse = MolecularGroundStateEnergy(driver,
                                      qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                                      two_qubit_reduction=False, freeze_core=False,
                                      z2symmetry_reduction=None)

    vqe_result = mgse.compute_energy(vqe_create_solver).energy
    system.opt_amplitudes = mgse.solver.optimal_params

    # # # # # # # # # # # # # # # # # # # # # #
    # Exact Result
    # # # # # # # # # # # # # # # # # # # # # #
    mgse = MolecularGroundStateEnergy(driver, NumPyMinimumEigensolver(),
                                      qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                                      two_qubit_reduction=False, freeze_core=False,
                                      z2symmetry_reduction=None)
    exact_result = mgse.compute_energy().energy

    print("VQE Result:", vqe_result,
          "Exact Energy:", exact_result)

    return ({"Exact Energy" : exact_result, "VQE Energy" : vqe_result})
Exemple #16
0
    vqe.quantum_instance = backend
    return vqe


for dist in distances:

    molecule_string = "H .0 .0 .0; H .0 .0 " + str(dist) + "; H .0 .0 3.3"
    driver = PySCFDriver(atom=molecule_string,
                         unit=UnitsType.ANGSTROM, charge=charge, spin=spin, basis=basis_string)


    # # # # # # # # # # # # # # # # # # # # # #
    # vqe Result
    # # # # # # # # # # # # # # # # # # # # # #
    mgse = MolecularGroundStateEnergy(driver, qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                                      two_qubit_reduction=False, freeze_core=False,
                                      z2symmetry_reduction=None)
    vqe_result = mgse.compute_energy(vqe_create_solver)
    vqe_energies.append(vqe_result.energy)


    # # # # # # # # # # # # # # # # # # # # # #
    # Exact Result
    # # # # # # # # # # # # # # # # # # # # # #
    mgse = MolecularGroundStateEnergy(driver, NumPyMinimumEigensolver(),
                                      qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                                      two_qubit_reduction=False, freeze_core=False,
                                      z2symmetry_reduction=None)
    exact_result = mgse.compute_energy()
    exact_energies.append(exact_result.energy)