Example #1
0
def write_fcidump(system, name='FCIDUMP'):
    fcidump.from_integrals(name,
                           system.H1[0],
                           system.h2e,
                           system.H1[0].shape[0],
                           system.ne,
                           nuc=system.ecore)
Example #2
0
 def make_fcidump(self, filename):
     mo_coeff = self.mf.mo_coeff
     h1 = reduce(numpy.dot, (mo_coeff.T, self.mf.get_hcore(), mo_coeff))
     if self.mf._eri is None:
         eri = ao2mo.full(self.mol, mo_coeff)
     else:
         eri = ao2mo.full(self.mf._eri, mo_coeff)
     nuc = self.mf.energy_nuc()
     orbsym = getattr(mo_coeff, 'orbsym', None)
     if self.symmetry in ('DOOH', 'COOV'):
         self.writeComplexOrbIntegrals(h1, eri, h1.shape[0],
                                       self.n_up + self.n_down, nuc, orbsym,
                                       self.partner_orbs)
         fcidump.from_integrals("FCIDUMP_real_orbs", h1, eri, h1.shape[0],
                                self.mol.nelec, nuc, 0, orbsym)
     else:
         orbsym = [sym + 1 for sym in orbsym]
         fcidump.from_integrals(filename,
                                h1,
                                eri,
                                h1.shape[0],
                                self.mol.nelec,
                                nuc,
                                0,
                                orbsym,
                                tol=1e-15,
                                float_format=' %.16g')
Example #3
0
 def test_from_integral(self):
     tmpfcidump = tempfile.NamedTemporaryFile()
     h1 = reduce(numpy.dot, (mf.mo_coeff.T, mf.get_hcore(), mf.mo_coeff))
     h2 = ao2mo.full(mf._eri, mf.mo_coeff)
     fcidump.from_integrals(tmpfcidump.name,
                            h1,
                            h2,
                            h1.shape[0],
                            mol.nelectron,
                            tol=1e-15)
Example #4
0
 def test_fcidump(self, filename):
     mo_coeff = self.mf.mo_coeff
     orbsym = getattr(mo_coeff, 'orbsym', None)
     mo_coeff = reduce(numpy.dot,
                       (mo_coeff, self.real2complex_coeffs.conj().T))
     h1 = reduce(numpy.dot,
                 (mo_coeff.conj().T, self.mf.get_hcore(), mo_coeff))
     if self.mf._eri is None:
         eri = ao2mo.full(self.mol, mo_coeff)
     else:
         eri = ao2mo.full(self.mf._eri, mo_coeff)
     nuc = self.mf.energy_nuc()
     orbsym = [sym + 1 for sym in orbsym]
     fcidump.from_integrals(filename,
                            h1,
                            eri,
                            h1.shape[0],
                            self.mol.nelec,
                            nuc,
                            0,
                            orbsym,
                            tol=1e-15,
                            float_format=' %.16g')
Example #5
0
def call_molpro(h1e, eri, mo, nelec, inputstr, log=None):
    tdir = tempfile.mkdtemp(prefix='tmolpro')
    inpfile = os.path.join(tdir, 'inputs')

    open(inpfile, 'w').write(inputstr)
    write_matrop(os.path.join(tdir,'orb.matrop'), mo)
    nmo = mo.shape[1]
    fcidump.from_integrals(os.path.join(tdir, 'fcidump'),
                           h1e, eri, nmo, nelec, 0)

# note fcidump and orb.matrop should be put in the runtime dir
    cmd = ' '.join(('cd', tdir, '&& TMPDIR=`pwd`', MOLPROEXE, inpfile))
    rec = commands.getoutput(cmd)
    if 'fehler' in rec:
        sys.stderr.write('molpro tempfiles in %s\n'%tdir)
        raise RuntimeError('molpro fail as:\n' + rec)

    with open(inpfile+'.out') as fin:
        dat = fin.read()
        dat1 = dat.split('\n')
        es = dat1[-4]
        if log is not None:
            log.debug1(dat)
            log.debug('\n'.join(dat1[-5:-3]))
    eci, escf = map(float, es.split())[:2]

    if os.path.isfile(os.path.join(tdir,'rdm1')):
        with open(os.path.join(tdir,'rdm1')) as fin:
            fin.readline()
            fin.readline()
            dat = fin.read().replace(',', ' ').split()
        rdm1 = numpy.array(map(float, dat[:-1])).reshape(nmo,nmo)
