Beispiel #1
0
    def test_swaprz(self, mode):
        """ SwapRZ variational form test """

        driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5'))
        qmolecule = driver.run()
        operator = Hamiltonian(qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                               two_qubit_reduction=False)
        qubit_op, _ = operator.run(qmolecule)

        optimizer = SLSQP(maxiter=100)
        initial_state = HartreeFock(
            operator.molecule_info['num_orbitals'],
            operator.molecule_info['num_particles'],
            qubit_mapping=operator._qubit_mapping,
            two_qubit_reduction=operator._two_qubit_reduction)

        if mode == 'wrapped':
            warnings.filterwarnings('ignore', category=DeprecationWarning)
            wavefunction = SwapRZ(qubit_op.num_qubits,
                                  initial_state=initial_state)
        else:
            wavefunction = ExcitationPreserving(qubit_op.num_qubits,
                                                initial_state=initial_state)

        algo = VQE(qubit_op, wavefunction, optimizer)

        if mode == 'wrapped':
            warnings.filterwarnings('always', category=DeprecationWarning)

        result = algo.run(
            QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                            seed_simulator=aqua_globals.random_seed,
                            seed_transpiler=aqua_globals.random_seed))
        result = operator.process_algorithm_result(result)
        self.assertAlmostEqual(result.energy, self.reference_energy, places=6)
Beispiel #2
0
    def test_excitation_preserving(self):
        """Test the excitation preserving wavefunction on a chemistry example."""

        driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5'))
        qmolecule = driver.run()
        operator = Hamiltonian(qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                               two_qubit_reduction=False)
        qubit_op, _ = operator.run(qmolecule)

        optimizer = SLSQP(maxiter=100)
        initial_state = HartreeFock(
            operator.molecule_info['num_orbitals'],
            operator.molecule_info['num_particles'],
            qubit_mapping=operator._qubit_mapping,
            two_qubit_reduction=operator._two_qubit_reduction)

        wavefunction = ExcitationPreserving(qubit_op.num_qubits,
                                            initial_state=initial_state)
        algo = VQE(qubit_op, wavefunction, optimizer)

        result = algo.run(
            QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                            seed_simulator=aqua_globals.random_seed,
                            seed_transpiler=aqua_globals.random_seed))
        result = operator.process_algorithm_result(result)
        self.assertAlmostEqual(result.energy, self.reference_energy, places=6)
Beispiel #3
0
 def test_vqe_auto_symmetry_freeze_core(self):
     """ Auto symmetry reduction, with freeze core using VQE """
     core = Hamiltonian(transformation=TransformationType.FULL,
                        qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                        two_qubit_reduction=False,
                        freeze_core=True,
                        orbital_reduction=None,
                        z2symmetry_reduction='auto')
     qubit_op, aux_ops = core.run(self.qmolecule)
     self.assertEqual(qubit_op.num_qubits, 6)
     num_orbitals = core.molecule_info[core.INFO_NUM_ORBITALS]
     num_particles = core.molecule_info[core.INFO_NUM_PARTICLES]
     qubit_mapping = 'jordan_wigner'
     two_qubit_reduction = core.molecule_info[core.INFO_TWO_QUBIT_REDUCTION]
     z2_symmetries = core.molecule_info[core.INFO_Z2SYMMETRIES]
     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(qubit_op, var_form=var_form, optimizer=SLSQP(maxiter=500), aux_operators=aux_ops)
     vqe.quantum_instance = BasicAer.get_backend('statevector_simulator')
     result = core.process_algorithm_result(vqe.compute_minimum_eigenvalue())
     self._validate_result(result)
     self.assertEqual(core.molecule_info[core.INFO_Z2SYMMETRIES].tapering_values, [-1, 1, 1, -1])
Beispiel #4
0
    def test_uccsd_hf(self):
        """ uccsd hf test """

        driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5'))
        qmolecule = driver.run()
        core = Hamiltonian(qubit_mapping=QubitMappingType.PARITY,
                           two_qubit_reduction=True)
        qubit_op, _ = core.run(qmolecule)

        optimizer = SLSQP(maxiter=100)
        initial_state = HartreeFock(
            core.molecule_info['num_orbitals'],
            core.molecule_info['num_particles'],
            qubit_mapping=core._qubit_mapping,
            two_qubit_reduction=core._two_qubit_reduction)
        var_form = UCCSD(num_orbitals=core.molecule_info['num_orbitals'],
                         num_particles=core.molecule_info['num_particles'],
                         initial_state=initial_state,
                         qubit_mapping=core._qubit_mapping,
                         two_qubit_reduction=core._two_qubit_reduction)
        algo = VQE(qubit_op, var_form, optimizer)
        result = algo.run(
            QuantumInstance(BasicAer.get_backend('statevector_simulator')))
        result = core.process_algorithm_result(result)
        self.assertAlmostEqual(result.energy, self.reference_energy, places=6)
