<jupyter_start><jupyter_text>_*H2 energy with various RY and RYRZ variational forms*_This notebook demonstrates using Qiskit Chemistry to plot graphs of the ground state energy of the Hydrogen (H2) molecule using VQE with different variation form configurations. The results are compared to the same energy as computed by the ExactEigensolver This notebook has been written to use the PYSCF chemistry driver.<jupyter_code>import numpy as np
import pylab
from qiskit import BasicAer
from qiskit.aqua import aqua_globals, QuantumInstance
from qiskit.aqua.algorithms import ExactEigensolver, VQE
from qiskit.aqua.components.optimizers import COBYLA
from qiskit.aqua.components.variational_forms import RYRZ, RY
from qiskit.aqua.components.initial_states import Zero
from qiskit.chemistry.drivers import PySCFDriver
from qiskit.chemistry.core import Hamiltonian, QubitMappingType

var_forms = [RYRZ, RY]
entanglements = ['full', 'linear']
depths = [x for x in range(3, 11)]

energies = np.empty([len(var_forms), len(entanglements), len(depths)])
hf_energy = None
energy = None
eval_counts = np.empty([len(var_forms), len(entanglements), len(depths)])

aqua_globals.random_seed = 50

driver = PySCFDriver('H .0 .0 -0.3625; H .0 .0 0.3625', basis='sto3g')
qmolecule = driver.run()
operator =  Hamiltonian(qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False)
qubit_op, aux_ops = operator.run(qmolecule)
result = ExactEigensolver(qubit_op).run()
lines, result = operator.process_algorithm_result(result)
    
hf_energy = result['hf_energy']
energy = result['energy']
print('Hartree-Fock energy:', hf_energy)
print('FCI energy:', energy)<jupyter_output>Couldn't find cython int routine
Couldn't find cython int routine
Hartree-Fock energy: -1.1173432691225826
FCI energy: -1.1372213770723036<jupyter_text>With a reference FCI energy computed from ExactEigensolver we now compute the ground state energy with VQE and different variational form setups<jupyter_code>print('Processing step __', end='')
for i, d in enumerate(depths):
    print('\b\b{:2d}'.format(i), end='', flush=True)
    for j in range(len(entanglements)):
        for k in range(len(var_forms)):
            variational_form_cls = var_forms[k] 
        
            driver = PySCFDriver('H .0 .0 -0.3625; H .0 .0 0.3625', basis='sto3g')
            qmolecule = driver.run()
            operator =  Hamiltonian(qubit_mapping=QubitMappingType.JORDAN_WIGNER, two_qubit_reduction=False)
            qubit_op, aux_ops = operator.run(qmolecule)
            optimizer = COBYLA(maxiter=10000)
            initial_state = Zero(qubit_op.num_qubits)
            var_form = variational_form_cls(qubit_op.num_qubits, depth=d, entanglement=entanglements[j])
            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))
            lines, result = operator.process_algorithm_result(result)

            energies[k][j][i] = result['energy']
            eval_counts[k][j][i] = result['algorithm_retvals']['eval_count']
print(' --- complete')

print('Depths: ', depths)
print('Energies:', energies)
print('Num evaluations:', eval_counts)
for k in range(len(var_forms)):
    for j in range(len(entanglements)):
        pylab.plot(depths, energies[k][j]-energy, label=var_forms[k].__name__+' + '+entanglements[j])
pylab.xlabel('Variational form depth')
pylab.ylabel('Energy difference')
pylab.yscale('log')
pylab.title('H2 Ground State Energy Difference from Reference')
pylab.legend(loc='upper right');<jupyter_output><empty_output><jupyter_text>The above plot shows how close the ground state energy result from VQE was to the reference. The next plot shows how many evaluations (calls to the objective/cost function) were needed by the optimizer before it stopped and returned. Note that the optimzer was configured with a maximum number of iterations of 10,000. The COBYLA optimizer makes one evaluation per iteration and it can be seen that for some points that the iteration limit was reached which caused the optimizer to return.<jupyter_code>for k in range(len(var_forms)):
    for j in range(len(entanglements)):
        pylab.plot(depths, eval_counts[k][j], '-o', label=var_forms[k].__name__+' + '+entanglements[j])
pylab.xlabel('Variational form depth')
pylab.ylabel('Evaluations')
pylab.title('VQE number of evaluations')
pylab.legend(loc='upper right');<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1024411508282476, 'fraction_numerical': 0.018090671316477767, 'mean_word_length': 4.779596977329975, 'pattern_counts': {'":': 0, '<': 12, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '166145', 'license': 'Apache-2.0', 'n_tokens_mistral': 1544, 'n_tokens_neox': 1465, 'n_words': 395, 'path': 'chemistry/h2_var_forms.ipynb', 'repo_name': 'ajrazander/qiskit-community-tutorials', 'size': '4588'}