# molpro will transform rdm1 back to AO representation (consistent to fcidump)
    else:
        rdm1 = None
    shutil.rmtree(tdir)
    return escf, eci, rdm1
Example #6
0
 def test_from_integral(self):
     tmpfcidump = tempfile.NamedTemporaryFile(dir=lib.param.TMPDIR)
     h1 = reduce(numpy.dot, (mf.mo_coeff.T, mf.get_hcore(), mf.mo_coeff))
     h2 = ao2mo.full(mf._eri, mf.mo_coeff)
     fcidump.from_integrals(tmpfcidump.name, h1, h2, h1.shape[0],
                            mol.nelectron, tol=1e-15)
  #mol.symmetry = True
  mol.basis = {'H': 'sto-6g'}
  mol.build()

  m = scf.RHF(mol)
  m.verbose = 4
  ehf = m.scf()
  print "ORB ENERGY : ", m.mo_energy

  #1-e Integrals
  hcore = mol.intor('cint1e_nuc_sph') + mol.intor('cint1e_kin_sph')
  ovlp = mol.intor('cint1e_ovlp_sph')

  Sihalf = lo.orth.lowdin(ovlp)
  h1e = np.einsum('pi,pq,qj->ij',Sihalf,hcore,Sihalf)
  nmo = np.shape(h1e)[0]

  #2-e Integrals
  eri_4fold = ao2mo.kernel(mol,Sihalf)

  #FCI-DUMP
  fname = 'FCIDUMP'
  nelec = mol.nelectron
  energy_nuc = mol.energy_nuc()
  fcid.from_integrals(fname,h1e,eri_4fold,nmo,nelec,energy_nuc)

  #Energy Test
  e = fci.direct_spin0.kernel(h1e,eri_4fold,nmo,nelec)
  print e[0]+energy_nuc
Example #8
0
#
# Example 2: Given a set of orbitals to transform integrals then dump the
# integrals to FCIDUMP
#
fcidump.from_mo(mol, 'fcidump.example2', myhf.mo_coeff)


#
# Exampel 3: FCIDUMP for given 1e and 2e integrals
#
c = myhf.mo_coeff
h1e = reduce(numpy.dot, (c.T, myhf.get_hcore(), c))
eri = ao2mo.kernel(mol, c)

fcidump.from_integrals('fcidump.example3', h1e, eri, c.shape[1],
                             mol.nelectron, ms=0)

#
# Exampel 4: Ignore small matrix elements in FCIDUMP
#
fcidump.from_integrals('fcidump.example4', h1e, eri, c.shape[1],
                             mol.nelectron, ms=0, tol=1e-10)