Beispiel #5
0
    def test_swaprz(self):
        """ SwapRZ variational form test """

        driver = HDF5Driver(self.get_resource_path('test_driver_hdf5.hdf5'))
        qmolecule = driver.run()
        operator = Hamiltonian(qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                               two_qubit_reduction=False)
        qubit_op, _ = operator.run(qmolecule)

        optimizer = SLSQP(maxiter=100)
        initial_state = HartreeFock(
            qubit_op.num_qubits,
            operator.molecule_info['num_orbitals'],
            operator.molecule_info['num_particles'],
            qubit_mapping=operator._qubit_mapping,
            two_qubit_reduction=operator._two_qubit_reduction)
        var_form = SwapRZ(qubit_op.num_qubits, initial_state=initial_state)
        algo = VQE(qubit_op, var_form, optimizer)
        result = algo.run(
            QuantumInstance(BasicAer.get_backend('statevector_simulator'),
                            seed_simulator=aqua_globals.random_seed,
                            seed_transpiler=aqua_globals.random_seed))
        _, result = operator.process_algorithm_result(result)
        self.assertAlmostEqual(result['energy'],
                               self.reference_energy,
                               places=6)
    def compute_energy(
        self,
        callback: Optional[Callable[[List, int, str, bool, Z2Symmetries],
                                    MinimumEigensolver]] = None
    ) -> MolecularGroundStateResult:
        """
        Compute the ground state energy of the molecule that was supplied via the driver

        Args:
            callback: If not None will be called with the following values
                num_particles, num_orbitals, qubit_mapping, two_qubit_reduction, z2_symmetries
                in that order. This information can then be used to setup chemistry
                specific component(s) that are needed by the chosen MinimumEigensolver.
                The MinimumEigensolver can then be built and returned from this callback
                for use as the solver here.

        Returns:
            A molecular ground state result
        Raises:
            QiskitChemistryError: If no MinimumEigensolver was given and no callback is being
                                  used that could supply one instead.
        """
        if self.solver is None and callback is None:
            raise QiskitChemistryError('MinimumEigensolver was not provided')

        q_molecule = self.driver.run()
        core = Hamiltonian(transformation=self._transformation,
                           qubit_mapping=self._qubit_mapping,
                           two_qubit_reduction=self._two_qubit_reduction,
                           freeze_core=self._freeze_core,
                           orbital_reduction=self._orbital_reduction,
                           z2symmetry_reduction=self._z2symmetry_reduction)
        operator, aux_operators = core.run(q_molecule)

        if callback is not None:
            num_particles = core.molecule_info[
                ChemistryOperator.INFO_NUM_PARTICLES]
            num_orbitals = core.molecule_info[
                ChemistryOperator.INFO_NUM_ORBITALS]
            two_qubit_reduction = core.molecule_info[
                ChemistryOperator.INFO_TWO_QUBIT_REDUCTION]
            z2_symmetries = core.molecule_info[
                ChemistryOperator.INFO_Z2SYMMETRIES]
            self.solver = callback(num_particles, num_orbitals,
                                   self._qubit_mapping.value,
                                   two_qubit_reduction, z2_symmetries)

        aux_operators = aux_operators if self.solver.supports_aux_operators(
        ) else None

        raw_result = self.solver.compute_minimum_eigenvalue(
            operator, aux_operators)
        return core.process_algorithm_result(raw_result)
Beispiel #7
0
 def test_no_symmetry(self):
     """ No symmetry reduction """
     core = Hamiltonian(transformation=TransformationType.FULL,
                        qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                        two_qubit_reduction=False,
                        freeze_core=False,
                        orbital_reduction=None,
                        z2symmetry_reduction=None)
     qubit_op, aux_ops = core.run(self.qmolecule)
     self.assertEqual(qubit_op.num_qubits, 12)
     npme = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops)
     result = core.process_algorithm_result(npme.compute_minimum_eigenvalue())
     self._validate_result(result, False)
Beispiel #8
0
 def test_auto_ph_freeze_core_parity_2(self):
     """ Auto symmetry reduction, with freeze core, parity and two q reduction """
     core = Hamiltonian(transformation=TransformationType.PARTICLE_HOLE,
                        qubit_mapping=QubitMappingType.PARITY,
                        two_qubit_reduction=True,
                        freeze_core=True,
                        orbital_reduction=None,
                        z2symmetry_reduction='auto')
     qubit_op, aux_ops = core.run(self.qmolecule)
     self.assertEqual(qubit_op.num_qubits, 6)
     npme = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops)
     result = core.process_algorithm_result(npme.compute_minimum_eigenvalue())
     self._validate_result(result)
     self.assertEqual(core.molecule_info[core.INFO_Z2SYMMETRIES].tapering_values, [1, 1])
Beispiel #9
0
 def test_given_symmetry(self):
     """ Supplied symmetry reduction """
     core = Hamiltonian(transformation=TransformationType.FULL,
                        qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                        two_qubit_reduction=False,
                        freeze_core=False,
                        orbital_reduction=None,
                        z2symmetry_reduction=[1, 1, 1, 1])
     qubit_op, aux_ops = core.run(self.qmolecule)
     self.assertEqual(qubit_op.num_qubits, 8)
     npme = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops)
     result = core.process_algorithm_result(npme.compute_minimum_eigenvalue())
     self._validate_result(result)
     self.assertEqual(core.molecule_info[core.INFO_Z2SYMMETRIES].tapering_values, [1, 1, 1, 1])
