Exemplo n.º 1
0
def ucc(geometry,
        basis="sto-3g",
        multiplicity=1,
        charge=1,
        theta_thresh=1e-7,
        pool=operator_pools.singlet_GSD(),
        spin_adapt=True,
        psi4_filename="psi4_%12.12f" % random.random()):
    # {{{

    molecule = openfermion.hamiltonians.MolecularData(geometry, basis,
                                                      multiplicity)
    molecule.filename = psi4_filename
    molecule = openfermionpsi4.run_psi4(molecule,
                                        run_scf=1,
                                        run_mp2=1,
                                        run_cisd=0,
                                        run_ccsd=0,
                                        run_fci=1,
                                        delete_input=1)
    pool.init(molecule)
    print(" Basis: ", basis)

    print(' HF energy      %20.16f au' % (molecule.hf_energy))
    print(' MP2 energy     %20.16f au' % (molecule.mp2_energy))
    #print(' CISD energy    %20.16f au' %(molecule.cisd_energy))
    #print(' CCSD energy    %20.16f au' %(molecule.ccsd_energy))
    print(' FCI energy     %20.16f au' % (molecule.fci_energy))

    #Build p-h reference and map it to JW transform
    reference_ket = scipy.sparse.csc_matrix(
        openfermion.jw_configuration_state(
            list(range(0, molecule.n_electrons)),
            molecule.n_qubits)).transpose()
    reference_bra = reference_ket.transpose().conj()

    #JW transform Hamiltonian computed classically with OFPsi4
    hamiltonian_op = molecule.get_molecular_hamiltonian()
    hamiltonian = openfermion.transforms.get_sparse_operator(hamiltonian_op)

    #Thetas
    parameters = [0] * pool.n_ops

    pool.generate_SparseMatrix()

    ucc = UCC(hamiltonian, pool.spmat_ops, reference_ket, parameters)

    opt_result = scipy.optimize.minimize(ucc.energy,
                                         parameters,
                                         options={
                                             'gtol': 1e-6,
                                             'disp': True
                                         },
                                         method='BFGS',
                                         callback=ucc.callback)
    print(" Finished: %20.12f" % ucc.curr_energy)
    parameters = opt_result['x']
    for p in parameters:
        print(p)
Exemplo n.º 2
0
import vqe_methods 
import operator_pools

import sys

r = 2.684
geometry = [('H',   (0,0,-r)), 
            ('Be',  (0,0,0)), 
            ('H',   (0,0,r))]


filename = "beh2_r2684_random04_gsd.out"

sys.stdout = open(filename, 'w')

vqe_methods.test_random(geometry,pool = operator_pools.singlet_GSD(), seed=4)
Exemplo n.º 3
0
def test():
    r = 1.5
    geometry = [('H', (0, 0, 1 * r)), ('H', (0, 0, 2 * r)),
                ('H', (0, 0, 3 * r)), ('H', (0, 0, 4 * r)),
                ('H', (0, 0, 5 * r)), ('H', (0, 0, 6 * r))]

    charge = 0
    spin = 0
    basis = 'sto-3g'

    [n_orb, n_a, n_b, h, g, mol, E_nuc, E_scf, C,
     S] = pyscf_helper.init(geometry, charge, spin, basis)

    print(" n_orb: %4i" % n_orb)
    print(" n_a  : %4i" % n_a)
    print(" n_b  : %4i" % n_b)

    sq_ham = pyscf_helper.SQ_Hamiltonian()
    sq_ham.init(h, g, C, S)
    print(" HF Energy: %12.8f" %
          (E_nuc + sq_ham.energy_of_determinant(range(n_a), range(n_b))))

    fermi_ham = sq_ham.export_FermionOperator()

    hamiltonian = openfermion.transforms.get_sparse_operator(fermi_ham)

    s2 = vqe_methods.Make_S2(n_orb)

    #build reference configuration
    occupied_list = []
    for i in range(n_a):
        occupied_list.append(i * 2)
    for i in range(n_b):
        occupied_list.append(i * 2 + 1)

    print(
        " Build reference state with %4i alpha and %4i beta electrons" %
        (n_a, n_b), occupied_list)
    reference_ket = scipy.sparse.csc_matrix(
        openfermion.jw_configuration_state(occupied_list,
                                           2 * n_orb)).transpose()

    [e, v] = scipy.sparse.linalg.eigsh(hamiltonian.real,
                                       1,
                                       which='SA',
                                       v0=reference_ket.todense())
    for ei in range(len(e)):
        S2 = v[:, ei].conj().T.dot(s2.dot(v[:, ei]))
        print(" State %4i: %12.8f au  <S2>: %12.8f" % (ei, e[ei] + E_nuc, S2))

    fermi_ham += FermionOperator((), E_nuc)
    pyscf.molden.from_mo(mol, "full.molden", sq_ham.C)

    #   Francesco, change this to singlet_GSD() if you want generalized singles and doubles
    pool = operator_pools.singlet_GSD()
    pool.init(n_orb,
              n_occ_a=n_a,
              n_occ_b=n_b,
              n_vir_a=n_orb - n_a,
              n_vir_b=n_orb - n_b)

    [e, v, params] = vqe_methods.adapt_vqe(fermi_ham,
                                           pool,
                                           reference_ket,
                                           theta_thresh=1e-9)

    print(" Final ADAPT-VQE energy: %12.8f" % e)
    print(" <S^2> of final state  : %12.8f" %
          (v.conj().T.dot(s2.dot(v))[0, 0].real))
