Example #1
0
 def molden(self,mo_coeff,fname='mocoeff'):
    print '\n[iface.molden] dump MOcoeff into file = '+fname+'.molden'   
    from pyscf.tools import molden
    with open(fname+'.molden','w') as thefile:
       molden.header(self.mol,thefile)
       molden.orbital_coeff(self.mol,thefile,mo_coeff,symm=['A']*mo_coeff.shape[1])
    return 0 	 
Example #2
0
 def dump_bath_orbs( self, filename, impnumber=0 ):
     
     import qcdmet_paths
     from pyscf import tools
     from pyscf.tools import molden
     with open( filename, 'w' ) as thefile:
         molden.header( self.ints.mol, thefile )
         molden.orbital_coeff( self.ints.mol, thefile, np.dot( self.ints.ao2loc, self.dmetOrbs[impnumber] ) )
Example #3
0
 def dump_bath_orbs( self, filename, impnumber=0 ):
     
     import qcdmet_paths
     from pyscf import tools
     from pyscf.tools import molden
     with open( filename, 'w' ) as thefile:
         molden.header( self.ints.mol, thefile )
         molden.orbital_coeff( self.ints.mol, thefile, np.dot( self.ints.ao2loc, self.dmetOrbs[impnumber] ) )
Example #4
0
def dumpLMO(mol,fname,lmo):
   print 'Dump into '+fname+'.h5'
   f = h5py.File(fname+'.h5','w')
   f.create_dataset("lmo",data=lmo)
   f.close()
   print 'Dump into '+fname+'_lmo.molden'
   with open(fname+'_lmo.molden','w') as thefile:
       molden.header(mol,thefile)
       molden.orbital_coeff(mol,thefile,lmo)
   return 0
Example #5
0
def dumpLMO(mol,fname,lmo):
   print 'Dump into '+fname+'.h5'
   f = h5py.File(fname+'.h5','w')
   f.create_dataset("lmo",data=lmo)
   f.close()
   print 'Dump into '+fname+'_lmo.molden'
   with open(fname+'_lmo.molden','w') as thefile:
       molden.header(mol,thefile)
       molden.orbital_coeff(mol,thefile,lmo)
   return 0
Example #6
0
    def submo_molden(self, mo_coeff, mo_occ, loc2sub, filename, mol=None):

        if mol is None: mol = self.mol

        dim = mo_coeff.shape[0]
        mo_loc = np.dot(loc2sub[:, :dim], mo_coeff)
        transfo = np.dot(self.ao2loc, mo_loc)
        with open(filename, 'w') as thefile:
            molden.header(mol, thefile)
            molden.orbital_coeff(mol, thefile, transfo, occ=mo_occ)
Example #7
0
    def dump_molden(self, filename, orbital_coeff):
        r'''Create a molden file to inspect a set of orbitals

        Args:
            filename : Filename of the molden file
            orbital_coeff: Set of orthonormal orbitals, expressed in terms of the AO, for which a molden file should be created
        '''

        with open(filename, 'w') as thefile:
            molden.header(self.themol, thefile)
            molden.orbital_coeff(self.themol, thefile, orbital_coeff)
Example #8
0
    def dump_molden( self, filename, orbital_coeff ):
        r'''Create a molden file to inspect a set of orbitals

        Args:
            filename : Filename of the molden file
            orbital_coeff: Set of orthonormal orbitals, expressed in terms of the AO, for which a molden file should be created
        '''

        with open( filename, 'w' ) as thefile:
            molden.header( self.themol, thefile )
            molden.orbital_coeff( self.themol, thefile, orbital_coeff )
Example #9
0
    def make_frozen_orbs(self, norb=None):

        mf = self.mf_full
        mol = mf.mol
        loc_method = self.loc_method
        pop_method = self.pop_method
        pm_exponent = self.pm_exponent

        if (norb is None):
            norb = mol.nelectron // 2

        mo_lo = None
        if (loc_method.upper() == 'PM'):
            pm = lo.pipek.PM(mol)
            pm.pop_method = pop_method
            pm.exponent = pm_exponent
            mo_lo = pm.kernel(mf.mo_coeff[:, :norb], verbose=4)
        elif (loc_method.upper() == 'BOYS'):
            boys = lo.boys.Boys(mol)
            mo_lo = boys.kernel(mf.mo_coeff[:, :norb], verbose=4)
        else:
            raise NotImplementedError('loc_method %s' % loc_method)

        s = mol.intor_symmetric('int1e_ovlp')
        nbas = mol.nao_nr()
        dm_lo = np.empty((norb, nbas, nbas))
        for i in range(norb):
            dm_lo[i] = np.outer(mo_lo[:, i], mo_lo[:, i])

        pop = np.zeros((norb))
        for i in range(norb):
            for iatom, (b0, b1, p0, p1) in enumerate(mol.offset_nr_by_atom()):
                if (self.env[iatom] == 1):
                    pop[i] += np.trace(np.dot(dm_lo[i, p0:p1, :], s[:, p0:p1]))

        #tools.VecPrint(pop,"Mulliken popupaltion")

        ind = np.argsort(-pop)
        pop = pop[ind]
        mo_lo[:, :norb] = mo_lo[:, ind]

        tools.VecPrint(pop,
                       "sorted Mulliken popupaltion: 1.0 for fully occupied")
        with open('mo_lo.molden', 'w') as thefile:
            molden.header(mol, thefile)
            molden.orbital_coeff(mol, thefile, mo_lo)

        self.mo_lo = mo_lo
        self.pop_lo = pop

        return (mo_lo, pop)
Example #10
0
    
name = 'ceo'
atm = [0,1]
mol = lib.chkfile.load_mol(name+'.chk')
mo_coeff = lib.chkfile.load(name+'.chk', 'scf/mo_coeff')
nmo = mol.nelectron//2
mo_coeff = mo_coeff[:,0:nmo]