Beispiel #10
0
    def _run_driver(driver, transformation=TransformationType.FULL,
                    qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False,
                    freeze_core=True):
        qmolecule = driver.run()

        core = Hamiltonian(transformation=transformation,
                           qubit_mapping=qubit_mapping,
                           two_qubit_reduction=two_qubit_reduction,
                           freeze_core=freeze_core,
                           orbital_reduction=[])

        qubit_op, aux_ops = core.run(qmolecule)

        exact_eigensolver = ExactEigensolver(qubit_op, aux_operators=aux_ops, k=1)
        _, result = core.process_algorithm_result(exact_eigensolver.run())
        return result
    def run(self, instance, verbose=False):
        for i, d in enumerate(self.distances):
            print("Simulation step", i, "simulating molecule: ", self.molecule.format(d))
            if verbose:
                print("PySCFDriver")
            driver = PySCFDriver(self.molecule.format(d), basis="sto3g")
            if verbose:
                print("driver.run")
            qmolecule = driver.run()
            if verbose:
                print("Hamiltonian")
            operator = Hamiltonian(qubit_mapping=QubitMappingType.PARITY, 
                                   two_qubit_reduction=self.two_qubit_reduction, 
                                   freeze_core=self.freeze_core, 
                                   orbital_reduction=self.orbital_reduction)
            if verbose:
                print("Hamiltonian.run")
            qubit_op, aux_ops = operator.run(qmolecule)
            if verbose:
                print("SLSQP")
            optimizer = SLSQP(maxiter=100)
            
            if verbose:
                print("HartreeFock")
            initial_state = HartreeFock(operator.molecule_info["num_orbitals"], 
                                        operator.molecule_info["num_particles"], 
                                        "parity", 
                                        two_qubit_reduction=self.two_qubit_reduction)
            if verbose:
                print("UCCSD")
            var_form = UCCSD(num_orbitals=operator.molecule_info["num_orbitals"], 
                             num_particles=operator.molecule_info["num_particles"], 
                             initial_state=initial_state, 
                             qubit_mapping="parity", 
                             two_qubit_reduction=self.two_qubit_reduction)
            if verbose:
                print("VQE")
            algo = VQE(qubit_op, var_form, optimizer, aux_operators=aux_ops)
            if verbose:
                print("VQE.run")
            vqe_result = algo.run(instance)
            if verbose:
                print("Hamiltonian.process_algorithm_result")
            vqe_result_processed = operator.process_algorithm_result(vqe_result)

            self.vqe_energies.append(vqe_result_processed.energy)
            self.hf_energies.append(vqe_result_processed.hartree_fock_energy)
Beispiel #12
0
    def _run_driver(driver,
                    transformation=TransformationType.FULL,
                    qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                    two_qubit_reduction=False,
                    freeze_core=True):
        qmolecule = driver.run()

        core = Hamiltonian(transformation=transformation,
                           qubit_mapping=qubit_mapping,
                           two_qubit_reduction=two_qubit_reduction,
                           freeze_core=freeze_core,
                           orbital_reduction=[])

        qubit_op, aux_ops = core.run(qmolecule)

        npme = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops)
        result = core.process_algorithm_result(
            npme.compute_minimum_eigenvalue())
        return result
 def test_auto_symmetry(self):
     """ Auto symmetry reduction """
     warnings.filterwarnings('ignore', category=DeprecationWarning)
     core = Hamiltonian(transformation=TransformationType.FULL,
                        qubit_mapping=QubitMappingType.JORDAN_WIGNER,
                        two_qubit_reduction=False,
                        freeze_core=False,
                        orbital_reduction=None,
                        z2symmetry_reduction='auto')
     warnings.filterwarnings('always', category=DeprecationWarning)
     qubit_op, aux_ops = core.run(self.qmolecule)
     self.assertEqual(qubit_op.num_qubits, 8)
     npme = NumPyMinimumEigensolver(qubit_op, aux_operators=aux_ops)
     warnings.filterwarnings('ignore', category=DeprecationWarning)
     result = core.process_algorithm_result(
         npme.compute_minimum_eigenvalue())
     warnings.filterwarnings('always', category=DeprecationWarning)
     self._validate_result(result)
     self.assertEqual(
         core.molecule_info[core.INFO_Z2SYMMETRIES].tapering_values,
         [1, 1, 1, 1])
Beispiel #14
0
    # Variational Quantum Eigensolver (VQE)
    optimizer = SLSQP(maxiter=1000)
    initial_state = HartreeFock(
        operator.molecule_info['num_orbitals'],
        operator.molecule_info['num_particles'],
        qubit_mapping=operator._qubit_mapping,
        two_qubit_reduction=operator._two_qubit_reduction)

    variational_form = UCCSD(
        num_orbitals=operator.molecule_info['num_orbitals'],
        num_particles=operator.molecule_info['num_particles'],
        initial_state=initial_state,
        qubit_mapping=operator._qubit_mapping,
        two_qubit_reduction=operator._two_qubit_reduction)

    algo = VQE(qubit_op, variational_form, optimizer, aux_operators=aux_ops)

    variational_quantum_eigensolver_result = algo.run(
        QuantumInstance(BasicAer.get_backend('statevector_simulator')))
    variational_quantum_eigensolver_result = operator.process_algorithm_result(
        variational_quantum_eigensolver_result)

    variational_quantum_eigensolver_energies.append(
        variational_quantum_eigensolver_result.energy)
    hartree_fock_energies.append(
        variational_quantum_eigensolver_result.hartree_fock_energy)

for i, d in enumerate(distances):
    print('%f A %f eV' % (d, variational_quantum_eigensolver_energies[i]))