Exemplo n.º 4
0
def test_lexical(geometry,
                 basis="sto-3g",
                 multiplicity=1,
                 charge=1,
                 adapt_conver='norm',
                 adapt_thresh=1e-3,
                 theta_thresh=1e-7,
                 adapt_maxiter=200,
                 pool=operator_pools.singlet_GSD(),
                 spin_adapt=True,
                 psi4_filename="psi4_%12.12f" % random.random()):
    # {{{

    molecule = openfermion.hamiltonians.MolecularData(geometry, basis,
                                                      multiplicity)
    molecule.filename = psi4_filename
    molecule = openfermionpsi4.run_psi4(molecule,
                                        run_scf=1,
                                        run_mp2=1,
                                        run_cisd=0,
                                        run_ccsd=0,
                                        run_fci=1,
                                        delete_input=1)
    pool.init(molecule)
    print(" Basis: ", basis)

    print(' HF energy      %20.16f au' % (molecule.hf_energy))
    print(' MP2 energy     %20.16f au' % (molecule.mp2_energy))
    #print(' CISD energy    %20.16f au' %(molecule.cisd_energy))
    #print(' CCSD energy    %20.16f au' %(molecule.ccsd_energy))
    print(' FCI energy     %20.16f au' % (molecule.fci_energy))

    #Build p-h reference and map it to JW transform
    reference_ket = scipy.sparse.csc_matrix(
        openfermion.jw_configuration_state(
            list(range(0, molecule.n_electrons)),
            molecule.n_qubits)).transpose()
    reference_bra = reference_ket.transpose().conj()

    #JW transform Hamiltonian computed classically with OFPsi4
    hamiltonian_op = molecule.get_molecular_hamiltonian()
    hamiltonian = openfermion.transforms.get_sparse_operator(hamiltonian_op)

    #Thetas
    parameters = []

    pool.generate_SparseMatrix()

    ansatz_ops = []  #SQ operator strings in the ansatz
    ansatz_mat = []  #Sparse Matrices for operators in ansatz

    print(" Start ADAPT-VQE algorithm")
    op_indices = []
    parameters = []
    curr_state = 1.0 * reference_ket

    print(" Now start to grow the ansatz")
    for n_iter in range(0, adapt_maxiter):

        print("\n\n\n")
        print(
            " --------------------------------------------------------------------------"
        )
        print("                         ADAPT-VQE iteration: ", n_iter)
        print(
            " --------------------------------------------------------------------------"
        )
        next_index = None
        next_deriv = 0
        curr_norm = 0

        print(" Check each new operator for coupling")
        next_term = []
        print(" Measure commutators:")
        sig = hamiltonian.dot(curr_state)
        for op_trial in range(pool.n_ops):

            opA = pool.spmat_ops[op_trial]
            com = 2 * (curr_state.transpose().conj().dot(opA.dot(sig))).real
            assert (com.shape == (1, 1))
            com = com[0, 0]
            assert (np.isclose(com.imag, 0))
            com = com.real
            opstring = ""
            for t in pool.fermi_ops[op_trial].terms:
                opstring += str(t)
                break

            if abs(com) > adapt_thresh:
                print(" %4i %40s %12.8f" % (op_trial, opstring, com))

            curr_norm += com * com
            if abs(com) > abs(next_deriv):
                next_deriv = com
                next_index = op_trial

        next_index = n_iter % pool.n_ops
        curr_norm = np.sqrt(curr_norm)

        min_options = {'gtol': theta_thresh, 'disp': False}

        max_of_com = next_deriv
        print(" Norm of <[A,H]> = %12.8f" % curr_norm)
        print(" Max  of <[A,H]> = %12.8f" % max_of_com)

        converged = False
        if adapt_conver == "norm":
            if curr_norm < adapt_thresh:
                converged = True
        else:
            print(" FAIL: Convergence criterion not defined")
            exit()

        if converged:
            print(" Ansatz Growth Converged!")
            print(" Number of operators in ansatz: ", len(ansatz_ops))
            print(" *Finished: %20.12f" % trial_model.curr_energy)
            print(" -----------Final ansatz----------- ")
            print(" %4s %40s %12s" % ("#", "Term", "Coeff"))
            for si in range(len(ansatz_ops)):
                s = ansatz_ops[si]
                opstring = ""
                for t in s.terms:
                    opstring += str(t)
                    break
                print(" %4i %40s %12.8f" % (si, opstring, parameters[si]))
            break

        print(" Add operator %4i" % next_index)
        parameters.insert(0, 0)
        ansatz_ops.insert(0, pool.fermi_ops[next_index])
        ansatz_mat.insert(0, pool.spmat_ops[next_index])

        trial_model = tUCCSD(hamiltonian, ansatz_mat, reference_ket,
                             parameters)

        opt_result = scipy.optimize.minimize(trial_model.energy,
                                             parameters,
                                             jac=trial_model.gradient,
                                             options=min_options,
                                             method='BFGS',
                                             callback=trial_model.callback)

        parameters = list(opt_result['x'])
        curr_state = trial_model.prepare_state(parameters)
        print(" Finished: %20.12f" % trial_model.curr_energy)
        print(" -----------New ansatz----------- ")
        print(" %4s %40s %12s" % ("#", "Term", "Coeff"))
        for si in range(len(ansatz_ops)):
            s = ansatz_ops[si]
            opstring = ""
            for t in s.terms:
                opstring += str(t)
                break
            print(" %4i %40s %12.8f" % (si, opstring, parameters[si]))

    return