with h5py.File(name+'.chk.h5') as f:
    idx = 'ovlp'+str(atm[0])
    aom1 = f[idx+'/aom'].value
    idx = 'ovlp'+str(atm[1])
    aom2 = f[idx+'/aom'].value

delta = 4*numpy.einsum('ij,ji->', aom1, aom2)
log.info('Delta %f for pair %d %d' %  (delta, atm[0], atm[1]))

dab = 4*numpy.einsum('ik,kj->ij', aom1, aom2)
dba = 4*numpy.einsum('ik,kj->ij', aom2, aom1)
d2c = (dab+dba)/2.0

from pyscf.tools import molden
natocc, natorb = numpy.linalg.eigh(d2c)
log.info('Occ for NADO %s', natocc)
log.info('Sum Occ for NADO %f', natocc.sum())
natorb = numpy.dot(mo_coeff, natorb)
with open(name+'_'+str(atm[0])+'-'+str(atm[1])+'_2c.molden', 'w') as f1:
    molden.header(mol, f1)
    molden.orbital_coeff(mol, f1, natorb, occ=natocc)

Example #11
0
def dumpLUNO(fname, thresh=0.01):
    chkfile = fname + '.chk'
    outfile = fname + '_cmo.molden'
    tools.molden.from_chkfile(outfile, chkfile)
    #=============================
    # Natural orbitals
    # Lowdin basis X=S{-1/2}
    # psi = chi * C
    #     = chi' * C'
    #     = chi*X*(X{-1}C')
    #=============================
    mol, mf = scf.chkfile.load_scf(chkfile)
    mo_coeff = mf["mo_coeff"]
    ova = mol.intor_symmetric("cint1e_ovlp_sph")
    nb = mo_coeff.shape[1]
    # Check overlap
    diff = reduce(numpy.dot,
                  (mo_coeff[0].T, ova, mo_coeff[0])) - numpy.identity(nb)
    print numpy.linalg.norm(diff)
    diff = reduce(numpy.dot,
                  (mo_coeff[1].T, ova, mo_coeff[1])) - numpy.identity(nb)
    print numpy.linalg.norm(diff)
    # UHF-alpha/beta
    ma = mo_coeff[0]
    mb = mo_coeff[1]
    nalpha = (mol.nelectron + mol.spin) / 2
    nbeta = (mol.nelectron - mol.spin) / 2
    # Spin-averaged DM
    pTa = numpy.dot(ma[:, :nalpha], ma[:, :nalpha].T)
    pTb = numpy.dot(mb[:, :nbeta], mb[:, :nbeta].T)
    pT = 0.5 * (pTa + pTb)
    # Lowdin basis
    s12 = sqrtm(ova)
    s12inv = lowdin(ova)
    pTOAO = reduce(numpy.dot, (s12, pT, s12))
    eig, coeff = scipy.linalg.eigh(-pTOAO)
    eig = -2.0 * eig
    eig[eig < 0.0] = 0.0
    eig[abs(eig) < 1.e-14] = 0.0
    ifplot = False  #True
    if ifplot:
        import matplotlib.pyplot as plt
        plt.plot(range(nb), eig, 'ro')
        plt.show()
    # Back to AO basis
    coeff = numpy.dot(s12inv, coeff)
    diff = reduce(numpy.dot, (coeff.T, ova, coeff)) - numpy.identity(nb)
    print 'CtSC-I', numpy.linalg.norm(diff)
    #
    # Averaged Fock
    #
    enorb = mf["mo_energy"]
    fa = reduce(numpy.dot, (ma, numpy.diag(enorb[0]), ma.T))
    fb = reduce(numpy.dot, (mb, numpy.diag(enorb[1]), mb.T))
    # Non-orthogonal cases: FC=SCE
    # Fao = SC*e*C{-1} = S*C*e*Ct*S
    fav = 0.5 * (fa + fb)
    # Expectation value of natural orbitals <i|F|i>
    fexpt = reduce(numpy.dot, (coeff.T, ova, fav, ova, coeff))
    enorb = numpy.diag(fexpt)
    nocc = eig.copy()
    #
    # Reordering and define active space according to thresh
    #
    idx = 0
    active = []
    for i in range(nb):
        if nocc[i] <= 2.0 - thresh and nocc[i] >= thresh:
            active.append(True)
        else:
            active.append(False)
    print '\nNatural orbitals:'
    for i in range(nb):
        print 'orb:', i, active[i], nocc[i], enorb[i]
    active = numpy.array(active)
    actIndices = list(numpy.argwhere(active == True).flatten())
    cOrbs = coeff[:, :actIndices[0]]
    aOrbs = coeff[:, actIndices]
    vOrbs = coeff[:, actIndices[-1] + 1:]
    nb = cOrbs.shape[0]
    nc = cOrbs.shape[1]
    na = aOrbs.shape[1]
    nv = vOrbs.shape[1]
    print 'core orbs:', cOrbs.shape
    print 'act  orbs:', aOrbs.shape
    print 'vir  orbs:', vOrbs.shape
    assert nc + na + nv == nb
    # dump UNO
    with open(fname + '_uno.molden', 'w') as thefile:
        molden.header(mol, thefile)
        molden.orbital_coeff(mol, thefile, coeff)
    #=====================
    # Population analysis
    #=====================
    from pyscf import lo
    aux = lo.orth_ao(mol, method='meta_lowdin')
    #clmo = ulocal.scdm(cOrbs,ova,aux)
    #almo = ulocal.scdm(aOrbs,ova,aux)
    clmo = cOrbs
    almo = aOrbs
    ierr, uc = pmloc.loc(mol, clmo)
    ierr, ua = pmloc.loc(mol, almo)
    clmo = clmo.dot(uc)
    almo = almo.dot(ua)
    vlmo = ulocal.scdm(vOrbs, ova, aux)
    # P-SORT
    mo_c, n_c, e_c = ulocal.psort(ova, fav, pT, clmo)
    mo_o, n_o, e_o = ulocal.psort(ova, fav, pT, almo)
    mo_v, n_v, e_v = ulocal.psort(ova, fav, pT, vlmo)
    lmo = numpy.hstack((mo_c, mo_o, mo_v)).copy()
    enorb = numpy.hstack([e_c, e_o, e_v])
    occ = numpy.hstack([n_c, n_o, n_v])
    # CHECK
    diff = reduce(numpy.dot, (lmo.T, ova, lmo)) - numpy.identity(nb)
    print 'diff=', numpy.linalg.norm(diff)
    ulocal.lowdinPop(mol, lmo, ova, enorb, occ)
    ulocal.dumpLMO(mol, fname, lmo)
    print 'nalpha,nbeta,mol.spin,nb:',\
           nalpha,nbeta,mol.spin,nb
    return mol, ova, fav, pT, nb, nalpha, nbeta, nc, na, nv, lmo, enorb, occ