class TestUCCSDHartreeFock(QiskitChemistryTestCase):
    """Test for these aqua extensions."""

    def setUp(self):
        super().setUp()
        self.molecule = "H 0.000000 0.000000 0.735000;H 0.000000 0.000000 0.000000"
        self.driver = PySCFDriver(atom=self.molecule,
                                  unit=UnitsType.ANGSTROM,
                                  charge=0,
                                  spin=0,
                                  basis='631g')
        self.qmolecule = self.driver.run()
        self.core = Hamiltonian(transformation=TransformationType.FULL,
                                qubit_mapping=QubitMappingType.PARITY,
                                two_qubit_reduction=True,
                                freeze_core=True,
                                orbital_reduction=[])
        self.qubit_op, _ = self.core.run(self.qmolecule)

        z2_symmetries = Z2Symmetries.find_Z2_symmetries(self.qubit_op)
        tapered_ops = z2_symmetries.taper(self.qubit_op)
        smallest_eig_value = 99999999999999
        smallest_idx = -1
        for idx, _ in enumerate(tapered_ops):
            ee = ExactEigensolver(tapered_ops[idx], k=1)
            curr_value = ee.run()['energy']
            if curr_value < smallest_eig_value:
                smallest_eig_value = curr_value
                smallest_idx = idx
        self.the_tapered_op = tapered_ops[smallest_idx]

        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]]]
        pass

    def test_uccsd_hf_qpUCCD(self):
        """ paired uccd test """

        optimizer = SLSQP(maxiter=100)
        initial_state = HartreeFock(self.qubit_op.num_qubits,
                                    self.core.molecule_info['num_orbitals'],
                                    self.core.molecule_info['num_particles'],
                                    qubit_mapping=self.core._qubit_mapping,
                                    two_qubit_reduction=self.core._two_qubit_reduction)

        var_form = UCCSD(num_qubits=self.qubit_op.num_qubits, depth=1,
                         num_orbitals=self.core._molecule_info['num_orbitals'],
                         num_particles=self.core._molecule_info['num_particles'],
                         active_occupied=None, active_unoccupied=None,
                         initial_state=initial_state,
                         qubit_mapping=self.core._qubit_mapping,
                         two_qubit_reduction=self.core._two_qubit_reduction,
                         num_time_slices=1,
                         shallow_circuit_concat=False,
                         method_doubles='pucc',
                         excitation_type='d'
                         )

        algo = VQE(self.qubit_op, var_form, optimizer)
        result = algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator')))
        _, result = self.core.process_algorithm_result(result)
        self.assertAlmostEqual(result['energy'], self.reference_energy_pUCCD, places=6)

    def test_uccsd_hf_qUCCD0(self):
        """ singlet uccd test """

        optimizer = SLSQP(maxiter=100)
        initial_state = HartreeFock(self.qubit_op.num_qubits,
                                    self.core.molecule_info['num_orbitals'],
                                    self.core.molecule_info['num_particles'],
                                    qubit_mapping=self.core._qubit_mapping,
                                    two_qubit_reduction=self.core._two_qubit_reduction)

        var_form = UCCSD(num_qubits=self.qubit_op.num_qubits, depth=1,
                         num_orbitals=self.core._molecule_info['num_orbitals'],
                         num_particles=self.core._molecule_info['num_particles'],
                         active_occupied=None, active_unoccupied=None,
                         initial_state=initial_state,
                         qubit_mapping=self.core._qubit_mapping,
                         two_qubit_reduction=self.core._two_qubit_reduction,
                         num_time_slices=1,
                         shallow_circuit_concat=False,
                         method_doubles='succ',
                         excitation_type='d'
                         )

        algo = VQE(self.qubit_op, var_form, optimizer)
        result = algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator')))
        _, result = self.core.process_algorithm_result(result)
        self.assertAlmostEqual(result['energy'], self.reference_energy_UCCD0, places=6)

    def test_uccsd_hf_qUCCD0full(self):
        """ singlet full uccd test """

        optimizer = SLSQP(maxiter=100)

        initial_state = HartreeFock(self.qubit_op.num_qubits,
                                    self.core.molecule_info['num_orbitals'],
                                    self.core.molecule_info['num_particles'],
                                    qubit_mapping=self.core._qubit_mapping,
                                    two_qubit_reduction=self.core._two_qubit_reduction)

        var_form = UCCSD(num_qubits=self.qubit_op.num_qubits, depth=1,
                         num_orbitals=self.core._molecule_info['num_orbitals'],
                         num_particles=self.core._molecule_info['num_particles'],
                         active_occupied=None, active_unoccupied=None,
                         initial_state=initial_state,
                         qubit_mapping=self.core._qubit_mapping,
                         two_qubit_reduction=self.core._two_qubit_reduction,
                         num_time_slices=1,
                         shallow_circuit_concat=False,
                         method_doubles='succ_full',
                         excitation_type='d'
                         )

        algo = VQE(self.qubit_op, var_form, optimizer)
        result = algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator')))
        _, result = self.core.process_algorithm_result(result)
        self.assertAlmostEqual(result['energy'], self.reference_energy_UCCD0full, places=6)

    def test_uccsd_hf_qUCCSD(self):
        """ uccsd tapering test using all double excitations """

        # optimizer
        optimizer = SLSQP(maxiter=100)

        # initial state
        init_state = HartreeFock(num_qubits=self.the_tapered_op.num_qubits,
                                 num_orbitals=self.core._molecule_info['num_orbitals'],
                                 qubit_mapping=self.core._qubit_mapping,
                                 two_qubit_reduction=self.core._two_qubit_reduction,
                                 num_particles=self.core._molecule_info['num_particles'],
                                 sq_list=self.the_tapered_op.z2_symmetries.sq_list)

        var_form = UCCSD(num_qubits=self.the_tapered_op.num_qubits, depth=1,
                         num_orbitals=self.core._molecule_info['num_orbitals'],
                         num_particles=self.core._molecule_info['num_particles'],
                         active_occupied=None, active_unoccupied=None,
                         initial_state=init_state,
                         qubit_mapping=self.core._qubit_mapping,
                         two_qubit_reduction=self.core._two_qubit_reduction,
                         num_time_slices=1,
                         z2_symmetries=self.the_tapered_op.z2_symmetries,
                         shallow_circuit_concat=False,
                         method_doubles='ucc',
                         excitation_type='sd',
                         skip_commute_test=True)

        algo = VQE(self.the_tapered_op, var_form, optimizer)

        result = algo.run(QuantumInstance(BasicAer.get_backend('statevector_simulator')))
        _, result = self.core.process_algorithm_result(result)
        self.assertAlmostEqual(result['energy'], self.reference_energy_UCCSD, places=6)

    def test_uccsd_hf_excitations(self):
        """ uccsd tapering test using all double excitations """

        # initial state
        init_state = HartreeFock(num_qubits=self.the_tapered_op.num_qubits,
                                 num_orbitals=self.core._molecule_info['num_orbitals'],
                                 qubit_mapping=self.core._qubit_mapping,
                                 two_qubit_reduction=self.core._two_qubit_reduction,
                                 num_particles=self.core._molecule_info['num_particles'],
                                 sq_list=self.the_tapered_op.z2_symmetries.sq_list)

        # check singlet excitations
        var_form = UCCSD(num_qubits=self.the_tapered_op.num_qubits, depth=1,
                         num_orbitals=self.core._molecule_info['num_orbitals'],
                         num_particles=self.core._molecule_info['num_particles'],
                         active_occupied=None, active_unoccupied=None,
                         initial_state=init_state,
                         qubit_mapping=self.core._qubit_mapping,
                         two_qubit_reduction=self.core._two_qubit_reduction,
                         num_time_slices=1,
                         z2_symmetries=self.the_tapered_op.z2_symmetries,
                         shallow_circuit_concat=False,
                         method_doubles='succ',
                         excitation_type='d',
                         skip_commute_test=True)

        double_excitations_singlet = var_form._double_excitations
        res = TestUCCSDHartreeFock.excitation_lists_comparator(
            double_excitations_singlet, self.reference_singlet_double_excitations)
        self.assertEqual(res, True)

        # check grouped singlet excitations
        var_form = UCCSD(num_qubits=self.the_tapered_op.num_qubits, depth=1,
                         num_orbitals=self.core._molecule_info['num_orbitals'],
                         num_particles=self.core._molecule_info['num_particles'],
                         active_occupied=None, active_unoccupied=None,
                         initial_state=init_state,
                         qubit_mapping=self.core._qubit_mapping,
                         two_qubit_reduction=self.core._two_qubit_reduction,
                         num_time_slices=1,
                         z2_symmetries=self.the_tapered_op.z2_symmetries,
                         shallow_circuit_concat=False,
                         method_doubles='succ_full',
                         excitation_type='d',
                         skip_commute_test=True)

        double_excitations_singlet_grouped = var_form._double_excitations_grouped
        res_groups = TestUCCSDHartreeFock.group_excitation_lists_comparator(
            double_excitations_singlet_grouped, self.reference_singlet_groups)
        self.assertEqual(res_groups, True)

    @staticmethod
    def pop_el_when_matched(list1, list2):
        """
        Compares if in list1 and list2 one of excitations is the same (regardless of permutations of
        its elements). When same excitation is found, it returns the 2 lists without that excitation
        .

        Args:
            list1 (list): list of excitations (e.g. [[0, 2, 4, 6], [0, 2, 4, 7]])
            list2 (list): list of excitations

        Returns:
            list: list1 with one popped element if match was found
            list: list2 with one popped element if match was found
        """
        counter = 0
        for i, exc1 in enumerate(list1):
            for j, exc2 in enumerate(list2):
                for ind1 in exc1:
                    for ind2 in exc2:
                        if ind1 == ind2:
                            counter += 1
                if counter == len(exc1) and counter == len(exc2):
                    list1.pop(i)
                    list2.pop(j)
                    break
            break
        return list1, list2

    @staticmethod
    def excitation_lists_comparator(list1, list2):
        """
        Compares if list1 and list2 contain same excitations (regardless of permutations of
        its elements). Only works provided all indices for an excitation are different.

        Args:
            list1 (list): list of excitations (e.g. [[0, 2, 4, 6], [0, 2, 4, 7]])
            list2 (list): list of excitations

        Returns:
            bool: True or False, if list1 and list2 contain the same excitations
        """
        if len(list1) != len(list2):
            return False

        number_el = len(list1)

        for _ in range(number_el):
            list1, list2 = TestUCCSDHartreeFock.pop_el_when_matched(list1, list2)

        return bool(len(list1) or len(list2) in [0])

    @staticmethod
    def group_excitation_lists_comparator(glist1, glist2):
        """
        Compares if list1 and list2 contain same excitations (regardless of permutations of
        its elements). Only works provided all indices for an excitation are different.

        Args:
            glist1 (list): list of excitations (e.g. [[0, 2, 4, 6], [0, 2, 4, 7]])
            glist2 (list): list of excitations

        Returns:
            bool: True or False, if list1 and list2 contain the same excitations
        """
        if len(glist1) != len(glist2):
            return False

        number_groups = len(glist1)
        counter = 0
        for _, gr1 in enumerate(glist1):
            for _, gr2 in enumerate(glist2):
                res = TestUCCSDHartreeFock.excitation_lists_comparator(gr1, gr2)
                if res is True:
                    counter += 1

        return bool(counter == number_groups)