Exemplo n.º 5
0
print("Beta Orbs :", beta_orbs)

n_alpha = molecule.get_n_alpha_electrons()
n_beta = molecule.get_n_beta_electrons()

alpha_occ = alpha_orbs[0:n_alpha]
alpha_vir = alpha_orbs[n_alpha::]
beta_occ = beta_orbs[0:n_beta]
beta_vir = beta_orbs[n_beta::]

print(alpha_occ, alpha_vir)
print(beta_occ, beta_vir)

#pool = operator_pools.singlet_SD(2,2)
#pool = operator_pools.singlet_SD()
pool = operator_pools.singlet_GSD()
pool.init(molecule)
'''
Count t2 second-quantized operations, add a parameter for each one, and add each one to the list
'''
#ansatz_type = "pqrs"
#ansatz_type = "ijab"
#ansatz_type = "pqrs_spinfree"
#ansatz_type = "ijab_spinfree"

ansatz_type = args['ansatz']

n_spat_orbs = int(n_spinorbitals / 2)

if ansatz_type == "ijab":
    for i in alpha_occ:
Exemplo n.º 6
0
import vqe_methods 
import operator_pools

import sys

r = 2.684
geometry = [('H',   (0,0,-r)), 
            ('Be',  (0,0,0)), 
            ('H',   (0,0,r))]


filename = "beh2_r2684_lex_gsd.out"

sys.stdout = open(filename, 'w')

vqe_methods.test_lexical(geometry,pool = operator_pools.singlet_GSD())