#
# Example 5: Inculde the symmetry information in FCIDUMP
#
# to write the irreps for each orbital, first use pyscf.symm.label_orb_symm to
# get the irrep ids
MOLPRO_ID = {'D2h': { 'Ag' : 1,
                      'B1g': 4,
                      'B2g': 6,
Example #9
0
def solve(mol, nel, cf_core, cf_gs, ImpOrbs, chempot=0., n_orth=0):
    # cf_core : core orbitals (in AO basis, assumed orthonormal)
    # cf_gs   : guess orbitals (in AO basis)
    # ImpOrbs : cf_gs -> impurity orbitals transformation
    # n_orth  : number of orthonormal orbitals in cf_gs [1..n_orth]

    cfx = cf_gs
    Sf = mol.intor_symmetric('cint1e_ovlp_sph')
    Hc  = mol.intor_symmetric('cint1e_kin_sph') \
        + mol.intor_symmetric('cint1e_nuc_sph')

    # core contributions
    dm_core = np.dot(cf_core, cf_core.T) * 2
    jk_core = scf.hf.get_veff(mol, dm_core)
    e_core  =     np.trace(np.dot(Hc, dm_core)) \
            + 0.5*np.trace(np.dot(jk_core, dm_core))

    # transform integrals
    Sp = np.dot(cfx.T, np.dot(Sf, cfx))
    Hp = np.dot(cfx.T, np.dot(Hc, cfx))
    jkp = np.dot(cfx.T, np.dot(jk_core, cfx))
    intsp = ao2mo.outcore.full_iofree(mol, cfx)

    # orthogonalize cf [virtuals]
    cf = np.zeros((cfx.shape[1], ) * 2, )
    if n_orth > 0:
        assert (n_orth <= cfx.shape[1])
        assert (np.allclose(np.eye(n_orth), Sp[:n_orth, :n_orth]))
    else:
        n_orth = 0

    cf[:n_orth, :n_orth] = np.eye(n_orth)
    if n_orth < cfx.shape[1]:
        val, vec = sla.eigh(-Sp[n_orth:, n_orth:])
        idx = -val > 1.e-12
        U = np.dot(vec[:,idx]*1./(np.sqrt(-val[idx])), \
                   vec[:,idx].T)
        cf[n_orth:, n_orth:] = U

    # define ImpOrbs projection
    Xp = np.dot(ImpOrbs, ImpOrbs.T)

    # Si = np.dot(ImpOrbs.T, np.dot(Sp, ImpOrbs))
    # Mp = np.dot(ImpOrbs, np.dot(sla.inv(Si), ImpOrbs.T))
    Np = np.dot(Sp, Xp)
    # print np.allclose(Np, np.dot(Np, np.dot(Mp, Np)))

    _h1 = np.dot(cf.T, np.dot(Hp + jkp - 0.5 * chempot * (Np + Np.T), cf))
    _h2 = ao2mo.incore.full(intsp, cf)

    # prepare BLOCK file, FCIDUMP
    fcidump.from_integrals('FCIDUMP', _h1, _h2, cfx.shape[1], nel)

    target = open('dmrg.inp', 'w')
    output = open('dmrg.out', 'w')
    target.write('orbitals FCIDUMP\n')
    target.write('nelec %2d\n' % nel)
    target.write('spin  %2d\n' % 0)
    target.write('irrep %2d\n' % 1)

    target.write('\nhf_occ integral\n')
    target.write('schedule\n')
    target.write(' %2d %5d %9.1e %9.1e\n' % (
        0,
        512,
        1e-10,
        1e-6,
    ))
    target.write(' %2d %5d %9.1e %9.1e\n' % (
        3,
        1024,
        1e-10,
        1e-6,
    ))
    target.write(' %2d %5d %9.1e %9.1e\n' % (
        6,
        1024,
        1e-10,
        0.0,
    ))
    target.write('end\n')
    target.write('maxiter %3d\n' % 16)
    target.write('sweep_tol %9.1e\n' % 1e-8)
    target.write('onedot\n')

    target.write('\ntwopdm\n')
    target.write('outputlevel %2d\n' % 0)
    target.close()

    subprocess.call(['mpirun', '-np', '1', block_exe, 'dmrg.inp'],
                    stdout=output)
    output.close()

    os.remove('FCIDUMP')
    os.remove('dmrg.inp')
    os.remove('dmrg.out')

    rdm2i = np.loadtxt('node0/spatial_twopdm.0.0.txt',
                       dtype=int,
                       skiprows=1,
                       usecols=(
                           0,
                           1,
                           2,
                           3,
                       ))
    rdm2t = np.loadtxt('node0/spatial_twopdm.0.0.txt',
                       dtype=float,
                       skiprows=1,
                       usecols=(4, ))

    shutil.rmtree('node0')

    rdm2 = np.zeros((cfx.shape[1], ) * 4)
    for i in range(rdm2t.shape[0]):
        rdm2[rdm2i[i, 0], rdm2i[i, 3], rdm2i[i, 1], rdm2i[i, 2]] = 2 * rdm2t[i]

    rdm1 = np.einsum('ijkk->ij', rdm2)
    rdm1 /= (nel - 1)
    del rdm2i, rdm2t

    # transform rdm's to original basis
    tei = ao2mo.restore(1, intsp, cfx.shape[1])
    rdm1 = np.dot(cf, np.dot(rdm1, cf.T))
    rdm2 = np.einsum('ai,ijkl->ajkl', cf, rdm2)
    rdm2 = np.einsum('bj,ajkl->abkl', cf, rdm2)
    rdm2 = np.einsum('ck,abkl->abcl', cf, rdm2)
    rdm2 = np.einsum('dl,abcl->abcd', cf, rdm2)

    ImpEnergy = +0.25 *np.einsum('ij,jk,ki->', 2*Hp+jkp, rdm1, Xp) \
                +0.25 *np.einsum('ij,jk,ki->', 2*Hp+jkp, Xp, rdm1) \
                +0.125*np.einsum('ijkl,ijkm,ml->', tei, rdm2, Xp) \
                +0.125*np.einsum('ijkl,ijml,mk->', tei, rdm2, Xp) \
                +0.125*np.einsum('ijkl,imkl,mj->', tei, rdm2, Xp) \
                +0.125*np.einsum('ijkl,mjkl,mi->', tei, rdm2, Xp)

    Nel = np.trace(np.dot(np.dot(rdm1, Sp), Xp))

    return Nel, ImpEnergy
Example #10
0
def test_pyscf(U=2, norb=4, periodic=False):
    nelec = norb
    n_beta = norb // 2
    n_alpha = nelec - n_beta

    # Define 1D Hubbard hamiltonian
    h1 = np.zeros((norb, norb))
    for i in range(norb - 1):
        h1[i, i + 1] = h1[i + 1, i] = -1.0
    if periodic:
        h1[norb - 1, 0] = h1[0,
                             norb - 1] = -1.0  # Periodic boundary conditions
    eri = np.zeros((norb, norb, norb, norb))
    for i in range(norb):
        eri[i, i, i, i] = U

    from pyscf.tools.fcidump import from_integrals
    from_integrals('FCIDUMP.PySCF', h1, eri, norb, nelec)

    #
    # Generally, direct_spin1.kernel is the FCI object which can handle all generic systems.
    #
    e, fcivec = fci.direct_spin1.kernel(h1, eri, norb, nelec, verbose=6)
    print('FCI Energy is {}'.format(e))

    # Alternative options below:
    #
    # A better way is to create a FCI (=FCISolver) object because FCI object offers
    # more options to control the calculation.
    #
    cisolver = fci.direct_spin1.FCI()
    cisolver.max_cycle = 100
    cisolver.conv_tol = 1e-8
    e, fcivec = cisolver.kernel(
        h1, eri, norb, (n_alpha, n_beta),
        verbose=5)  # n_alpha alpha, n_beta beta electrons
    print('FCI Energy is {}'.format(e))

    #
    # If you are sure the system ground state is singlet, you can use spin0 solver.
    # Spin symmetry is considered in spin0 solver to reduce cimputation cost.
    #
    cisolver = fci.direct_spin0.FCI()
    cisolver.verbose = 5
    e, fcivec = cisolver.kernel(h1, eri, norb, nelec)
    print('FCI Energy is {}'.format(e))

    # OPTIONAL: Perform a mean-field hartree-fock calculation, by overwriting some internal objects
    mol = gto.M(verbose=3)
    mol.nelectron = nelec
    # Setting incore_anyway=True to ensure the customized Hamiltonian (the _eri
    # attribute) to be used in the post-HF calculations.  Without this parameter,
    # some post-HF method (particularly in the MO integral transformation) may
    # ignore the customized Hamiltonian if memory is not enough.
    mol.incore_anyway = True
    mf = scf.RHF(mol)
    mf.get_hcore = lambda *args: h1
    mf.get_ovlp = lambda *args: np.eye(norb)
    mf._eri = ao2mo.restore(8, eri, norb)
    e = mf.kernel()
    print('FCI Energy is {}'.format(e))