var_form = UCCSD(num_qubits=the_tapered_op.num_qubits,
                 depth=1,
                 num_orbitals=core._molecule_info['num_orbitals'],
                 num_particles=core._molecule_info['num_particles'],
                 active_occupied=None,
                 active_unoccupied=None,
                 initial_state=init_state,
                 qubit_mapping=core._qubit_mapping,
                 two_qubit_reduction=core._two_qubit_reduction,
                 num_time_slices=1,
                 z2_symmetries=the_tapered_op.z2_symmetries,
                 shallow_circuit_concat=False)
#                 force_no_tap_excitation=True,
#                 method_doubles='succ',
#                 excitation_type='d',
#                 same_spin_doubles=False)

# set up VQE
algo = VQE(the_tapered_op, var_form, optimizer)

# Choose the backend (use Aer instead of BasicAer)
backend = Aer.get_backend('statevector_simulator')
quantum_instance = QuantumInstance(backend=backend, optimization_level=1)

# run the algorithm
algo_result = algo.run(quantum_instance)

# get the results
_, result = core.process_algorithm_result(algo_result)
print(result)
class VQEWrapper():
    def __init__(self):

        ### MOLECULE ###
        # These things need to be set before running
        self.molecule_string = None
        # You can make a pretty educated guess for these two
        self.spin = None
        self.charge = None

        self.qmolecule = None

        ### CHEMISTRY DRIVER ###
        #Basis has to be in a format accepted by Gaussian (sto-3g, 6-31g)
        self.basis = 'sto-3g'
        self.chem_driver = DriverType.GAUSSIAN
        self.hf_method = HFMethodType.UHF
        self.length_unit = UnitsType.ANGSTROM
        self.gaussian_checkfile = ''

        self.driver = None
        self.core = None

        ### HAMILTONIAN ###
        self.transformation = TransformationType.FULL
        self.qubit_mapping = QubitMappingType.JORDAN_WIGNER
        self.two_qubit_reduction = False
        self.freeze_core = True
        self.orbital_reduction = []

        self.qubit_op = None
        self.aux_ops = None
        self.initial_point = None

        self.optimizer = SLSQP(maxiter=5000)

        self.ansatz = 'UCCSD'
        self.excitation_type = 'sd'
        self.num_time_slices = 1
        self.shallow_circuit_concat = False

        self.vqe_algo = None

        self.var_form = None
        self.vqe_callback = None
        self.vqe_time = None

        ### BACKEND CONFIG ###
        #Choose the backend (use Aer instead of BasicAer)
        self.simulator = 'statevector_simulator'
        self.shots = 1024
        self.seed_simulator = None
        self.seed_transpiler = None
        self.noise_model = None
        self.measurement_error_mitigation_cls = None
        self.backend_options = {}

    def opt_str(self):
        match = re.search(r'optimizers.[A-z]+.(.+) object',
                          str(self.optimizer))
        opt_str = match.group(1)
        return opt_str

    def gaussian_config(self):
        #Format properties to a string fitting the gaussian input format
        if self.gaussian_checkfile != '':
            chk = f'%Chk={self.gaussian_checkfile}\n'
        else:
            chk = ''
        gaussian_config = chk + f'# {self.hf_method.value}/{self.basis} scf(conventional)\n\nMolecule\n\n{self.charge} {self.spin+1}\n'
        gaussian_config = gaussian_config + self.molecule_string.replace(
            '; ', '\n') + '\n\n'
        return gaussian_config

    def initiate(self):

        self.init_backend()
        self.init_driver()
        self.init_core()
        self.init_ops()
        self.init_init_state()
        self.init_var_form()
        self.init_vqe()

    def init_driver(self):

        if self.chem_driver.value == 'PySCF':
            if self.hf_method == HFMethodType.RHF and self.spin % 2 == 0:
                print(
                    f'WARNING: Restricted Hartree-Fock (RHF) cannot handle unpaired electrons!'
                )
                print(f'Switching to Unrestricted Hartree-Fock!')
                self.chem_driver = HFMethodType.UHF

            self.driver = PySCFDriver(atom=self.molecule_string,
                                      unit=self.length_unit,
                                      charge=self.charge,
                                      spin=self.spin,
                                      hf_method=self.hf_method,
                                      basis=self.basis)

        elif self.chem_driver.value == 'Gaussian':
            self.driver = GaussianDriver(config=self.gaussian_config())

        self.qmolecule = self.driver.run()

    def init_backend(self):
        self.backend = Aer.get_backend(self.simulator)
        self.quantum_instance = QuantumInstance(
            backend=self.backend,
            shots=self.shots,
            seed_simulator=self.seed_simulator,
            seed_transpiler=self.seed_transpiler,
            noise_model=self.noise_model,
            measurement_error_mitigation_cls=self.
            measurement_error_mitigation_cls,
            backend_options=self.backend_options)

    def init_core(self):
        self.core = Hamiltonian(transformation=self.transformation,
                                qubit_mapping=self.qubit_mapping,
                                two_qubit_reduction=self.two_qubit_reduction,
                                freeze_core=self.freeze_core,
                                orbital_reduction=self.orbital_reduction)

    def init_ops(self):
        self.qubit_op, self.aux_ops = self.core.run(self.qmolecule)

    #Initial state
    def init_init_state(self):
        self.init_state = HartreeFock(
            num_orbitals=self.core._molecule_info['num_orbitals'],
            qubit_mapping=self.core._qubit_mapping,
            two_qubit_reduction=self.core._two_qubit_reduction,
            num_particles=self.core._molecule_info['num_particles'])

    #Set up VQE
    def init_vqe(self):
        self.vqe_algo = VQE(self.qubit_op,
                            self.var_form,
                            self.optimizer,
                            initial_point=self.initial_point,
                            callback=self.vqe_callback)

    def init_var_form(self):
        if self.ansatz.upper() == 'UCCSD':
            # UCCSD Ansatz
            self.var_form = UCCSD(
                num_orbitals=self.core._molecule_info['num_orbitals'],
                num_particles=self.core._molecule_info['num_particles'],
                initial_state=self.init_state,
                qubit_mapping=self.core._qubit_mapping,
                two_qubit_reduction=self.core._two_qubit_reduction,
                num_time_slices=self.num_time_slices,
                excitation_type=self.excitation_type,
                shallow_circuit_concat=self.shallow_circuit_concat)
        else:
            if self.var_form is None:
                raise ValueError('No variational form specified!')

    def print_config(self):
        print(f'\n\n=== MOLECULAR INFORMATION ===')
        print(f'*  Molecule string: {self.molecule_string}')
        print(f'*  Charge: {self.charge}')
        print(f'*  Spin (2S): {self.spin}')
        print(f'*  Basis set: {self.basis}')
        print(f'*  Num orbitals: {self.qmolecule.num_orbitals}')
        print(f'*  Lenght Unit: {self.length_unit}')
        print(f'*  HF method: {self.hf_method}')

        print(f'\n\n=== HAMILTONIAN INFORMATION ===')
        print(f'*  Transformation type: {self.transformation}')
        print(f'*  Qubit mapping: {self.qubit_mapping}')
        print(f'*  Two qubit reduction: {self.two_qubit_reduction}')
        print(f'*  Freeze core: {self.freeze_core}')
        print(f'*  Orbital reduction: {self.orbital_reduction}')

        print(f'\n\n=== CHEMISTRY DRIVER INFORMATION ===')
        print(f'*  Not yet implemented!')

        print(f'\n\n=== BACKEND INFORMATION ===')
        print(f'*  Not yet implemented!')

    def run_vqe(self):
        #Run the algorithm
        vqe_start = timer()
        self.vqe_result = self.vqe_algo.run(self.quantum_instance)
        self.vqe_time = timer() - vqe_start

        #Get the results
        result = self.core.process_algorithm_result(self.vqe_result)

        return result
            result = NumPyMinimumEigensolver(qubit_op).run()
        else:
            # Choice of classical optimizer
            optimizer = SPSA(max_trials=256)
            # Choice of ansatz
            var_form = TwoLocal(qubit_op.num_qubits, ['ry', 'rz'],
                                'cz',
                                reps=3,
                                entanglement='full')
            algo = VQE(qubit_op, var_form, optimizer, max_evals_grouped=1)
            result = algo.run(
                QuantumInstance(BasicAer.get_backend('statevector_simulator')))
            if j == 0:
                algorithms[j]['initial_point'] = result.optimal_point.tolist()

        result = operator.process_algorithm_result(result)
        energies[j][i] = result.energy
        hf_energies[i] = result.hartree_fock_energy

    distances[i] = d