Example #12
0
def genEmbedBasis(mol,
                  mo_coeff,
                  selectionRule,
                  thresh=0.001,
                  lao='meta_lowdin',
                  debug=False,
                  ifplot=True):
    print('\n[embed.genEmbedBasis] for unrestricted determinant')
    ova = mol.intor_symmetric("cint1e_ovlp_sph")
    nb = mo_coeff.shape[1]
    # Check overlap
    diff = reduce(numpy.dot,
                  (mo_coeff[0].T, ova, mo_coeff[0])) - numpy.identity(nb)
    print(' (CtSC-I)[a]', numpy.linalg.norm(diff))
    diff = reduce(numpy.dot,
                  (mo_coeff[1].T, ova, mo_coeff[1])) - numpy.identity(nb)
    print(' (CtSC-I)[b]', numpy.linalg.norm(diff))
    # UHF-alpha/beta
    ma = mo_coeff[0]
    mb = mo_coeff[1]
    nalpha = (mol.nelectron + mol.spin) / 2
    nbeta = (mol.nelectron - mol.spin) / 2
    print(' nalpha/nbeta = ', (nalpha, nbeta))
    # Spin-averaged DM
    ma_occ = ma[:, :nalpha]
    mb_occ = mb[:, :nbeta]
    pTa = numpy.dot(ma_occ, ma_occ.T)
    pTb = numpy.dot(mb_occ, mb_occ.T)
    pT = pTa + pTb

    #------------------------------------
    # OAO basis
    #------------------------------------
    # Due to optimization by segmentation,
    # the lowdin here do not correspond to
    # the idea lowdin OAO.
    if lao == 'bad_lowdin':
        s12 = sqrtm(ova)
        s12inv = lowdin(ova)
    # Better choice: Pbas*|chiANO>
    elif lao == 'meta_lowdin':
        from pyscf import lo
        meta = lo.orth_ao(mol, method='meta_lowdin')
        diff = reduce(numpy.dot, (meta.T, ova, meta)) - numpy.identity(nb)
        s12inv = meta.copy()
        s12 = numpy.linalg.inv(s12inv)
    #
    # Psi = chiAO*C
    #     = (chiAO*Y)*(Yinv*C)
    # DM in ortho basis = Yinv*C*n*C^T*Yinv^T
    # Only in lowdin basis Y^T=Y.
    #
    pTOAO = reduce(numpy.dot, (s12, pT, s12.T))
    #------------------------------------

    # Define impurity
    labels = mol.spheric_labels()
    fragBasis = []
    fragLabels = []
    for idx, item in enumerate(labels):
        ifselect = False
        if selectionRule(item):
            ifselect = True
        if ifselect:
            fragBasis.append(idx)
            fragLabels.append(item)
    print(' Define central fragment:')
    print(' No. of totalBasis:', nb)
    print(' No. of fragBasis :', len(fragBasis))
    print(' Indices of fragBasis:', fragBasis)
    print(' fragLabels:')
    for idx, item in enumerate(fragLabels):
        print('  idx = ', idx, ' fragBas=', item)
    compBasis = list(set(range(nb)) - set(fragBasis))
    nfrag = len(fragBasis)
    ncomp = len(compBasis)
    # Fragment
    pTf = pTOAO[numpy.ix_(fragBasis, fragBasis)]
    ef, u = scipy.linalg.eigh(-pTf)
    ef = -ef
    ne_f = sum(ef)
    print(' Diag_values of pTf:\n', numpy.diag(pTf))
    print(' Eigenvalues of pTf:\n', ef)
    uf = numpy.zeros((nb, nfrag))
    # Retain the locality for impurity
    #uf[fragBasis,:] = u
    uf[fragBasis, :] = numpy.identity(nfrag)
    # Complementary
    if ncomp > 0:
        pTc = pTOAO[numpy.ix_(compBasis, compBasis)]
        ec, v = scipy.linalg.eigh(-pTc)
        ec = -ec
        ne_c = sum(ec)
        print(' Eigenvalues of pTc:\n', ec)
        cindx = []
        aindx = []
        vindx = []
        for i in range(ncomp):
            if abs(ec[i] - 2.0) < thresh:
                cindx.append(i)
            elif abs(ec[i]) < thresh:
                vindx.append(i)
            else:
                aindx.append(i)
        ncStrict = len(numpy.argwhere(abs(ec - 2.0) < 1.e-6))
        nvStrict = len(numpy.argwhere(abs(ec) < 1.e-6))
        naStrict = ncomp - ncStrict - nvStrict
        nc = len(cindx)
        na = len(aindx)
        nv = len(vindx)
        vc = numpy.zeros((nb, nc))
        va = numpy.zeros((nb, na))
        vv = numpy.zeros((nb, nv))
        vc[compBasis, :] = v[:, cindx]
        va[compBasis, :] = v[:, aindx]
        vv[compBasis, :] = v[:, vindx]
        # Set up the proper ordering
        ucoeff = numpy.hstack((uf, va, vc, vv))
        print('-' * 70)
        print(' Final results for classification of basis with thresh=',
              thresh)
        print('-' * 70)
        print(' (nf,na,nc,nv) = ', nfrag, na, nc, nv)
        print(' (ncomp,ncStrict,nvStrict,naStrict) =', ncomp, ncStrict,
              nvStrict, naStrict)
        print(' Eigen_na =\n', ec[aindx])
        if ifplot:
            import matplotlib.pyplot as plt
            plt.plot(abs(ef), marker='o', linewidth=2.0)
            plt.plot(abs(ec), marker='o', linewidth=2.0)
            plt.show()
    else:
        ne_c = 0.0
        ucoeff = uf.copy()
    # Check
    pTu = reduce(numpy.dot, (ucoeff.T, pTOAO, ucoeff))
    print(' Nf =', ne_f, 'Nc =', ne_c, 'Nt =', ne_f + ne_c)
    if debug:
        print(' diagonal of pTu =')
        print(numpy.diag(pTu))
        print('ucoeff\n', ucoeff)
    # Back to AO basis
    basis = numpy.dot(s12inv, ucoeff)
    # Dump
    diff = reduce(numpy.dot, (basis.T, ova, basis)) - numpy.identity(nb)
    print(' CtSC-I=', numpy.linalg.norm(diff))
    with open('embas.molden', 'w') as thefile:
        molden.header(mol, thefile)
        molden.orbital_coeff(mol, thefile, basis)
    with open('cmoA.molden', 'w') as thefile:
        molden.header(mol, thefile)
        molden.orbital_coeff(mol, thefile, ma)
    with open('cmoB.molden', 'w') as thefile:
        molden.header(mol, thefile)
        molden.orbital_coeff(mol, thefile, mb)
    ua = reduce(numpy.dot, (basis.T, ova, ma_occ))
    ub = reduce(numpy.dot, (basis.T, ova, mb_occ))
    if debug: print(' ua\n', ua)
    if debug: print(' ub\n', ub)
    ia = abs(reduce(numpy.dot, (ua.T, ua)))
    ib = abs(reduce(numpy.dot, (ub.T, ub)))
    print(' diffIa=', numpy.linalg.norm(ia - numpy.identity(nalpha)))
    print(' diffIb=', numpy.linalg.norm(ib - numpy.identity(nbeta)))
    return basis, ua, ub
