Ejemplo n.º 1
0
def get_pi_space_local_split(mol, mf, cas_norb, cas_nel):
    # {{{
    from pyscf import mcscf, mo_mapping, lo, ao2mo
    # find the 2pz orbitals using mo_mapping
    ao_labels = ['C 2pz']
    pop = mo_mapping.mo_comps(ao_labels, mol, mf.mo_coeff)
    cas_list = np.sort(
        pop.argsort()
        [-cas_norb:])  #take the 2z orbitals and resort in MO order
    print('Population for pz orbitals', pop[cas_list])
    mo_occ = np.where(mf.mo_occ > 0)[0]
    focc_list = list(set(mo_occ) - set(cas_list))

    mo_vir = np.where(mf.mo_occ == 0)[0]
    fvir_list = list(set(mo_vir) - set(cas_list))
    focc = len(focc_list)
    # localize the active space

    C = mf.mo_coeff
    ##### New stuff
    occ_l = cas_list[:cas_norb // 2]
    occ_v = cas_list[cas_norb // 2:]

    if 0:
        boys = lo.Boys(mol, mf.mo_coeff[:, occ_l])
        #boys.init_guess = None
        cl_a = boys.kernel()

        boys = lo.Boys(mol, mf.mo_coeff[:, occ_v])
        #boys.init_guess = None
        cl_b = boys.kernel()
    else:
        cl_a = lo.Boys(mol, mf.mo_coeff[:, occ_l]).kernel(verbose=4)
        cl_b = lo.Boys(mol, mf.mo_coeff[:, occ_v]).kernel(verbose=4)

    C[:, occ_l] = cl_a
    C[:, occ_v] = cl_b

    # reorder the orbitals to get docc,active,vir ordering  (Note:sort mo takes orbital ordering from 1)
    mycas = mcscf.CASCI(mf, cas_norb, cas_nel)
    C = mycas.sort_mo(cas_list + 1, mo_coeff=C)
    # Get the active space integrals and the frozen core energy
    h, ecore = mycas.get_h1eff(C)
    g = ao2mo.kernel(mol,
                     C[:, focc:focc + cas_norb],
                     aosym='s4',
                     compact=False).reshape(4 * ((cas_norb), ))
    C = C[:, focc:focc + cas_norb]  #only carrying the active sapce orbs
    return h, ecore, g, C
Ejemplo n.º 2
0
def build_iAO_basis(mol, Cf, Cf_core, Cf_vale, nfreeze):
    import numpy as np
    import scipy.linalg as sla
    S_f = mol.intor_symmetric('cint1e_ovlp_sph')
    nup = mol.nelectron // 2
    iao, Cf_core = build_iao(S_f,
                             Cf[:, :nup],
                             Cf_vale,
                             P_core=Cf_core,
                             nfreeze=nfreeze)
    # loc          = localizer.localizer(mol,iao,'boys')
    # loc.verbose  = 5
    # iao_loc      = loc.optimize (threshold=1.0e-5)
    # del loc
    iao_loc = lo.Boys(mol, iao).kernel()
    # need to find occupied orbitals orthogonal to core
    if (Cf_core is not None):
        Cf_x = project(Cf[:, :nup], S_f, Cf_core, 'out')
        return iao_loc, Cf_core, Cf_x
        #print("CFX shape", Cf_x.shape)
        exit()
    else:
        Cf_x = Cf[:, :nup]
        #print("CFX shape", Cf_x.shape)
        exit()
        return iao_loc, None, Cf_x
Ejemplo n.º 3
0
def loc_orbs(mol: gto.Mole, mo_coeff: Tuple[np.ndarray, np.ndarray], \
             s: np.ndarray, ref: str, variant: str) -> np.ndarray:
    """
        this function returns a set of localized MOs of a specific variant
        """
    # loop over spins
    for i, spin_mo in enumerate((mol.alpha, mol.beta)):

        if variant == 'fb':
            # foster-boys procedure
            loc = lo.Boys(mol, mo_coeff[i][:, spin_mo])
            loc.conv_tol = LOC_CONV
            # FB MOs
            mo_coeff[i][:, spin_mo] = loc.kernel()
        elif variant == 'pm':
            # pipek-mezey procedure
            loc = lo.PM(mol, mo_coeff[i][:, spin_mo])
            loc.conv_tol = LOC_CONV
            # PM MOs
            mo_coeff[i][:, spin_mo] = loc.kernel()
        elif 'ibo' in variant:
            # orthogonalized IAOs
            iao = lo.iao.iao(mol, mo_coeff[i][:, spin_mo])
            iao = lo.vec_lowdin(iao, s)
            # IBOs
            mo_coeff[i][:, spin_mo] = lo.ibo.ibo(mol, mo_coeff[i][:, spin_mo], iaos=iao, \
                                                 grad_tol = LOC_CONV, exponent=int(variant[-1]), verbose=0)
        # closed-shell reference
        if ref == 'restricted' and mol.spin == 0:
            mo_coeff[i + 1][:, spin_mo] = mo_coeff[i][:, spin_mo]
            break

    return mo_coeff
Ejemplo n.º 4
0
def get_pi_space(mol, mf, cas_norb, cas_nel, local=True, p3=False):
    # {{{
    from pyscf import mcscf, mo_mapping, lo, ao2mo
    # find the 2pz orbitals using mo_mapping
    ao_labels = ['C 2pz']

    # get the 3pz and 2pz orbitals
    if p3:
        ao_labels = ['C 2pz', 'C 3pz']
        cas_norb = 2 * cas_norb

    pop = mo_mapping.mo_comps(ao_labels, mol, mf.mo_coeff)
    cas_list = np.sort(
        pop.argsort()
        [-cas_norb:])  #take the 2z orbitals and resort in MO order
    print('Population for pz orbitals', pop[cas_list])
    mo_occ = np.where(mf.mo_occ > 0)[0]
    focc_list = list(set(mo_occ) - set(cas_list))
    focc = len(focc_list)

    # localize the active space
    if local:
        cl_a = lo.Boys(mol, mf.mo_coeff[:, cas_list]).kernel(verbose=4)
        C = mf.mo_coeff
        C[:, cas_list] = cl_a
    else:
        C = mf.mo_coeff
        mo_energy = mf.mo_energy[cas_list]
        J, K = mf.get_jk()
        K = K[cas_list, :][:, cas_list]
        print(K)

        if mol.symmetry == True:
            from pyscf import symm
            mo = symm.symmetrize_orb(mol, C[:, cas_list])
            osym = symm.label_orb_symm(mol, mol.irrep_name, mol.symm_orb, mo)
            #symm.addons.symmetrize_space(mol, mo, s=None, check=True, tol=1e-07)
            for i in range(len(osym)):
                print("%4d %8s %16.8f" % (i + 1, osym[i], mo_energy[i]))

    # reorder the orbitals to get docc,active,vir ordering  (Note:sort mo takes orbital ordering from 1)
    mycas = mcscf.CASCI(mf, cas_norb, cas_nel)
    C = mycas.sort_mo(cas_list + 1, mo_coeff=C)
    np.save('C.npy', C)

    # Get the active space integrals and the frozen core energy
    h, ecore = mycas.get_h1eff(C)
    g = ao2mo.kernel(mol,
                     C[:, focc:focc + cas_norb],
                     aosym='s4',
                     compact=False).reshape(4 * ((cas_norb), ))
    C = C[:, focc:focc + cas_norb]  #only carrying the active sapce orbs
    return h, ecore, g, C
Ejemplo n.º 5
0
def IAO_construction(mol, mf, nfreeze=0):
    rho = mf.make_rdm1()
    nb = mol.nao_nr()
    S = mf.get_ovlp()
    C_oc = mf.mo_coeff[:, mf.mo_occ > 0]
    C_vl = np.zeros((nb, nb))

    cs, cf = 0, 0
    if (type(mol.atom) != list):
        mol_atom = mol.atom.split(';')
        mol_atom = [list(x.split()) for x in mol_atom]
        mol_atom = [[x[0], (x[1], x[2], x[3])] for x in mol_atom]
    else:
        mol_atom = mol.atom
    for [a, x], (sh0, sh1, ao0, ao1) in zip(mol_atom, mol.offset_nr_by_atom()):
        pmol = gto.Mole()
        pmol.atom = [[a, (0.0, 0.0, 0.0)]]
        pmol.basis = mol.basis
        pmol.charge = 0
        pmol.verbose = 0
        pmol.spin = atomic_spins[a]
        pmol.symmetry = True
        pmol.build()
        pmf = scf.ROHF(pmol)
        pmf.kernel()
        C_vl_a = pmf.mo_coeff[:, :minimal_basis_size[a]]
        cf = cs + C_vl_a.shape[1]
        C_vl[ao0:ao1, cs:cf] = C_vl_a[:, :]
        cs = cf

    C_vl = C_vl[:, :cf]
    Px = orthonormalize(C_vl, S, 'orthonormalize')
    C_oc_p = project(Px, S, C_oc, 'along')

    M1 = projector(C_oc, S)
    M2 = projector(C_oc_p, S)
    IAO = np.dot(np.dot(M1, M2), Px) + np.dot(
        np.dot(np.eye(nb) - M1,
               np.eye(nb) - M2), Px)
    IAO = orthonormalize(IAO, S, 'orthonormalize')
    IAO = lo.Boys(mol, IAO).kernel()

    if (nfreeze > 0):
        C_freeze = C_oc[:, :nfreeze]
        IAO_unfrozen = project(IAO, S, C_freeze, 'outside')
        IAO[:, :nfreeze] = C_freeze[:, :]
        IAO[:, nfreeze:] = IAO_unfrozen[:, :]

    return IAO
Ejemplo n.º 6
0
from pyscf import lo
from pyscf.tools import molden

mol = gto.M(
    atom = '''
C    0.000000000000     1.398696930758     0.000000000000
C    0.000000000000    -1.398696930758     0.000000000000
C    1.211265339156     0.699329968382     0.000000000000
C    1.211265339156    -0.699329968382     0.000000000000
C   -1.211265339156     0.699329968382     0.000000000000
C   -1.211265339156    -0.699329968382     0.000000000000
H    0.000000000000     2.491406946734     0.000000000000
H    0.000000000000    -2.491406946734     0.000000000000
H    2.157597486829     1.245660462400     0.000000000000
H    2.157597486829    -1.245660462400     0.000000000000
H   -2.157597486829     1.245660462400     0.000000000000
H   -2.157597486829    -1.245660462400     0.000000000000''',
    basis = '6-31g')
mf = scf.RHF(mol).run()

pz_idx = numpy.array([17,20,21,22,23,30,36,41,42,47,48,49])-1
loc_orb = lo.Boys(mol, mf.mo_coeff[:,pz_idx]).kernel()
molden.from_mo(mol, 'boys.molden', loc_orb)

loc_orb = lo.ER(mol, mf.mo_coeff[:,pz_idx]).kernel()
molden.from_mo(mol, 'edmiston.molden', loc_orb)

loc_orb = lo.PM(mol, mf.mo_coeff[:,pz_idx]).kernel()
molden.from_mo(mol, 'pm.molden', loc_orb)

Ejemplo n.º 7
0
        Cocc = C[:,i].reshape(C.shape[0],1)
        temp = Cocc @ Cocc.T @ S   
        for m,lb in enumerate(mol.ao_labels()):
            print(lb)
            v1,v2,v3 = lb.split()
            print(v1)
            mulliken[int(v1),i] += temp[m,m]
    print(mulliken)
    return mulliken
# }}}

local = False
local = True
if local:
    cl_c = mf.mo_coeff[:, focc_list]
    cl_a = lo.Boys(mol, mf.mo_coeff[:, cas_list]).kernel(verbose=4)
    cl_v = mf.mo_coeff[:, fvir_list]
    C = np.column_stack((cl_c, cl_a, cl_v))
else:
    cl_c = mf.mo_coeff[:, focc_list]
    cl_a = mf.mo_coeff[:, cas_list]
    cl_v = mf.mo_coeff[:, fvir_list]
    C = np.column_stack((cl_c, cl_a, cl_v))

from pyscf import mo_mapping
s_pop = mo_mapping.mo_comps('C 2pz', mol, C)
print(s_pop)
cas_list = s_pop.argsort()[-cas_norb:]
print('cas_list', np.array(cas_list))
print('s population for active space orbitals', s_pop[cas_list])
focc_list = list(set(mo_occ)-set(cas_list))
Ejemplo n.º 8
0
    def init(self,molecule,charge,spin,basis_set,orb_basis='scf',cas=False,cas_nstart=None,cas_nstop=None,cas_nel=None,loc_nstart=None,loc_nstop=None,
            scf_conv_tol=1e-14):
    # {{{
        import pyscf
        from pyscf import gto, scf, ao2mo, molden, lo
        pyscf.lib.num_threads(1)  #with degenerate states and multiple processors there can be issues
        #PYSCF inputs
        print(" ---------------------------------------------------------")
        print("                      Using Pyscf:")
        print(" ---------------------------------------------------------")
        print("                                                          ")

        mol = gto.Mole()
        mol.atom = molecule

        mol.max_memory = 1000 # MB
        mol.symmetry = True
        mol.charge = charge
        mol.spin = spin
        mol.basis = basis_set
        mol.build()
        print("symmertry")
        print(mol.topgroup)

        #SCF 

        #mf = scf.RHF(mol).run(init_guess='atom')
        mf = scf.RHF(mol).run(conv_tol=scf_conv_tol)
        #C = mf.mo_coeff #MO coeffs
        enu = mf.energy_nuc()
        
        print(" SCF Total energy: %12.8f" %mf.e_tot) 
        print(" SCF Elec  energy: %12.8f" %(mf.e_tot-enu))
        print(mf.get_fock())
        print(np.linalg.eig(mf.get_fock())[0])
        
        if mol.symmetry == True:
            from pyscf import symm
            mo = symm.symmetrize_orb(mol, mf.mo_coeff)
            osym = symm.label_orb_symm(mol, mol.irrep_name, mol.symm_orb, mo)
            #symm.addons.symmetrize_space(mol, mo, s=None, check=True, tol=1e-07)
            for i in range(len(osym)):
                print("%4d %8s %16.8f"%(i+1,osym[i],mf.mo_energy[i]))

        #orbitals and lectrons
        n_orb = mol.nao_nr()
        n_b , n_a = mol.nelec 
        nel = n_a + n_b
        self.n_orb = mol.nao_nr()


        if cas == True:
            cas_norb = cas_nstop - cas_nstart
            from pyscf import mcscf
            assert(cas_nstart != None)
            assert(cas_nstop != None)
            assert(cas_nel != None)
        else:
            cas_nstart = 0
            cas_nstop = n_orb
            cas_nel = nel

        ##AO 2 MO Transformation: orb_basis or scf
        if orb_basis == 'scf':
            print("\nUsing Canonical Hartree Fock orbitals...\n")
            C = cp.deepcopy(mf.mo_coeff)
            print("C shape")
            print(C.shape)

        elif orb_basis == 'lowdin':
            assert(cas == False)
            S = mol.intor('int1e_ovlp_sph')
            print("Using lowdin orthogonalized orbitals")

            C = lowdin(S)
            #end

        elif orb_basis == 'boys':
            pyscf.lib.num_threads(1)  #with degenerate states and multiple processors there can be issues
            cl_c = mf.mo_coeff[:, :cas_nstart]
            cl_a = lo.Boys(mol, mf.mo_coeff[:, cas_nstart:cas_nstop]).kernel(verbose=4)
            cl_v = mf.mo_coeff[:, cas_nstop:]
            C = np.column_stack((cl_c, cl_a, cl_v))

        elif orb_basis == 'boys2':
            pyscf.lib.num_threads(1)  #with degenerate states and multiple processors there can be issues
            cl_c = mf.mo_coeff[:, :loc_nstart]
            cl_a = lo.Boys(mol, mf.mo_coeff[:, loc_nstart:loc_nstop]).kernel(verbose=4)
            cl_v = mf.mo_coeff[:, loc_nstop:]
            C = np.column_stack((cl_c, cl_a, cl_v))

        elif orb_basis == 'PM':
            pyscf.lib.num_threads(1)  #with degenerate states and multiple processors there can be issues
            cl_c = mf.mo_coeff[:, :cas_nstart]
            cl_a = lo.PM(mol, mf.mo_coeff[:, cas_nstart:cas_nstop]).kernel(verbose=4)
            cl_v = mf.mo_coeff[:, cas_nstop:]
            C = np.column_stack((cl_c, cl_a, cl_v))

        elif orb_basis == 'PM2':
            pyscf.lib.num_threads(1)  #with degenerate states and multiple processors there can be issues
            cl_c = mf.mo_coeff[:, :loc_nstart]
            cl_a = lo.PM(mol, mf.mo_coeff[:, loc_nstart:loc_nstop]).kernel(verbose=4)
            cl_v = mf.mo_coeff[:, loc_nstop:]
            C = np.column_stack((cl_c, cl_a, cl_v))

        elif orb_basis == 'ER':
            pyscf.lib.num_threads(1)  #with degenerate states and multiple processors there can be issues
            cl_c = mf.mo_coeff[:, :cas_nstart]
            cl_a = lo.PM(mol, mf.mo_coeff[:, cas_nstart:cas_nstop]).kernel(verbose=4)
            cl_v = mf.mo_coeff[:, cas_nstop:]
            C = np.column_stack((cl_c, cl_a, cl_v))

        elif orb_basis == 'ER2':
            pyscf.lib.num_threads(1)  #with degenerate states and multiple processors there can be issues
            cl_c = mf.mo_coeff[:, :loc_nstart]
            cl_a = lo.ER(mol, mf.mo_coeff[:, loc_nstart:loc_nstop]).kernel(verbose=4)
            cl_v = mf.mo_coeff[:, loc_nstop:]
            C = np.column_stack((cl_c, cl_a, cl_v))

        elif orb_basis == 'ibmo':
            loc_vstop =  loc_nstop - n_a
            print(loc_vstop)

            mo_occ = mf.mo_coeff[:,mf.mo_occ>0]
            mo_vir = mf.mo_coeff[:,mf.mo_occ==0]
            c_core = mo_occ[:,:loc_nstart]
            iao_occ = lo.iao.iao(mol, mo_occ[:,loc_nstart:])
            iao_vir = lo.iao.iao(mol, mo_vir[:,:loc_vstop])
            c_out  = mo_vir[:,loc_vstop:]

            # Orthogonalize IAO
            iao_occ = lo.vec_lowdin(iao_occ, mf.get_ovlp())
            iao_vir = lo.vec_lowdin(iao_vir, mf.get_ovlp())

            #
            # Method 1, using Knizia's alogrithm to localize IAO orbitals
            #
            '''
            Generate IBOS from orthogonal IAOs
            '''
            ibo_occ = lo.ibo.ibo(mol, mo_occ[:,loc_nstart:], iaos = iao_occ)
            ibo_vir = lo.ibo.ibo(mol, mo_vir[:,:loc_vstop], iaos = iao_vir)

            C = np.column_stack((c_core,ibo_occ,ibo_vir,c_out))

        else: 
            print("Error:NO orbital basis defined")

        molden.from_mo(mol, 'orbitals.molden', C)

        if cas == True:
            print(C.shape)
            print(cas_norb)
            print(cas_nel)
            mycas = mcscf.CASSCF(mf, cas_norb, cas_nel)
            h1e_cas, ecore = mycas.get_h1eff(mo_coeff = C)  #core core orbs to form ecore and eff
            h2e_cas = ao2mo.kernel(mol, C[:,cas_nstart:cas_nstop], aosym='s4',compact=False).reshape(4 * ((cas_norb), )) 
            print(h1e_cas)
            print(h1e_cas.shape)
            #return h1e_cas,h2e_cas,ecore,C,mol,mf
            self.h = h1e_cas
            self.g = h2e_cas
            self.ecore = ecore
            self.mf = mf
            self.mol = mol
            self.C = cp.deepcopy(C[:,cas_nstart:cas_nstop])
            J,K = mf.get_jk()
            self.J = self.C.T @ J @ self.C
            self.K = self.C.T @ J @ self.C

            #HF density
            if orb_basis == 'scf':
                #C = C[:,cas_nstart:cas_nstop]
                D = mf.make_rdm1(mo_coeff=C)
                S = mf.get_ovlp()
                sal, svec = np.linalg.eigh(S)
                idx = sal.argsort()[::-1]
                sal = sal[idx]
                svec = svec[:, idx]
                sal = sal**-0.5
                sal = np.diagflat(sal)
                X = svec @ sal @ svec.T
                C_ao2mo = np.linalg.inv(X) @ C
                Cocc = C_ao2mo[:, :n_a]
                D = Cocc @ Cocc.T
                DMO = C_ao2mo.T   @ D @ C_ao2mo
                
                #only for cas space 
                DMO = DMO[cas_nstart:cas_nstop,cas_nstart:cas_nstop]
                self.dm_aa = DMO
                self.dm_bb = DMO
                print("DENSITY")
                print(self.dm_aa.shape)

            if 0:
                h = C.T.dot(mf.get_hcore()).dot(C)
                g = ao2mo.kernel(mol,C,aosym='s4',compact=False).reshape(4*((n_orb),))
                const,heff = get_eff_for_casci(cas_nstart,cas_nstop,h,g)
                print(heff)
                print("const",const)
                print("ecore",ecore)
                
                idx = range(cas_nstart,cas_nstop)
                h = h[:,idx] 
                h = h[idx,:] 
                g = g[:,:,:,idx] 
                g = g[:,:,idx,:] 
                g = g[:,idx,:,:] 
                g = g[idx,:,:,:] 

                self.ecore = const
                self.h = h + heff
                self.g = g 


        elif cas==False:
            h = C.T.dot(mf.get_hcore()).dot(C)
            g = ao2mo.kernel(mol,C,aosym='s4',compact=False).reshape(4*((n_orb),))
            print(h)
            #return h, g, enu, C,mol,mf
            self.h = h
            self.g = g
            self.ecore = enu
            self.mf = mf
            self.mol = mol
            self.C = C
            J,K = mf.get_jk()
            self.J = self.C.T @ J @ self.C
            self.K = self.C.T @ J @ self.C

            #HF density
            if orb_basis == 'scf':
                D = mf.make_rdm1(mo_coeff=None)
                S = mf.get_ovlp()
                sal, svec = np.linalg.eigh(S)
                idx = sal.argsort()[::-1]
                sal = sal[idx]
                svec = svec[:, idx]
                sal = sal**-0.5
                sal = np.diagflat(sal)
                X = svec @ sal @ svec.T
                C_ao2mo = np.linalg.inv(X) @ C
                Cocc = C_ao2mo[:, :n_a]
                D = Cocc @ Cocc.T
                DMO = C_ao2mo.T   @ D @ C_ao2mo
                self.dm_aa = DMO
                self.dm_bb = DMO
                print("DENSITY")
                print(self.dm_aa)
Ejemplo n.º 9
0
        print("Find Fermi-Orbitals for spin: {0} / {1} electrons".format(
            _mys, te))
        #print("  total e: {0} (spin {1})".format(te,spin))
        #print("1s core: {0}".format(ne_1s))
        #print("valence: {0}".format(ve))

        # define which orbitals are use for initial boys
        pz_idx = np.arange(0, te)
        nfods = len(pz_idx)
        initial_fods = np.zeros((nfods, 3), dtype=np.float64)
        #print(pz_idx, len(pz_idx))

        #sys.exit()

        # build the localized orbitals
        loc_orb = lo.Boys(mol, m.mo_coeff[spin][:, pz_idx]).kernel()

        #print loc_orb.shape
        osym = 'X'
        if spin == 1:
            osym = 'He'
        for j in range(pz_idx.shape[0]):
            sstr = 'UP'
            if spin == 1:
                sstr = 'DN'
            print("  density fit for spin {0} orb #{1} ...".format(
                sstr, j + 1),
                  flush=True)
            #print("find initial fod: {0}".format(j))
            initial_fods[j, :] = lorb2fod(m,
                                          loc_orb[:, j],
Ejemplo n.º 10
0
def init_pyscf(molecule, charge, spin, basis, orbitals):
    # {{{
    #PYSCF inputs
    print(" ---------------------------------------------------------")
    print("                                                          ")
    print("                      Using Pyscf:")
    print("                                                          ")
    print(" ---------------------------------------------------------")
    print("                                                          ")
    mol = gto.Mole()
    mol.atom = molecule

    # this is needed to prevent openblas - openmp clash for some reason
    # todo: take out
    lib.num_threads(1)

    mol.max_memory = 1000  # MB
    mol.charge = charge
    mol.spin = spin
    mol.basis = basis
    mol.build()

    #orbitals and electrons
    n_orb = mol.nao_nr()
    n_b, n_a = mol.nelec
    nel = n_a + n_b

    #SCF
    mf = scf.RHF(mol).run()
    #mf = scf.ROHF(mol).run()
    C = mf.mo_coeff  #MO coeffs
    S = mf.get_ovlp()

    print(" Orbs1:")
    print(C)
    Cl = cp.deepcopy(C)
    if orbitals == "boys":
        print("\nUsing Boys localised orbitals:\n")
        cl_o = lo.Boys(mol, mf.mo_coeff[:, :n_a]).kernel(verbose=4)
        cl_v = lo.Boys(mol, mf.mo_coeff[:, n_a:]).kernel(verbose=4)
        Cl = np.column_stack((cl_o, cl_v))

    elif orbitals == "pipek":
        print("\nUsing Pipek-Mezey localised orbitals:\n")
        cl_o = lo.PM(mol, mf.mo_coeff[:, :n_a]).kernel(verbose=4)
        cl_v = lo.PM(mol, mf.mo_coeff[:, n_a:]).kernel(verbose=4)
        Cl = np.column_stack((cl_o, cl_v))
    elif orbitals == "edmiston":
        print("\nUsing Edmiston-Ruedenberg localised orbitals:\n")
        cl_o = lo.ER(mol, mf.mo_coeff[:, :n_a]).kernel(verbose=4)
        cl_v = lo.ER(mol, mf.mo_coeff[:, n_a:]).kernel(verbose=4)
        Cl = np.column_stack((cl_o, cl_v))
#    elif orbitals == "svd":
#        print("\nUsing SVD localised orbitals:\n")
#        cl_o = cp.deepcopy(mf.mo_coeff[:,:n_a])
#        cl_v = cp.deepcopy(mf.mo_coeff[:,n_a:])
#
#        [U,s,V] = np.linalg.svd(cl_o)
#        cl_o = cl_o.dot(V.T)
#        Cl = np.column_stack((cl_o,cl_v))
    elif orbitals == "canonical":
        print("\nUsing Canonical orbitals:\n")
        pass
    else:
        print("Error: Wrong orbital specification:")
        exit()

    print(" Overlap:")
    print(C.T.dot(S).dot(Cl))

    # sort by cluster
    blocks = [[0, 1, 2, 3], [4, 5, 6, 7]]
    O = Cl[:, :n_a]
    V = Cl[:, n_a:]
    [sorted_order, cluster_sizes] = mulliken_clustering(blocks, mol, O)
    O = O[:, sorted_order]
    [sorted_order, cluster_sizes] = mulliken_clustering(blocks, mol, V)
    V = V[:, sorted_order]
    Cl = np.column_stack((O, V))

    C = cp.deepcopy(Cl)
    # dump orbitals for viewing
    molden.from_mo(mol, 'orbitals_canon.molden', C)
    molden.from_mo(mol, 'orbitals_local.molden', Cl)

    ##READING INTEGRALS FROM PYSCF
    E_nu = gto.Mole.energy_nuc(mol)
    T = mol.intor('int1e_kin_sph')
    V = mol.intor('int1e_nuc_sph')
    hcore = T + V
    S = mol.intor('int1e_ovlp_sph')
    g = mol.intor('int2e_sph')

    print("\nSystem and Method:")
    print(mol.atom)

    print("Basis set                                      :%12s" % (mol.basis))
    print("Number of Orbitals                             :%10i" % (n_orb))
    print("Number of electrons                            :%10i" % (nel))
    print("Nuclear Repulsion                              :%16.10f " % E_nu)
    print("Electronic SCF energy                          :%16.10f " %
          (mf.e_tot - E_nu))
    print("SCF Energy                                     :%16.10f" %
          (mf.e_tot))

    print(" AO->MO")
    g = np.einsum("pqrs,pl->lqrs", g, C)
    g = np.einsum("lqrs,qm->lmrs", g, C)
    g = np.einsum("lmrs,rn->lmns", g, C)
    g = np.einsum("lmns,so->lmno", g, C)

    h = reduce(np.dot, (C.conj().T, hcore, C))

    #    #mf = mf.density_fit(auxbasis='weigend')
    #    #mf._eri = None
    #    mcc = cc.UCCSD(mf)
    #    eris = mcc.ao2mo()
    #    eris.g = g
    #    eris.focka = h
    #    eris.fockb = h
    #
    #    emp2, t1, t2 = mcc.init_amps(eris)
    #    exit()
    #    print(abs(t2).sum() - 4.9318753386922278)
    #    print(emp2 - -0.20401737899811551)
    #    t1, t2 = update_amps(mcc, t1, t2, eris)
    #    print(abs(t1).sum() - 0.046961325647584914)
    #    print(abs(t2).sum() - 5.378260578551683   )
    #
    #
    #    exit()

    return (n_orb, n_a, n_b, h, g, mol, E_nu, mf.e_tot, C, S)
Ejemplo n.º 11
0
    def hl_solver (self, chempot=0., threshold=1.0e-12):
#        energy = self.mol.energy_nuc()
        energy = 0.
        nelec  = 0.

        rdm_ao  = np.dot(self.cf, self.cf.T)
        AX_val  = np.dot(self.Sf, self.A_val)
        rdm_val = np.dot(AX_val.T, np.dot(rdm_ao, AX_val))

        print ( "shapes" )
        print ( "cf",self.cf.shape )
        print ( "rdm_ao",rdm_ao.shape )
        print ( "AX_val",AX_val.shape )
        print ( "rdm_val",rdm_val.shape )

        if(not self.parallel):
           myrange = range(self.nimp)
        else:
           from mpi4py import MPI
           comm = MPI.COMM_WORLD
           rank = MPI.COMM_WORLD.Get_rank()
           size = MPI.COMM_WORLD.Get_size()
           myrange = range(rank,rank+1)

        for i in myrange:
            # prepare orbital indexing
            imp_val   = np.zeros((self.nvl,), dtype=bool)
            imp_val_  = np.zeros((self.nvl,), dtype=bool)
            if self.nc > 0:
                imp_core  = np.zeros((self.nc,),  dtype=bool)
                imp_core_ = np.zeros((self.nc,),  dtype=bool)
            if self.nvt > 0:
                imp_virt  = np.zeros((self.nvt,), dtype=bool)
                imp_virt_ = np.zeros((self.nvt,), dtype=bool)
            for k in range(self.mol.natm):
                if self.imp_atx[i][k]:
                    imp_val[self.at_val == k]   = True
                    if self.nc > 0:
                        imp_core[self.at_core == k] = True
                    if self.nvt > 0:
                        imp_virt[self.at_virt == k] = True
                if self.imp_at[i][k]:
                    imp_val_[self.at_val == k]   = True
                    if self.nc > 0:
                        imp_core_[self.at_core == k] = True
                    if self.nvt > 0:
                        imp_virt_[self.at_virt == k] = True
            print("imp val", imp_val)

            # embedding
            cf_tmp, ncore, nact, ImpOrbs_x = \
                embedding.embedding (rdm_val, imp_val, \
                                     threshold=self.thresh, \
                                     transform_imp='hf')
            print("Doing EMBEDDING")
            print("cf_tmp", cf_tmp)
            print("ncore, nact", ncore, nact)
            print("ImpOrbs_x", ImpOrbs_x)
            cf_tmp = np.dot(self.A_val, cf_tmp)
            print("cf_tmp", cf_tmp)

            # localize imp+bath orbitals
            if self.method == 'dmrg':
                XR = np.random.rand(nact,nact)
                XR -= XR.T
                XS = sla.expm(0.01*XR)
                cf_ib = np.dot(cf_tmp[:,ncore:ncore+nact], XS)
                # loc = localizer.localizer (self.mol, cf_ib, 'boys')
                # loc.verbose = 5
                # cf_ib = loc.optimize(threshold=1.0e-5)
                # del loc
                cf_ib = lo.Boys(mol, cd_ib).kernel()

                R = np.dot(cf_ib.T, \
                           np.dot(self.Sf, cf_tmp[:,ncore:ncore+nact]))
                print ( np.allclose(np.dot(cf_tmp[:,ncore:ncore+nact], \
                                         ImpOrbs_x), \
                                  np.dot(cf_ib, np.dot(R, ImpOrbs_x))) )
                ImpOrbs_x = np.dot(R, ImpOrbs_x)
                cf_tmp[:,ncore:ncore+nact] = cf_ib
                print ( cf_ib )

            # prepare ImpOrbs
            ni_val = nact
            nj_val = np.count_nonzero(imp_val_)
            if self.nc > 0:
                ni_core = np.count_nonzero(imp_core)
                nj_core = np.count_nonzero(imp_core_)
            else:
                ni_core = nj_core = 0
            if self.nvt > 0:
                ni_virt = np.count_nonzero(imp_virt)
                nj_virt = np.count_nonzero(imp_virt_)
            else:
                ni_virt = nj_virt = 0

            ii = 0
            ImpOrbs = np.zeros((ni_val+ni_core+ni_virt,\
                                nj_val+nj_core+nj_virt,))
            if self.nc > 0:
                j = 0
                for i in range(self.nc):
                    if imp_core[i] and imp_core_[i]:
                        ImpOrbs[j,ii] = 1.
                        ii += 1
                    if imp_core[i]:
                        j += 1
            j = 0
            for i in range(self.nvl):
                if imp_val[i] and imp_val_[i]:
                    ImpOrbs[ni_core:ni_core+ni_val,ii] = ImpOrbs_x[:,j]
                    ii += 1
                if imp_val[i]:
                    j += 1
            if self.nvt > 0:
                j = 0
                for i in range(self.nvt):
                    if imp_virt[i] and imp_virt_[i]:
                        ImpOrbs[ni_core+ni_val+j,ii] = 1.
                        ii += 1
                    if imp_virt[i]:
                        j += 1

            # prepare orbitals
            cf_core = cf_virt = None
            if self.nc > 0:
                cf_core = self.A_core[:,imp_core]
            if self.nvt > 0:
                cf_virt = self.A_virt[:,imp_virt]
            cf_val = cf_tmp[:,ncore:ncore+nact]

            if cf_core is not None and cf_virt is not None:
                cf = np.hstack ((cf_core, cf_val, cf_virt,))
            elif cf_core is not None:
                cf = np.hstack ((cf_core, cf_val,))
            elif cf_virt is not None:
                cf = np.hstack ((cf_val, cf_virt,))
            else:
                cf = cf_val

            # prepare core
            if self.nc > 0:
                Ac_ = self.A_core[:,~(imp_core)]
                X_core = np.hstack((Ac_, cf_tmp[:,:ncore],))
            else:
                X_core = cf_tmp[:,:ncore]

            n_orth = cf.shape[1]
            if cf_virt is not None:
                n_orth -= cf_virt.shape[1]
            print("x-core", X_core)
            print("cf b4 solver", cf)
            print("imporbs", ImpOrbs)

            if self.method == 'hf':
                nel_, en_ = \
                    pyscf_hf.solve (self.mol, \
                                2*(self.nup-X_core.shape[1]), \
                                X_core, cf, ImpOrbs, chempot=chempot, \
                                n_orth=n_orth)

            elif self.method == 'cc':
                nel_, en_ = \
                    pyscf_cc.solve (self.mol, \
                                2*(self.nup-X_core.shape[1]), \
                                X_core, cf, ImpOrbs, chempot=chempot, \
                                n_orth=n_orth,FrozenPot=self.FrozenPot)

            elif self.method == 'ccsd(t)':
                nel_, en_ = \
                    pyscf_ccsdt.solve (self.mol, \
                                2*(self.nup-X_core.shape[1]), \
                                X_core, cf, ImpOrbs, chempot=chempot, \
                                n_orth=n_orth)

            elif self.method == 'mp2':
                nel_, en_ = \
                    pyscf_mp2.solve (self.mol, \
                                2*(self.nup-X_core.shape[1]), \
                                X_core, cf, ImpOrbs, chempot=chempot, \
                                n_orth=n_orth,FrozenPot=self.FrozenPot)


            elif self.method == 'dfmp2':
                nel_, en_ = \
                    pyscf_dfmp2.solve (self.mol, \
                                2*(self.nup-X_core.shape[1]), \
                                X_core, cf, ImpOrbs, chempot=chempot, \
                                n_orth=n_orth,FrozenPot=self.FrozenPot, mf_tot=self.mf_tot)

            elif self.method == 'dfmp2_testing':
                nel_, en_ = \
                    dfmp2_testing.solve (self.mol, \
                                2*(self.nup-X_core.shape[1]), \
                                X_core, cf, ImpOrbs, chempot=chempot, \
                                n_orth=n_orth,FrozenPot=self.FrozenPot, mf_tot=self.mf_tot)

            elif self.method == 'dfmp2_testing2':
                # print(self.mol)
                # print(2*(self.nup-X_core.shape[1]))
                # print(X_core.shape)
                # print(cf.shape)
                # print(ImpOrbs.shape)
                # print(n_orth)
                nel_, en_ = \
                    dfmp2_testing2.solve (self.mol, \
                                2*(self.nup-X_core.shape[1]), \
                                X_core, cf, ImpOrbs, chempot=chempot, \
                                n_orth=n_orth,FrozenPot=self.FrozenPot ) #, mf_tot=self.mf_tot)

            elif self.method == 'dfmp2_testing3':
                nel_, en_ = \
                    dfmp2_testing3.solve (self.mol, \
                                2*(self.nup-X_core.shape[1]), \
                                X_core, cf, ImpOrbs, chempot=chempot, \
                                n_orth=n_orth,FrozenPot=self.FrozenPot, mf_tot=self.mf_tot)

            elif self.method == 'dfmp2_testing4':
                nel_, en_ = \
                    dfmp2_testing4.solve (self.mol, \
                                2*(self.nup-X_core.shape[1]), \
                                X_core, cf, ImpOrbs, chempot=chempot, \
                                n_orth=n_orth,FrozenPot=self.FrozenPot, mf_tot=self.mf_tot)


            elif self.method == 'fci':
                nel_, en_ = \
                    pyscf_fci.solve (self.mol, \
                                2*(self.nup-X_core.shape[1]), \
                                X_core, cf, ImpOrbs, chempot=chempot, \
                                n_orth=n_orth)

            elif self.method == 'dmrg':
                nel_, en_ = \
                    dmrg.solve (self.mol, \
                                2*(self.nup-X_core.shape[1]), \
                                X_core, cf, ImpOrbs, chempot=chempot, \
                                n_orth=n_orth)

            nelec  += nel_
            energy += en_

        if(self.parallel):
           nelec_tot  = comm.reduce(nelec, op=MPI.SUM,root=0)
           energy_tot = comm.reduce(energy,op=MPI.SUM,root=0)
           if(rank==0):
              energy_tot    += self.mol.energy_nuc()+self.e_core
           nelec  = comm.bcast(nelec_tot, root=0)
           energy = comm.bcast(energy_tot,root=0)
           comm.barrier()
           if(rank==0): print ( 'DMET energy = ', energy )
        else:
           energy+=self.mol.energy_nuc()+self.e_core
           print ( 'DMET energy = ', energy )

        return nelec
Ejemplo n.º 12
0
#!/usr/bin/env python

import numpy
from pyscf import scf, gto, lo
from pyscf.tools import molden

mol = gto.Mole()
mol.basis = 'cc-pvdz'
mol.atom = '''
O
H 1 1.1
H 1 1.1 2 104
'''
mol.charge = 0
mol.spin = 0
mol.symmetry = 1
mol.verbose = 4
mol.build()

mf = scf.RHF(mol)
mf.kernel()

occ = mf.mo_coeff[:,mf.mo_occ>0]
vir = mf.mo_coeff[:,mf.mo_occ==0]

loc_occ = lo.ER(mol, occ).kernel()
loc_vir = lo.Boys(mol, vir).kernel()