print(' --- complete')

print('Distances: ', distances)
print('Energies:', energies)
print('Hartree-Fock energies:', hf_energies)

plt.plot(distances, hf_energies, label='Hartree-Fock')
for j in range(len(algorithms)):
    plt.plot(distances, energies[j], label=titles[j])
plt.xlabel('Interatomic distance')
plt.ylabel('Energy')
class TestEnd2End(QiskitChemistryTestCase):
    """End2End VQE tests."""
    def setUp(self):
        super().setUp()
        driver = HDF5Driver(
            hdf5_input=self.get_resource_path('test_driver_hdf5.hdf5'))
        self.qmolecule = driver.run()

        self.core = Hamiltonian(transformation=TransformationType.FULL,
                                qubit_mapping=QubitMappingType.PARITY,
                                two_qubit_reduction=True,
                                freeze_core=False,
                                orbital_reduction=[])

        self.qubit_op, self.aux_ops = self.core.run(self.qmolecule)
        self.reference_energy = -1.857275027031588

    @idata([
        [
            'COBYLA_M', 'COBYLA',
            qiskit.BasicAer.get_backend('statevector_simulator'), 1
        ],
        [
            'COBYLA_P', 'COBYLA',
            qiskit.BasicAer.get_backend('statevector_simulator'), 1
        ],
        # ['SPSA_P', 'SPSA', qiskit.BasicAer.get_backend('qasm_simulator'), 'paulis', 1024],
        # ['SPSA_GP', 'SPSA', qiskit.BasicAer.get_backend('qasm_simulator'), 'grouped_paulis', 1024]
    ])
    @unpack
    def test_end2end_h2(self, name, optimizer, backend, shots):
        """ end to end h2 """
        del name  # unused
        if optimizer == 'COBYLA':
            optimizer = COBYLA()
            optimizer.set_options(maxiter=1000)
        elif optimizer == 'SPSA':
            optimizer = SPSA(maxiter=2000)

        ryrz = TwoLocal(rotation_blocks=['ry', 'rz'], entanglement_blocks='cz')
        vqe = VQE(self.qubit_op, ryrz, optimizer, aux_operators=self.aux_ops)
        quantum_instance = QuantumInstance(backend, shots=shots)
        result = vqe.run(quantum_instance)
        self.assertAlmostEqual(result.eigenvalue.real,
                               self.reference_energy,
                               places=4)
        # TODO test aux_ops properly

    def test_deprecated_algo_result(self):
        """ Test processing a deprecated dictionary result from algorithm """
        try:
            warnings.filterwarnings("ignore", category=DeprecationWarning)
            ryrz = TwoLocal(self.qubit_op.num_qubits, ['ry', 'rz'],
                            'cz',
                            reps=3)
            vqe = VQE(self.qubit_op,
                      ryrz,
                      COBYLA(),
                      aux_operators=self.aux_ops)
            quantum_instance = QuantumInstance(
                qiskit.BasicAer.get_backend('statevector_simulator'))
            result = vqe.run(quantum_instance)
            keys = {'energy', 'energies', 'eigvals', 'eigvecs', 'aux_ops'}
            dict_res = {key: result[key] for key in keys}
            lines, result = self.core.process_algorithm_result(dict_res)
            self.assertAlmostEqual(result['energy'], -1.137306, places=4)
            self.assertEqual(len(lines), 19)
            self.assertEqual(
                lines[8],
                '  Measured:: Num particles: 2.000, S: 0.000, M: 0.00000')
        finally:
            warnings.filterwarnings("always", category=DeprecationWarning)