Example #13
0
#
rdm1 = mycc.make_rdm1()
rdm2 = mycc.make_rdm2()
eri_mo = ao2mo.kernel(mf._eri, coeff[:, :nmo], compact=False)
eri_mo = eri_mo.reshape(nmo, nmo, nmo, nmo)
h1 = reduce(numpy.dot, (coeff[:, :nmo].T, mf.get_hcore(), coeff[:, :nmo]))
ecc = (numpy.einsum('ij,ji->', h1, rdm1) +
       numpy.einsum('ijkl,ijkl->', eri_mo, rdm2) * .5 + mf.mol.energy_nuc())
lib.logger.info(mycc, "* Energy with 1/2-RDM : %.8f" % ecc)

den_file = name + '.den'
fspt = open(den_file, 'w')
fspt.write('CCIQA\n')
fspt.write('1-RDM:\n')
for i in range(nmo):
    for j in range(nmo):
        fspt.write('%i %i %.10f\n' % ((i + 1), (j + 1), rdm1[i, j]))
fspt.write('2-RDM:\n')
for i in range(nmo):
    for j in range(nmo):
        for k in range(nmo):
            for l in range(nmo):
                if (abs(rdm2[i, j, k, l]) > 1e-8):
                    fspt.write('%i %i %i %i %.10f\n' % ((i+1), \
                    (j+1), (k+1), (l+1), rdm2[i,j,k,l]))
fspt.close()

with open(name + '.mol', 'w') as f2:
    molden.header(mol, f2)
    molden.orbital_coeff(mol, f2, coeff[:, :nmo], occ=occ[:nmo])
Example #14
0
vOrbs = coeff[:,actIndices[-1]+1:]
nb = cOrbs.shape[0]
nc = cOrbs.shape[1]
na = aOrbs.shape[1]
nv = vOrbs.shape[1]
print 'core orbs:',cOrbs.shape
print 'act  orbs:',aOrbs.shape
print 'vir  orbs:',vOrbs.shape
assert nc+na+nv == nb
#
# dump UNO
#
from pyscf.tools import molden
with open(fname+'_uno.molden','w') as thefile:
    molden.header(mol,thefile)
    molden.orbital_coeff(mol,thefile,coeff)

#=============================
# local orbitals
#=============================
from pyscf.tools import molden,localizer
iflocal  = False #True
if iflocal:
   loc = localizer.localizer(mol,ma[:,:mol.nelectron/2],'boys')
   loc.verbose = 10
   new_coeff = loc.optimize()
   loc = localizer.localizer(mol,ma[:,mol.nelectron/2:],'boys')
   new_coeff2 = loc.optimize()
   lmo = numpy.hstack([new_coeff,new_coeff2])
   with open(fname+'lmo.molden','w') as thefile:
      molden.header(mol,thefile)
Example #15
0
    def locmo_molden(self, mo_coeff, mo_occ, filename):

        transfo = np.dot(self.ao2loc, mo_coeff)
        with open(filename, 'w') as thefile:
            molden.header(self.mol, thefile)
            molden.orbital_coeff(self.mol, thefile, transfo, occ=mo_occ)
Example #16
0
 def molden( self, filename ):
 
     with open( filename, 'w' ) as thefile:
         molden.header( self.mol, thefile )
         molden.orbital_coeff( self.mol, thefile, self.ao2loc )
Example #17
0
            fspt.write('%i %i %.16f\n' % ((i+1), (j+1), rdm1[i,j]))
    fspt.write('La matriz d es:\n')
    for i in range(nmo):
        for j in range(nmo):
            for k in range(nmo):
                for l in range(nmo):
                    if (abs(rdm2[i,j,k,l]) > 1e-12):
                            fspt.write('%i %i %i %i %.16f\n' % ((i+1), (j+1), (k+1), (l+1), rdm2[i,j,k,l]))
    fspt.close()
    orbsym = symm.label_orb_symm(mol, mol.irrep_id, mol.symm_orb, mc.mo_coeff[:,:nmo])
    natocc, natorb = symm.eigh(-rdm1, orbsym)
    for i, k in enumerate(numpy.argmax(abs(natorb), axis=0)):
        if natorb[k,i] < 0:
            natorb[:,i] *= -1
    natorb = numpy.dot(mc.mo_coeff[:,:nmo], natorb)
    natocc = -natocc
    with open('n2_cas.det', 'w') as f3:
        write_ci(f3, mc.ci, mc.ncas, mc.nelecas, mc.ncore)
    with open('n2_ref_nat.mol', 'w') as f2:
        molden.header(mol, f2)
        molden.orbital_coeff(mol, f2, natorb, occ=natocc)
    with open('n2_ref.mol', 'w') as f2:
        molden.header(mol, f2)
        molden.orbital_coeff(mol, f2, mc.mo_coeff[:,:nmo], occ=mf.mo_occ[:nmo])
    with open('n2_cas.wfn', 'w') as f2:
        write_mo(f2, mol, natorb, mo_occ=natocc)
        write_mo(f2, mol, mc.mo_coeff[:,:nmo])
    with open('rdm_wfn.wfn', 'w') as f2:
        write_mo(f2, mol, mc.mo_coeff[:,:nmo], mo_occ=mf.mo_occ[:nmo])