Beispiel #20
0
class TestSymmetries(QiskitChemistryTestCase):
    """Test for symmetry processing."""

    def setUp(self):
        super().setUp()
        try:
            driver = PySCFDriver(atom='Li .0 .0 .0; H .0 .0 1.6',
                                 unit=UnitsType.ANGSTROM,
                                 charge=0,
                                 spin=0,
                                 basis='sto3g')
        except QiskitChemistryError:
            self.skipTest('PYSCF driver does not appear to be installed')
        self.qmolecule = driver.run()
        self.core = Hamiltonian(transformation=TransformationType.FULL,
                                qubit_mapping=QubitMappingType.PARITY,
                                two_qubit_reduction=True,
                                freeze_core=True,
                                orbital_reduction=[])
        self.qubit_op, _ = self.core.run(self.qmolecule)
        self.z2_symmetries = Z2Symmetries.find_Z2_symmetries(self.qubit_op)

        self.reference_energy = -7.882096489442

    def test_symmetries(self):
        """ symmetries test """
        labels = [symm.to_label() for symm in self.z2_symmetries.symmetries]
        self.assertSequenceEqual(labels, ['ZIZIZIZI', 'ZZIIZZII'])

    def test_sq_paulis(self):
        """ sq paulis test """
        labels = [sq.to_label() for sq in self.z2_symmetries.sq_paulis]
        self.assertSequenceEqual(labels, ['IIIIIIXI', 'IIIIIXII'])

    def test_cliffords(self):
        """ clifford test """
        self.assertEqual(2, len(self.z2_symmetries.cliffords))

    def test_sq_list(self):
        """ sq list test """
        self.assertSequenceEqual(self.z2_symmetries.sq_list, [1, 2])

    def test_tapered_op(self):
        """ tapered op test """
        tapered_ops = self.z2_symmetries.taper(self.qubit_op)
        smallest_idx = 0  # Prior knowledge of which tapered_op has ground state
        the_tapered_op = tapered_ops[smallest_idx]

        optimizer = SLSQP(maxiter=1000)

        init_state = HartreeFock(num_qubits=the_tapered_op.num_qubits,
                                 num_orbitals=self.core._molecule_info['num_orbitals'],
                                 qubit_mapping=self.core._qubit_mapping,
                                 two_qubit_reduction=self.core._two_qubit_reduction,
                                 num_particles=self.core._molecule_info['num_particles'],
                                 sq_list=the_tapered_op.z2_symmetries.sq_list)

        var_form = UCCSD(num_qubits=the_tapered_op.num_qubits, depth=1,
                         num_orbitals=self.core._molecule_info['num_orbitals'],
                         num_particles=self.core._molecule_info['num_particles'],
                         active_occupied=None, active_unoccupied=None,
                         initial_state=init_state,
                         qubit_mapping=self.core._qubit_mapping,
                         two_qubit_reduction=self.core._two_qubit_reduction,
                         num_time_slices=1,
                         z2_symmetries=the_tapered_op.z2_symmetries)

        algo = VQE(the_tapered_op, var_form, optimizer)

        backend = BasicAer.get_backend('statevector_simulator')
        quantum_instance = QuantumInstance(backend=backend)

        algo_result = algo.run(quantum_instance)

        _, result = self.core.process_algorithm_result(algo_result)

        self.assertAlmostEqual(result['energy'], self.reference_energy, places=6)