Example #18
0
  H  3.4870    0.0000    0.0197
  H  1.0145    0.2578    0.0000
           """,
    basis="cc-pvdz",
    symmetry=1,
)

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

#
# First method is to explicit call the functions provided by molden.py
#
with open("C6H6mo.molden", "w") as f1:
    molden.header(mol, f1)
    molden.orbital_coeff(mol, f1, mf.mo_coeff, ene=mf.mo_energy, occ=mf.mo_occ)

#
# Second method is to simply call from_mo function to write the orbitals
#
c_loc_orth = lo.orth.orth_ao(mol)
molden.from_mo(mol, "C6H6loc.molden", c_loc_orth)


#
# Molden format does not support high angular momentum basis.  To handle the
# orbitals which have l>=5 functions, a hacky way is to call molden.remove_high_l
# function.  However, the resultant orbitals may not be orthnormal.
#
mol = gto.M(atom="He 0 0 0", basis={"He": gto.expand_etbs(((0, 3, 1.0, 2.0), (5, 2, 1.0, 2.0)))})
mf = scf.RHF(mol).run()
Example #19
0
    m = scf.RHF(mol)
    m.scf()

    mc = mcscf.CASSCF(m, 4, 4)
    mc.fcisolver = FCIQMCCI(mol)
    mc.fcisolver.tau = 0.01
    mc.fcisolver.RDMSamples = 1000
    mc.max_cycle_macro = 10
    # Return natural orbitals from mc2step in casscf_mo.
    mc.natorb = True
    emc_1, e_ci, fcivec, casscf_mo, mo_energy = mc.mc2step(m.mo_coeff)

    # Write orbitals to molden output.
    with open('output.molden', 'w') as fout:
        molden.header(mol, fout)
        molden.orbital_coeff(mol, fout, casscf_mo)

    # Now, calculate the full RDMs for the full energy.
    one_pdm, two_pdm = find_full_casscf_12rdm(mc.fcisolver, casscf_mo,
                                              'spinfree_TwoRDM.1', 4, 4)
    e = calc_energy_from_rdms(mol, casscf_mo, one_pdm, two_pdm)
    print('Energy from rdms and CASSCF should be the same: ', e, emc_1)

    mc = mcscf.CASCI(m, 4, 4)
    mc.fcisolver = FCIQMCCI(mol)
    mc.fcisolver.tau = 0.01
    mc.fcisolver.RDMSamples = 1000
    emc_0 = mc.casci()[0]

    b = 1.4
    mol = gto.Mole()
Example #20
0
#######################
#   Parse the input   #
#######################
thebasis1 = 'cc-pvdz'       # Basis set for H and C
thebasis2 = 'aug-cc-pvdz'   # Basis set for Cl and Br
mol = sn2_structures.structure( thestructure, thebasis1, thebasis2 )
mf = scf.RHF( mol )
mf.verbose = 4
mf.scf()

if ( False ):
    from pyscf.tools import molden, localizer
    with open( 'sn2-mo.molden', 'w' ) as thefile:
        molden.header( mol, thefile )
        molden.orbital_coeff( mol, thefile, mf.mo_coeff )

if ( False ):
    ccsolver = ccsd.CCSD( mf )
    ccsolver.verbose = 5
    ECORR, t1, t2 = ccsolver.ccsd()
    ECCSD = mf.hf_energy + ECORR
    print "ERHF  for structure", thestructure, "=", mf.hf_energy
    print "ECCSD for structure", thestructure, "=", ECCSD
    
if ( True ):
    # myInts = localintegrals.localintegrals( mf, range( mol.nao_nr() ), 'boys', localization_threshold=1e-5 )
    # myInts = localintegrals.localintegrals( mf, range( mol.nao_nr() ), 'meta_lowdin' )
    myInts = localintegrals.localintegrals( mf, range( mol.nao_nr() ), 'iao' )
    myInts.molden( 'sn2-loc.molden' )
    
Example #21
0
mc.kernel(loc_mo)
rdm1, rdm2 = mc.fcisolver.make_rdm12(mc.ci, norb, nelec)
rdm1, rdm2 = add_inactive_space_to_rdm(mol, mf.mo_coeff, rdm1, rdm2)
##########################################################################################
den_file = name + '.den'
fspt = open(den_file, 'w')
fspt.write(
    'CCIQA    ENERGY =      0.000000000000 THE VIRIAL(-V/T)=   2.00000000\n')
fspt.write('La matriz D es:\n')
for i in range(nmo):
    for j in range(nmo):
        fspt.write('%i %i %.16f\n' % ((i + 1), (j + 1), rdm1[i, j]))
fspt.write('La matriz d es:\n')
for i in range(nmo):
    for j in range(nmo):
        for k in range(nmo):
            for l in range(nmo):
                if (abs(rdm2[i, j, k, l]) > 1e-12):
                    fspt.write('%i %i %i %i %.16f\n' %
                               ((i + 1), (j + 1), (k + 1),
                                (l + 1), rdm2[i, j, k, l]))
fspt.close()
##########################################################################################
with open(name + '.mol', 'w') as f2:
    molden.header(mol, f2)
    molden.orbital_coeff(mol, f2, mc.mo_coeff, occ=mf.mo_occ)
cmd = '/home/jluis/bin/molden2aim ' + name
os.system(cmd)
cmd = 'cat ' + name + '.den ' + '>> ' + name + '.wfn'
os.system(cmd)
Example #22
0
    def sub_molden(self, loc2sub, filename, mo_occ=None):

        transfo = np.dot(self.ao2loc, loc2sub)
        with open(filename, 'w') as thefile:
            molden.header(self.mol, thefile)
            molden.orbital_coeff(self.mol, thefile, transfo, occ=mo_occ)
#===================this section is optional==============
# if you would like to check the generated orbitals
HF_en = mf.mo_energy
HF_MOcoeff = mf.mo_coeff
HF_occ = mf.mo_occ
ova = mol.intor_symmetric("cint1e_ovlp_sph")
e_d = numpy.diag(HF_en)
cect = numpy.dot(HF_MOcoeff, numpy.dot(e_d, HF_MOcoeff.T))
f = numpy.dot(ova, numpy.dot(cect, ova))
en = numpy.diag(numpy.dot(coeff.T, numpy.dot(f, coeff)))
fname = 'generated_AS_beforeCAS'
from pyscf.tools import molden
with open(fname + '.molden', 'w') as thefile:
    molden.header(mol, thefile)
    molden.orbital_coeff(mol, thefile, coeff, ene=en, occ=mf.mo_occ)
#==========================================================

mycas = mcscf.CASSCF(mf, norb, [nalpha, nbeta])
AS = range(N_Core, N_Core + N_Act)
mycas.chkfile = 'cas_FeCp2.chk'  # it is useful to keep the chk file for CASSCF in case you want to run some subsequent CASCI and NEVPT2 calculations
mycas.fcisolver.nroots = 1
mycas.fix_spin_(
    ss=0
)  # in newer PYSCF it is better to specify ss which is usually your mol.spin
activeMO = mcscf.sort_mo(mycas, coeff, AS, base=0)
mycas.verbose = 5
mycas.max_cycle_macro = 150
mycas.kernel(activeMO)

mc = mcscf.CASCI(mf, norb, [nalpha, nbeta])
Example #24
0
 def molden( self, filename ):
 
     with open( filename, 'w' ) as thefile:
         molden.header( self.mol, thefile )
         molden.orbital_coeff( self.mol, thefile, self.ao2loc )
Example #25
0
    m = scf.RHF(mol)
    m.scf()

    mc = mcscf.CASSCF(m, 4, 4)
    mc.fcisolver = FCIQMCCI(mol)
    mc.fcisolver.tau = 0.01
    mc.fcisolver.RDMSamples = 1000 
    mc.max_cycle_macro = 10
    # Return natural orbitals from mc2step in casscf_mo.
    mc.natorb = True
    emc_1, e_ci, fcivec, casscf_mo = mc.mc2step(m.mo_coeff)

    # Write orbitals to molden output.
    with open( 'output.molden', 'w' ) as fout:
        molden.header(mol, fout)
        molden.orbital_coeff(mol, fout, casscf_mo)

    # Now, calculate the full RDMs for the full energy.
    one_pdm, two_pdm = find_full_casscf_12rdm(mc.fcisolver, casscf_mo,
            'spinfree_TwoRDM.1', 4, 4)
    e = calc_energy_from_rdms(mol, casscf_mo, one_pdm, two_pdm)
    print('Energy from rdms and CASSCF should be the same: ',e,emc_1)

    mc = mcscf.CASCI(m, 4, 4)
    mc.fcisolver =  FCIQMCCI(mol)
    mc.fcisolver.tau = 0.01
    mc.fcisolver.RDMSamples = 1000
    emc_0 = mc.casci()[0]

    b = 1.4
    mol = gto.Mole()
Example #26
0
def mo_molden(mol,mo_coeff,filename):
    with open( filename, 'w' ) as thefile:
            molden.header( mol, thefile )
            molden.orbital_coeff( mol, thefile, mo_coeff )
Example #27
0
h1a = reduce(numpy.dot, (mo_a.T.conj(), hcore, mo_a))
h1b = reduce(numpy.dot, (mo_b.T.conj(), hcore, mo_b))
e1 = einsum('ij,ji', h1a, rdm1a)
e1 += einsum('ij,ji', h1b, rdm1b)
e1 += einsum('ijkl,ijkl', eriaa, rdm2aa) * 0.5
e1 += einsum('ijkl,ijkl', eriab, rdm2ab)
e1 += einsum('ijkl,ijkl', eribb, rdm2bb) * 0.5
e1 += mol.energy_nuc()
lib.logger.info(pt2, "* Excited state Energy with 1/2-RDM : %.8f" % e1)
####### This can be removed ######

coeff = numpy.hstack([mo_a, mo_b])
occ = numpy.hstack([occ_a, occ_b])
with open(name + '.mol', 'w') as f2:
    molden.header(mol, f2)
    molden.orbital_coeff(mol, f2, coeff, occ=occ)

# Aqui cuidado para hacer una prueba rapida los bucles
# Se recorren en alpha por ejemplo porque hay el mismo
# numero de alpha y beta congelados, si fuese distinto
# habria que cabiar
nmo = nmoa
den_file = name + '.den'
fspt = open(den_file, 'w')
fspt.write('CCIQA\n')
fspt.write('1-RDM:\n')
for i in range(nmo):
    for j in range(nmo):
        fspt.write('%i %i %.10f\n' % ((i + 1), (j + 1), rdm1a[i, j]))
        fspt.write('%i %i %.10f\n' % ((i + 1 + nmo),
                                      (j + 1 + nmo), rdm1b[i, j]))
Example #28
0
  C  3.2883    3.3891    0.2345       
  C  1.9047    3.5333    0.2237       
  C  3.8560    2.1213    0.1612       
  C  1.0888    2.4099    0.1396       
  C  3.0401    0.9977    0.0771       
  C  1.6565    1.1421    0.0663       
  H  3.9303    4.2734    0.3007       
  H  1.4582    4.5312    0.2815       
  H  4.9448    2.0077    0.1699       
  H  0.0000    2.5234    0.1311       
  H  3.4870    0.0000    0.0197       
  H  1.0145    0.2578    0.0000       
           ''',
    basis = 'cc-pvdz',
    symmetry = 1)

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

with open('C6H6mo.molden', 'w') as f1:
    molden.header(mol, f1)
    molden.orbital_coeff(mol, f1, mf.mo_coeff, ene=mf.mo_energy, occ=mf.mo_occ)

c_loc_orth = lo.orth.orth_ao(mol, 'meta_lowdin', lo.orth.pre_orth_ao(mol))
with open('C6H6loc.molden', 'w') as f2:
    molden.header(mol, f2)
    molden.orbital_coeff(mol, f2, c_loc_orth)



Example #29
0
mc.fix_spin_(shift=.5, ss=0)
#mc.__dict__.update(scf.chkfile.load(name+'.chk', 'mcscf'))
#mo = lib.chkfile.load(name+'.chk', 'mcscf/mo_coeff')
mc.kernel(mo)

nmo = mc.ncore + mc.ncas
rdm1, rdm2 = mc.fcisolver.make_rdm12(mc.ci, mc.ncas, mc.nelecas) 
rdm1, rdm2 = mcscf.addons._make_rdm12_on_mo(rdm1, rdm2, mc.ncore, mc.ncas, nmo)

den_file = name + '.den'
fspt = open(den_file,'w')
fspt.write('CCIQA\n')
fspt.write('1-RDM:\n')
for i in range(nmo):
    for j in range(nmo):
        fspt.write('%i %i %.10f\n' % ((i+1), (j+1), rdm1[i,j]))
fspt.write('2-RDM:\n')
for i in range(nmo):
    for j in range(nmo):
        for k in range(nmo):
            for l in range(nmo):
                if (abs(rdm2[i,j,k,l]) > 1e-8):
                        fspt.write('%i %i %i %i %.10f\n' % ((i+1), \
                        (j+1), (k+1), (l+1), rdm2[i,j,k,l]))
fspt.close()                    
    
with open(name+'.mol', 'w') as f2:
    molden.header(mol, f2)
    molden.orbital_coeff(mol, f2, mc.mo_coeff[:,:nmo], occ=mf.mo_occ[:nmo])

Example #30
0
                ['N', map(lambda x: x * fac, [0.0, 1.653532, 0.0])],
                ['O', map(lambda x: x * fac, [-2.050381, -2.530377, 0.0])],
                ['O', map(lambda x: x * fac, [2.050381, -2.530377, 0.0])],
                ['O', map(lambda x: x * fac, [-2.050381, 2.530377, 0.0])],
                ['O', map(lambda x: x * fac, [2.050381, 2.530377, 0.0])]]
    mol.basis = 'aug-cc-pvdz'
    mol.charge = 0
    mol.spin = 0
    mol.build()

    mf = scf.RHF(mol)
    mf.init_guess = 'atom'
    mf.level_shift = 0.0
    mf.max_cycle = 100
    mf.conv_tol = 1.e-20
    ehf = mf.scf()

    nocc = mol.nelectron / 2
    ierr, uo = loc(mol, mf.mo_coeff[:, :nocc], iop=0)
    ierr, uv = loc(mol, mf.mo_coeff[:, nocc:], iop=0)
    u = scipy.linalg.block_diag(uo, uv)
    lmo = numpy.dot(mf.mo_coeff, u)

    fname = 'n2o4'
    with open(fname + '_cmo.molden', 'w') as thefile:
        molden.header(mol, thefile)
        molden.orbital_coeff(mol, thefile, mf.mo_coeff)
    with open(fname + '_lmo.molden', 'w') as thefile:
        molden.header(mol, thefile)
        molden.orbital_coeff(mol, thefile, lmo)
Example #31
0
def dumpLUNO(fname,thresh=0.01):
   chkfile = fname+'.chk'
   outfile = fname+'_cmo.molden'
   tools.molden.from_chkfile(outfile, chkfile)
   #=============================
   # Natural orbitals
   # Lowdin basis X=S{-1/2}
   # psi = chi * C 
   #     = chi' * C'
   #     = chi*X*(X{-1}C')
   #=============================
   mol,mf = scf.chkfile.load_scf(chkfile)
   mo_coeff = mf["mo_coeff"]
   ova=mol.intor_symmetric("cint1e_ovlp_sph")
   nb = mo_coeff.shape[1]
   # Check overlap
   diff = reduce(numpy.dot,(mo_coeff[0].T,ova,mo_coeff[0])) - numpy.identity(nb)
   print numpy.linalg.norm(diff)
   diff = reduce(numpy.dot,(mo_coeff[1].T,ova,mo_coeff[1])) - numpy.identity(nb)
   print numpy.linalg.norm(diff)
   # UHF-alpha/beta
   ma = mo_coeff[0]
   mb = mo_coeff[1]
   nalpha = (mol.nelectron+mol.spin)/2
   nbeta  = (mol.nelectron-mol.spin)/2
   # Spin-averaged DM
   pTa = numpy.dot(ma[:,:nalpha],ma[:,:nalpha].T)
   pTb = numpy.dot(mb[:,:nbeta],mb[:,:nbeta].T)
   pT = 0.5*(pTa+pTb)
   # Lowdin basis
   s12 = sqrtm(ova)
   s12inv = lowdin(ova)
   pTOAO = reduce(numpy.dot,(s12,pT,s12))
   eig,coeff = scipy.linalg.eigh(-pTOAO)
   eig = -2.0*eig
   eig[eig<0.0]=0.0
   eig[abs(eig)<1.e-14]=0.0
   ifplot = False #True
   if ifplot:
      import matplotlib.pyplot as plt
      plt.plot(range(nb),eig,'ro')
      plt.show()
   # Back to AO basis
   coeff = numpy.dot(s12inv,coeff)
   diff = reduce(numpy.dot,(coeff.T,ova,coeff)) - numpy.identity(nb)
   print 'CtSC-I',numpy.linalg.norm(diff)
   # 
   # Averaged Fock
   #
   enorb = mf["mo_energy"]
   fa = reduce(numpy.dot,(ma,numpy.diag(enorb[0]),ma.T))
   fb = reduce(numpy.dot,(mb,numpy.diag(enorb[1]),mb.T))
   # Non-orthogonal cases: FC=SCE
   # Fao = SC*e*C{-1} = S*C*e*Ct*S
   fav = 0.5*(fa+fb)
   # Expectation value of natural orbitals <i|F|i>
   fexpt = reduce(numpy.dot,(coeff.T,ova,fav,ova,coeff))
   enorb = numpy.diag(fexpt)
   nocc = eig.copy()
   #
   # Reordering and define active space according to thresh
   #
   idx = 0
   active=[]
   for i in range(nb):
      if nocc[i]<=2.0-thresh and nocc[i]>=thresh:
         active.append(True)
      else:
         active.append(False)
   print '\nNatural orbitals:'
   for i in range(nb):
      print 'orb:',i,active[i],nocc[i],enorb[i]
   active = numpy.array(active)
   actIndices = list(numpy.argwhere(active==True).flatten())
   cOrbs = coeff[:,:actIndices[0]]
   aOrbs = coeff[:,actIndices]
   vOrbs = coeff[:,actIndices[-1]+1:]
   nb = cOrbs.shape[0]
   nc = cOrbs.shape[1]
   na = aOrbs.shape[1]
   nv = vOrbs.shape[1]
   print 'core orbs:',cOrbs.shape
   print 'act  orbs:',aOrbs.shape
   print 'vir  orbs:',vOrbs.shape
   assert nc+na+nv == nb
   # dump UNO
   with open(fname+'_uno.molden','w') as thefile:
       molden.header(mol,thefile)
       molden.orbital_coeff(mol,thefile,coeff)
   #=====================
   # Population analysis
   #=====================
   aux = s12inv
   #clmo = ulocal.scdm(cOrbs,ova,aux)
   #almo = ulocal.scdm(aOrbs,ova,aux)
   clmo = cOrbs
   almo = aOrbs
   ierr,uc = pmloc.loc(mol,clmo)
   ierr,ua = pmloc.loc(mol,almo)
   clmo = clmo.dot(uc)
   almo = almo.dot(ua)
   vlmo = ulocal.scdm(vOrbs,ova,aux)
   # P-SORT
   mo_c,n_c,e_c = ulocal.psort(ova,fav,pT,clmo)
   mo_o,n_o,e_o = ulocal.psort(ova,fav,pT,almo)
   mo_v,n_v,e_v = ulocal.psort(ova,fav,pT,vlmo)
   lmo = numpy.hstack((mo_c,mo_o,mo_v)).copy()
   enorb = numpy.hstack([e_c,e_o,e_v])
   occ = numpy.hstack([n_c,n_o,n_v])
   # CHECK
   diff = reduce(numpy.dot,(lmo.T,ova,lmo)) - numpy.identity(nb)
   print 'diff=',numpy.linalg.norm(diff)
   ulocal.lowdinPop(mol,lmo,ova,enorb,occ)
   ulocal.dumpLMO(mol,fname,lmo)
   print 'nalpha,nbeta,mol.spin,nb:',\
          nalpha,nbeta,mol.spin,nb
   return mol,ova,fav,pT,nb,nalpha,nbeta,nc,na,nv,lmo,enorb,occ
Example #32
0
  H  0.0000    2.5234    0.1311
  H  3.4870    0.0000    0.0197
  H  1.0145    0.2578    0.0000
           ''',
    basis = 'cc-pvdz',
    symmetry = 1)

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

#
# First method is to explicit call the functions provided by molden.py
#
with open('C6H6mo.molden', 'w') as f1:
    molden.header(mol, f1)
    molden.orbital_coeff(mol, f1, mf.mo_coeff, ene=mf.mo_energy, occ=mf.mo_occ)

#
# Second method is to simply call from_mo function to write the orbitals
#
c_loc_orth = lo.orth.orth_ao(mol)
molden.from_mo(mol, 'C6H6loc.molden', c_loc_orth)


#
# Molden format does not support high angular momentum basis.  To handle the
# orbitals which have l>=5 functions, a hacky way is to call molden.remove_high_l
# function.  However, the resultant orbitals may not be orthnormal.
#
mol = gto.M(
    atom = 'He 0 0 0',