Esempio n. 1
0
#!/usr/bin/env python
#
# Author: Qiming Sun <*****@*****.**>
#

from pyscf import gto
from pyscf import dft
from pyscf import grad

mol = gto.M(atom=[['O', (0., 0., 0)], [1, (0., -0.757, 0.587)],
                  [1, (0., 0.757, 0.587)]],
            basis='631g')

dft.RKS(mol).run(conv_tol=1e-15, xc='b3lyp').apply(grad.RKS).run()

#[[ -3.44790653e-16  -2.31083509e-15   1.21670343e-02]
# [  7.15579513e-17   2.11176116e-02  -6.08866586e-03]
# [ -6.40735965e-17  -2.11176116e-02  -6.08866586e-03]]
Esempio n. 2
0
    def test_convert_to_scf(self):
        from pyscf.x2c import x2c
        from pyscf.df import df_jk
        from pyscf.soscf import newton_ah
        addons.convert_to_rhf(dft.RKS(mol))
        addons.convert_to_uhf(dft.RKS(mol))
        #addons.convert_to_ghf(dft.RKS(mol))
        addons.convert_to_rhf(dft.UKS(mol))
        addons.convert_to_uhf(dft.UKS(mol))
        #addons.convert_to_ghf(dft.UKS(mol))
        #addons.convert_to_rhf(dft.GKS(mol))
        #addons.convert_to_uhf(dft.GKS(mol))
        #addons.convert_to_ghf(dft.GKS(mol))

        self.assertTrue(isinstance(addons.convert_to_rhf(mf), scf.rhf.RHF))
        self.assertTrue(isinstance(addons.convert_to_uhf(mf), scf.uhf.UHF))
        self.assertTrue(isinstance(addons.convert_to_ghf(mf), scf.ghf.GHF))
        self.assertTrue(isinstance(addons.convert_to_rhf(scf.UHF(mol)), scf.rhf.RHF))
        self.assertTrue(isinstance(addons.convert_to_rhf(mf_u), scf.rohf.ROHF))
        self.assertTrue(isinstance(addons.convert_to_uhf(mf_u), scf.uhf.UHF))
        self.assertTrue(isinstance(addons.convert_to_ghf(mf_u), scf.ghf.GHF))
        self.assertTrue(isinstance(addons.convert_to_rhf(sym_mf), scf.hf_symm.RHF))
        self.assertTrue(isinstance(addons.convert_to_uhf(sym_mf), scf.uhf_symm.UHF))
        self.assertTrue(isinstance(addons.convert_to_ghf(sym_mf), scf.ghf_symm.GHF))
        self.assertTrue(isinstance(addons.convert_to_rhf(sym_mf_u), scf.hf_symm.ROHF))
        self.assertTrue(isinstance(addons.convert_to_uhf(sym_mf_u), scf.uhf_symm.UHF))
        self.assertTrue(isinstance(addons.convert_to_ghf(sym_mf_u), scf.ghf_symm.GHF))

        mf1 = copy.copy(mf)
        self.assertTrue(isinstance(mf1.convert_from_(mf), scf.rhf.RHF))
        self.assertTrue(isinstance(mf1.convert_from_(mf_u), scf.rhf.RHF))
        self.assertFalse(isinstance(mf1.convert_from_(mf_u), scf.rohf.ROHF))
        self.assertTrue(isinstance(mf1.convert_from_(sym_mf), scf.rhf.RHF))
        self.assertTrue(isinstance(mf1.convert_from_(sym_mf_u), scf.rhf.RHF))
        self.assertFalse(isinstance(mf1.convert_from_(sym_mf_u), scf.rohf.ROHF))
        self.assertFalse(isinstance(mf1.convert_from_(sym_mf), scf.hf_symm.RHF))
        self.assertFalse(isinstance(mf1.convert_from_(sym_mf_u), scf.hf_symm.RHF))
        mf1 = copy.copy(mf_u)
        self.assertTrue(isinstance(mf1.convert_from_(mf), scf.uhf.UHF))
        self.assertTrue(isinstance(mf1.convert_from_(mf_u), scf.uhf.UHF))
        self.assertTrue(isinstance(mf1.convert_from_(sym_mf), scf.uhf.UHF))
        self.assertTrue(isinstance(mf1.convert_from_(sym_mf_u), scf.uhf.UHF))
        self.assertFalse(isinstance(mf1.convert_from_(sym_mf), scf.uhf_symm.UHF))
        self.assertFalse(isinstance(mf1.convert_from_(sym_mf_u), scf.uhf_symm.UHF))
        mf1 = scf.GHF(mol)
        self.assertTrue(isinstance(mf1.convert_from_(mf), scf.ghf.GHF))
        self.assertTrue(isinstance(mf1.convert_from_(mf_u), scf.ghf.GHF))
        self.assertTrue(isinstance(mf1.convert_from_(sym_mf), scf.ghf.GHF))
        self.assertTrue(isinstance(mf1.convert_from_(sym_mf_u), scf.ghf.GHF))
        self.assertFalse(isinstance(mf1.convert_from_(sym_mf), scf.ghf_symm.GHF))
        self.assertFalse(isinstance(mf1.convert_from_(sym_mf_u), scf.ghf_symm.GHF))

        self.assertTrue(isinstance(addons.convert_to_rhf(scf.RHF(mol).density_fit(), remove_df=False), df_jk._DFHF))
        self.assertTrue(isinstance(addons.convert_to_uhf(scf.RHF(mol).density_fit(), remove_df=False), df_jk._DFHF))
        self.assertTrue(isinstance(addons.convert_to_ghf(scf.RHF(mol).density_fit(), remove_df=False), df_jk._DFHF))
        self.assertTrue(isinstance(addons.convert_to_rhf(scf.UHF(mol).density_fit(), remove_df=False), df_jk._DFHF))
        self.assertTrue(isinstance(addons.convert_to_uhf(scf.UHF(mol).density_fit(), remove_df=False), df_jk._DFHF))
        self.assertTrue(isinstance(addons.convert_to_ghf(scf.UHF(mol).density_fit(), remove_df=False), df_jk._DFHF))
        #self.assertTrue(isinstance(addons.convert_to_rhf(scf.GHF(mol).density_fit(), remove_df=False),df_jk. _DFHF))
        #self.assertTrue(isinstance(addons.convert_to_uhf(scf.GHF(mol).density_fit(), remove_df=False),df_jk. _DFHF))
        self.assertTrue(isinstance(addons.convert_to_ghf(scf.GHF(mol).density_fit(), remove_df=False), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_rhf(scf.RHF(mol).density_fit(), out=scf.RHF(mol), remove_df=False), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_uhf(scf.RHF(mol).density_fit(), out=scf.UHF(mol), remove_df=False), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.RHF(mol).density_fit(), out=scf.GHF(mol), remove_df=False), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_rhf(scf.UHF(mol).density_fit(), out=scf.RHF(mol), remove_df=False), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_uhf(scf.UHF(mol).density_fit(), out=scf.UHF(mol), remove_df=False), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.UHF(mol).density_fit(), out=scf.GHF(mol), remove_df=False), df_jk._DFHF))
        #self.assertFalse(isinstance(addons.convert_to_rhf(scf.GHF(mol).density_fit(), out=scf.RHF(mol), remove_df=False),df_jk. _DFHF))
        #self.assertFalse(isinstance(addons.convert_to_uhf(scf.GHF(mol).density_fit(), out=scf.UHF(mol), remove_df=False),df_jk. _DFHF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.GHF(mol).density_fit(), out=scf.GHF(mol), remove_df=False), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_rhf(scf.RHF(mol).density_fit(), out=scf.RHF(mol), remove_df=True), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_uhf(scf.RHF(mol).density_fit(), out=scf.UHF(mol), remove_df=True), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.RHF(mol).density_fit(), out=scf.GHF(mol), remove_df=True), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_rhf(scf.UHF(mol).density_fit(), out=scf.RHF(mol), remove_df=True), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_uhf(scf.UHF(mol).density_fit(), out=scf.UHF(mol), remove_df=True), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.UHF(mol).density_fit(), out=scf.GHF(mol), remove_df=True), df_jk._DFHF))
        #self.assertFalse(isinstance(addons.convert_to_rhf(scf.GHF(mol).density_fit(), out=scf.RHF(mol), remove_df=True),df_jk. _DFHF))
        #self.assertFalse(isinstance(addons.convert_to_uhf(scf.GHF(mol).density_fit(), out=scf.UHF(mol), remove_df=True),df_jk. _DFHF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.GHF(mol).density_fit(), out=scf.GHF(mol), remove_df=True), df_jk._DFHF))

        addons.convert_to_rhf(scf.RHF(mol).x2c().density_fit())
        addons.convert_to_uhf(scf.RHF(mol).x2c().density_fit())
        addons.convert_to_ghf(scf.RHF(mol).x2c().density_fit())
        addons.convert_to_rhf(scf.UHF(mol).x2c().density_fit())
        addons.convert_to_uhf(scf.UHF(mol).x2c().density_fit())
        addons.convert_to_ghf(scf.UHF(mol).x2c().density_fit())
        #addons.convert_to_rhf(scf.GHF(mol).x2c().density_fit())
        #addons.convert_to_uhf(scf.GHF(mol).x2c().density_fit())
        addons.convert_to_ghf(scf.GHF(mol).x2c().density_fit())

        self.assertFalse(isinstance(addons.convert_to_rhf(scf.RHF(mol).x2c().newton().density_fit()), newton_ah._CIAH_SOSCF))
        self.assertFalse(isinstance(addons.convert_to_uhf(scf.RHF(mol).x2c().newton().density_fit()), newton_ah._CIAH_SOSCF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.RHF(mol).x2c().newton().density_fit()), newton_ah._CIAH_SOSCF))
        self.assertFalse(isinstance(addons.convert_to_rhf(scf.UHF(mol).x2c().newton().density_fit()), newton_ah._CIAH_SOSCF))
        self.assertFalse(isinstance(addons.convert_to_uhf(scf.UHF(mol).x2c().newton().density_fit()), newton_ah._CIAH_SOSCF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.UHF(mol).x2c().newton().density_fit()), newton_ah._CIAH_SOSCF))
        #self.assertFalse(isinstance(addons.convert_to_rhf(scf.GHF(mol).x2c().newton().density_fit()), newton_ah._CIAH_SOSCF))
        #self.assertFalse(isinstance(addons.convert_to_uhf(scf.GHF(mol).x2c().newton().density_fit()), newton_ah._CIAH_SOSCF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.GHF(mol).x2c().newton().density_fit()), newton_ah._CIAH_SOSCF))

        self.assertFalse(isinstance(addons.convert_to_rhf(scf.RHF(mol).newton().density_fit()), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_uhf(scf.RHF(mol).newton().density_fit()), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.RHF(mol).newton().density_fit()), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_rhf(scf.UHF(mol).newton().density_fit()), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_uhf(scf.UHF(mol).newton().density_fit()), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.UHF(mol).newton().density_fit()), df_jk._DFHF))
        #self.assertFalse(isinstance(addons.convert_to_rhf(scf.GHF(mol).newton().density_fit()), df_jk._DFHF))
        #self.assertFalse(isinstance(addons.convert_to_uhf(scf.GHF(mol).newton().density_fit()), df_jk._DFHF))
        self.assertFalse(isinstance(addons.convert_to_ghf(scf.GHF(mol).newton().density_fit()), df_jk._DFHF))

        self.assertTrue(isinstance(addons.convert_to_rhf(scf.RHF(mol).density_fit().newton()), df_jk._DFHF))
        self.assertTrue(isinstance(addons.convert_to_uhf(scf.RHF(mol).density_fit().newton()), df_jk._DFHF))
        self.assertTrue(isinstance(addons.convert_to_ghf(scf.RHF(mol).density_fit().newton()), df_jk._DFHF))
        self.assertTrue(isinstance(addons.convert_to_rhf(scf.UHF(mol).density_fit().newton()), df_jk._DFHF))
        self.assertTrue(isinstance(addons.convert_to_uhf(scf.UHF(mol).density_fit().newton()), df_jk._DFHF))
        self.assertTrue(isinstance(addons.convert_to_ghf(scf.UHF(mol).density_fit().newton()), df_jk._DFHF))
        #self.assertTrue(isinstance(addons.convert_to_rhf(scf.GHF(mol).density_fit().newton()), df_jk._DFHF))
        #self.assertTrue(isinstance(addons.convert_to_uhf(scf.GHF(mol).density_fit().newton()), df_jk._DFHF))
        self.assertTrue(isinstance(addons.convert_to_ghf(scf.GHF(mol).density_fit().newton()), df_jk._DFHF))
Esempio n. 3
0
from pyscf import tdscf

mol = gto.Mole()
mol.verbose = 5
mol.output = '/dev/null'
mol.atom = [
    ['H', (0., 0., .917)],
    ['F', (0., 0., 0.)],
]
mol.basis = '631g'
mol.build()

mf = scf.RHF(mol).run()
td_hf = tdscf.TDHF(mf).run()

mf_lda3 = dft.RKS(mol)
mf_lda3.xc = 'lda, vwn_rpa'
mf_lda3.grids.prune = None
mf_lda3.scf()

mf_lda = dft.RKS(mol)
mf_lda.xc = 'lda, vwn'
mf_lda.grids.prune = None
mf_lda.scf()

mf_bp86 = dft.RKS(mol)
mf_bp86.xc = 'b88,p86'
mf_bp86.grids.prune = None
mf_bp86.scf()

mf_b3lyp = dft.RKS(mol)
Esempio n. 4
0
def test_jacobs_projector(rad_type, grid_type):

    projector_type = rad_type + grid_type
    positions = np.array([[0.0, 0.0, 0.0], [-0.75846035, -0.59257417, 0.0],
                          [0.75846035, -0.59257417, 0.0]]) / xc.constants.Bohr

    if grid_type == 'euclidean':
        application = 'siesta'
    else:
        application = 'pyscf'

    if rad_type == 'ortho':
        basis_instructions = {
            'basis': {
                'n': 2,
                'l': 3,
                'r_o': 1
            },
            'projector': rad_type,
            'grid': grid_type,
            'grad': 1
        }
    else:
        basis_instructions = {
            "projector": rad_type,
            "grid": grid_type,
            "basis": {
                "file": os.path.join(test_dir, "basis-test"),
                "sigma": 2
            },
            'grad': 1
        }

    basis_instructions = ConfigFile({
        "engine": {
            "application": application
        },
        "preprocessor": basis_instructions
    })['preprocessor']
    print(basis_instructions)

    if grid_type == 'radial':
        from pyscf import dft, gto
        mol = gto.M(atom='O  0  0  0; H  0 1 0 ; H 0 0 1', basis='6-31g*')
        mf = dft.RKS(mol)
        mf.xc = 'PBE'
        mf.grids.level = 5
        mf.kernel()
        rho = pyscf.dft.numint.get_rho(mf._numint, mol, mf.make_rdm1(),
                                       mf.grids)
        print('Rho shape', rho.shape)
        print('Weights shape', mf.grids.weights.shape)
        density_projector = xc.projector.DensityProjector(
            grid_coords=mf.grids.coords,
            grid_weights=mf.grids.weights,
            basis_instructions=basis_instructions)
    else:
        density_getter = xc.utils.SiestaDensityGetter(binary=True)
        rho, unitcell, grid = density_getter.get_density(
            os.path.join(test_dir, 'h2o.RHO'))
        density_projector = xc.projector.DensityProjector(
            unitcell=unitcell,
            grid=grid,
            basis_instructions=basis_instructions)

    rho = np.stack([rho, rho])

    basis_rep = density_projector.get_basis_rep(rho,
                                                positions=positions,
                                                species=['X', 'X', 'X'])
    for key, val in basis_rep.items():
        l = val.shape[-1] // 2
        assert np.allclose(val[..., :l], val[..., l:])

    if rad_type == 'ortho':
        symmetrize_instructions = {
            'symmetrizer_type': 'trace',
            'basis': basis_instructions
        }
        sym = xc.symmetrizer.Symmetrizer(symmetrize_instructions)
        D = sym.get_symmetrized(basis_rep)['X']
        l = D.shape[-1] // 2
        assert np.allclose(D[:, :l], D[:, l:])
Esempio n. 5
0
def RKS(mol, *args):
    from pyscf import dft
    return dft.RKS(mol)
Esempio n. 6
0
# limitations under the License.

import unittest
import numpy
from pyscf import gto
from pyscf import dft
from pyscf import lib

dft.numint.SWITCH_SIZE = 0

mol = gto.Mole()
mol.verbose = 0
mol.atom = [('h', (0, 0, i * 3)) for i in range(12)]
mol.basis = 'ccpvtz'
mol.build()
mf = dft.RKS(mol)
mf.grids.atom_grid = {"H": (50, 110)}
mf.prune = None
mf.grids.build(with_non0tab=False)
nao = mol.nao_nr()
ao_loc = mol.ao_loc_nr()

h4 = gto.Mole()
h4.verbose = 0
h4.atom = 'H 0 0 0; H 0 0 9; H 0 9 0; H 0 9 9'
h4.basis = 'ccpvtz'
h4.build()
mf_h4 = dft.RKS(h4)
mf_h4.grids.atom_grid = {"H": (50, 110)}
mf_h4.grids.build(with_non0tab=True)
Esempio n. 7
0
sys.path.insert(0, './')
import inp
# Initialize geometry
geoms = read(inp.filename, ":")
geom = geoms[iconf]
symb = geom.get_chemical_symbols()
coords = geom.get_positions()
natoms = len(coords)
atoms = []
for i in range(natoms):
    coord = coords[i]
    atoms.append([symb[i], (coord[0], coord[1], coord[2])])

# Get PySCF objects for wave-function and density-fitted basis
mol = gto.M(atom=atoms, basis=inp.qmbasis)
m = dft.RKS(mol)
m.xc = inp.functional
# Save density matrix
m.kernel()

#ks_scanner = m.apply(grad.RKS).as_scanner()
#etot, grad = ks_scanner(mol)
#
#f = open("gradients/grad_conf"+str(iconf+1)+".dat","w")
#for i in range(natoms):
#    print >> f, symb[i], grad[i,0], grad[i,1], grad[i,2]
#f.close()

dm = m.make_rdm1()

dirpath = os.path.join(inp.path2qm, "density_matrices")
Esempio n. 8
0
             O     0.0000250    0.0415622   -3.4549197
             C    -0.0000028   -2.3369861    0.0065791
             O     0.0000240   -3.4513475    0.0412328
             C     0.0000037    2.3369862   -0.0065788
             O    -0.0000326    3.4513476   -0.0412324
''',
    basis='bfd-vtz',
    ecp='bfd',
    unit="angstrom",
    spin=4,
    verbose=5,
    cart=False,
    charge=2,
)

mf = dft.RKS(cell).density_fit()
#mf = dft.RKS(cell)
mf.xc = 'b3lyp'
#mf.chkfile = 'FeCO6.chk'
#dm = mf.from_chk('FeCO6.chk')
mf.chkfile = 'FeCO6-spherical.chk'
dm = mf.from_chk('FeCO6-spherical.chk')
mf.kernel(dm)
#mf.kernel()

title = 'FeCO6'
kpts = []

from PyscfToQmcpack import savetoqmcpack
savetoqmcpack(cell, mf, title=title, kpts=kpts)
Esempio n. 9
0
#!/usr/bin/env python
'''
Frequency and normal modes
'''

from pyscf import gto, dft
from pyscf.prop.freq import rks

mol = gto.M(atom='''
            O 0 0      0
            H 0 -0.757 0.587
            H 0  0.757 0.587''',
            basis='ccpvdz',
            verbose=4)
mf = dft.RKS(mol).run()

w, modes = rks.Freq(mf).kernel()
Esempio n. 10
0
#

from pyscf import gto, dft

'''
A simple example to run DFT calculation.

See pyscf/dft/vxc.py for the complete list of available XC functional
'''

mol = gto.Mole()
mol.build(
    atom = 'H 0 0 0; F 0 0 1.1',  # in Angstrom
    basis = '631g',
    symmetry = True,
)

mydft = dft.RKS(mol)
#mydft.xc = 'lda,vwn'
#mydft.xc = 'lda,vwn_rpa'
#mydft.xc = 'b86,p86'
#mydft.xc = 'b88,lyp'
#mydft.xc = 'b97,pw91'
#mydft.xc = 'b3p86'
#mydft.xc = 'o3lyp'
mydft.xc = 'b3lyp'
mydft.kernel()

# Orbital energies, Mulliken population etc.
mydft.analyze()
Esempio n. 11
0
H   0.870464   0.870464  -2.783308
C  -0.471925   0.471925   1.859111
C   0.471925  -0.471925   1.859111
H  -0.872422   0.872422   0.936125
H   0.872422  -0.872422   0.936125
H  -0.870464   0.870464   2.783308
H   0.870464  -0.870464   2.783308
'''
mol.basis = 'aug-cc-pvdz'
mol.charge = 0
mol.spin = 0
mol.symmetry = 0
mol.verbose = 4
mol.build()

mf_grad_scan = dft.RKS(mol).nuc_grad_method().as_scanner()
mf_grad_scan.base = scf.addons.remove_linear_dep_(mf_grad_scan.base)
mf_grad_scan.base.level_shift = 0.2
mf_grad_scan.base.verbose = 4
mf_grad_scan.base.xc = 'pbe0'
mf_grad_scan.base.grids.level = 3
mf_grad_scan.base.grids.prune = dft.gen_grid.nwchem_prune
mf_grad_scan.grid_response = False


def mf_grad_with_dftd3(geom):
    e_tot, g_rhf = mf_grad_scan(geom)
    mol = mf_grad_scan.mol
    func = 'pbe0'
    version = 4
    tz = 0
Esempio n. 12
0
        else:
            return 0


Grad = Gradients

if __name__ == '__main__':
    from pyscf import gto
    from pyscf import dft

    mol = gto.Mole()
    mol.atom = [['O', (0., 0., 0.)], [1, (0., -0.757, 0.587)],
                [1, (0., 0.757, 0.587)]]
    mol.basis = '631g'
    mol.build()
    mf = dft.RKS(mol).density_fit(auxbasis='ccpvdz-jkfit')
    mf.conv_tol = 1e-14
    e0 = mf.scf()
    g = Gradients(mf).set(auxbasis_response=False)
    print(lib.finger(g.kernel()) - -0.04993147565973481)
    g = Gradients(mf)
    print(lib.finger(g.kernel()) - -0.04990283616418435)
    # O     0.0000000000    -0.0000000000     0.0210278440
    # H    -0.0000000000     0.0282041778    -0.0105201841
    # H    -0.0000000000    -0.0282041778    -0.0105201841
    g.grid_response = True
    print(lib.finger(g.kernel()) - -0.04990623599165457)
    # O     0.0000000000    -0.0000000000     0.0210353722
    # H    -0.0000000000     0.0282046127    -0.0105176861
    # H    -0.0000000000    -0.0282046127    -0.0105176861
Esempio n. 13
0
 def test_nr_rks_fast_newton(self):
     mf = dft.RKS(h4_z0_s)
     mf.xc = 'b3lyp'
     mf1 = scf.fast_newton(mf)
     self.assertAlmostEqual(mf1.e_tot, -40.10277421254213, 9)
Esempio n. 14
0
mol.unit = "Angstrom"
mol.max_memory = 40000
mol.spin = 0
mol.charge = 0
mol.output = "_logs/_sa_mcscf.out"
mol.basis = "ccpvdz"
mol.build()

#
# Mean Field Calculation
#

# places the charge close to where the hydrogen in COO--H--OOC used to be
# (-7.0947 ± 0.1190, -3.0432 ± 0.0676, 0.1083 ± 0.6237)
chg_coords = np.array([[-7.0947, -3.0432, 0.1083]])
mf = qmmm.mm_charge(dft.RKS(mol), chg_coords, [-1.0])
mf.xc = "b3lyp"
mf.chkfile = "_chk/pp_anion_pt_chg_dz_b3lyp.chk"
mf.kernel()
# mf.analyze()

#
# Dump orbitals
#
molden.dump_scf(mf, "_molden/pp_anion_pt_chg_dz_b3lyp.molden")

#
# SA-MCSCF
#
nelecas, ncas = (4, 4)
n_states = 3
Esempio n. 15
0

if __name__ == '__main__':
    from pyscf import gto
    from pyscf import dft
    #dft.numint.NumInt.libxc = dft.xcfun
    xc_code = 'b3lyp'

    mol = gto.Mole()
    mol.verbose = 0
    mol.output = None
    mol.atom = [
        [1, (1., 0., 0.000)],
        [1, (0., 1., 0.000)],
        [1, (0., -1.517, 1.177)],
        [1, (0., 1.517, 1.177)],
    ]
    mol.basis = '631g'
    mol.unit = 'B'
    mol.build()
    mf = dft.RKS(mol).density_fit()
    mf.grids.level = 4
    mf.grids.prune = False
    mf.xc = xc_code
    mf.conv_tol = 1e-14
    mf.kernel()
    n3 = mol.natm * 3
    hobj = Hessian(mf)
    e2 = hobj.kernel().transpose(0, 2, 1, 3).reshape(n3, n3)
    print(lib.finger(e2) - -0.41387283263786201)
Esempio n. 16
0
import numpy
from pyscf import lib
from pyscf import gto, dft
from pyscf import tdscf
from pyscf.grad import tdrks as tdrks_grad

mol = gto.Mole()
mol.verbose = 0
mol.output = None
mol.atom = [
    ['H' , (0. , 0. , 1.804)],
    ['F' , (0. , 0. , 0.)], ]
mol.unit = 'B'
mol.basis = '631g'
mol.build()
mf_lda = dft.RKS(mol).set(xc='LDA,')
mf_lda.grids.prune = False
mf_lda.kernel()
mf_gga = dft.RKS(mol).set(xc='b88,')
mf_gga.grids.prune = False
mf_gga.kernel()

def tearDownModule():
    global mol, mf_lda
    del mol, mf_lda

class KnownValues(unittest.TestCase):
    def test_tda_singlet_lda(self):
        td = tdscf.TDA(mf_lda).run(nstates=3)
        tdg = td.nuc_grad_method()
        g1 = tdg.kernel(td.xy[2])
Esempio n. 17
0

if __name__ == '__main__':
    from pyscf import lib
    from pyscf import gto
    from pyscf import dft
    mol = gto.Mole()
    mol.verbose = 7
    mol.output = '/dev/null'
    mol.atom = '''h  ,  0.   0.   .917
                  F  ,  0.   0.   0.
                  '''
    mol.basis = 'ccpvdz'
    mol.build()

    mf = dft.RKS(mol).run(xc='b3lyp')
    rotg = mf.RotationalGTensor()
    m = rotg.kernel()
    print(m[0,0] - 0.6944660741142765)

    rotg.gauge_orig = (0,0,.1)
    m = rotg.kernel()
    print(m[0,0] - 0.7362841753490392)

    mol.atom = '''C  ,  0.   0.   0.
                  O  ,  0.   0.   1.1283
                  '''
    mol.basis = 'ccpvdz'
    mol.build()
    mf = dft.RKS(mol).run(xc='bp86')
    rotg = RotationalGTensor(mf)
Esempio n. 18
0
 def test_reset(self):
     mf = dft.RKS(h2o).newton()
     mf.reset(h2osym)
     self.assertTrue(mf.mol is h2osym)
     self.assertTrue(mf.grids.mol is h2osym)
     self.assertTrue(mf.nlcgrids.mol is h2osym)
Esempio n. 19
0
from pyscf.prop.polarizability.rhf import \
        (polarizability, hyper_polarizability, polarizability_with_freq,
         Polarizability)

if __name__ == '__main__':
    import numpy
    from pyscf import gto
    from pyscf import dft
    mol = gto.Mole()
    mol.atom = '''h  ,  0.   0.   0.
                  F  ,  0.   0.   .917'''
    mol.basis = '631g'
    mol.build()

    mf = dft.RKS(mol).run(xc='b3lyp', conv_tol=1e-14)
    polar = Polarizability(mf).polarizability()
    hpol = Polarizability(mf).hyper_polarizability()
    print(polar)

    mf.verbose = 0
    charges = mol.atom_charges()
    coords = mol.atom_coords()
    charge_center = numpy.einsum('i,ix->x', charges, coords) / charges.sum()
    with mol.with_common_orig(charge_center):
        ao_dip = mol.intor_symmetric('int1e_r', comp=3)
    h1 = mf.get_hcore()

    def apply_E(E):
        mf.get_hcore = lambda *args, **kwargs: h1 + numpy.einsum(
            'x,xij->ij', E, ao_dip)
Esempio n. 20
0
num_frozen_cores = int(
    results.frozen_cores) if results.frozen_cores is not None else 0

sys.argv = [sys.argv[0]]

# -----------------------
#     PYSCF
# -----------------------

mol = gto.M(atom=atomic_coords,
            basis=basis_set,
            spin=spin,
            charge=charge,
            verbose=5)

my_dft = dft.RKS(mol)
my_dft.xc = functional
if density_fit:
    my_dft = my_dft.density_fit()
    my_dft.with_df.auxbasis = aux_basis_set
my_dft.run()

my_tddft = tddft.TDDFT(my_dft)
# my_tddft.nstates = 10
my_tddft.kernel()
excitation_energies = (my_tddft.e * 27.2114).tolist()

properties = {
    "excitationEnergies": excitation_energies,
}
stringified_properties = json.dumps(properties)
Esempio n. 21
0
#!/usr/bin/env python
#
# Author: Qiming Sun <*****@*****.**>
#
'''
The TDDFT calculations by default use the same XC functional, grids, _numint
schemes as the ground state DFT calculations.  Different XC, grids, _numint
can be set in TDDFT.
'''

import copy
from pyscf import gto, dft, tddft

mol = gto.M(atom='N 0 0 0; N 0 0 1', basis='6-31g*')
mf = dft.RKS(mol).run(xc='pbe0')

#
# A common change for TDDFT is to use different XC functional library.  For
# example, PBE0 is not supported by the default XC library (libxc) in the TDDFT
# calculation.  Changing to xcfun library for TDDFT can solve this problem
#
mf._numint.libxc = dft.xcfun
# PySCF-1.6.1 and newer supports the .TDDFT method to create a TDDFT
# object after importing tdscf module.
td = mf.TDDFT()
print(td.kernel()[0] * 27.2114)

#
# Overwriting the relevant attributes of the ground state mf object,
# the TDDFT calculations can be run with different XC, grids.
#
Esempio n. 22
0
 def test_nr_lda_1e(self):
     mf = dft.RKS(mol1).run()
     self.assertAlmostEqual(mf.e_tot, -1.936332393935281, 9)
Esempio n. 23
0

if __name__ == '__main__':
    from pyscf import gto
    from pyscf import dft
    mol = gto.Mole()
    mol.verbose = 0
    mol.output = None

    mol.atom = [
        ['Ne', (0., 0., 0.)],
    ]
    mol.basis = '631g'
    mol.build()

    mf = dft.RKS(mol).run()
    mag = Magnetizability(mf).kernel()
    print(lib.finger(mag) - -0.30375149255154221)

    mf.set(xc='b3lyp').run()
    mag = Magnetizability(mf).kernel()
    print(lib.finger(mag) - -0.3022331813238171)

    mol.atom = [
        [1, (0., 0., .917)],
        ['F', (0., 0., 0.)],
    ]
    mol.basis = '6-31g'
    mol.build()

    mf = dft.RKS(mol).set(xc='lda,vwn').run()
Esempio n. 24
0
        
    else:
        rho01=rho02=rho*0.5

    rho0=np.concatenate((rho01.reshape((-1,1)),rho02.reshape((-1,1))),axis=1)
    N=rho0.shape[0]
    x=Variable(torch.Tensor(rho0),requires_grad=True)
    pred_exc=model(x)
    exc=pred_exc.data[:,0].numpy()
    eneden=torch.dot(pred_exc[:,0],x[:,0]+x[:,1])
    eneden.backward()
    grad=x.grad.data.numpy()

    if spin!=0:
        vrho=np.hstack((grad[:,0].reshape((-1,1)),grad[:,1].reshape((-1,1))))

    else:
        vlapl=np.zeros(N)    
        vrho=(grad[:,0]+grad[:,1])/2
    vxc=(vrho, None, None, None)
    return exc, vxc, None, None

# DFT calculation #
if mol.spin==0:
    mfl = dft.RKS(mol)
else:
    mfl = dft.UKS(mol)

mfl = mfl.define_xc_(eval_xc, 'LDA')
mfl.kernel()
Esempio n. 25
0
            mo[:, nmo + noccb:]
        ])
    else:
        log.note(
            'UHF/UKS wavefunction is stable in the UHF/UKS -> GHF/GKS stability analysis'
        )
    return mo


if __name__ == '__main__':
    from pyscf import gto, scf, dft
    mol = gto.M(atom='O 0 0 0; O 0 0 1.2222', basis='631g*')
    mf = scf.RHF(mol).run()
    rhf_stability(mf, True, True, verbose=4)

    mf = dft.RKS(mol).run(level_shift=.2)
    rhf_stability(mf, True, True, verbose=4)

    mf = scf.UHF(mol).run()
    mo1 = uhf_stability(mf, True, True, verbose=4)[0]

    mf = scf.newton(mf).run(mo1, mf.mo_occ)
    uhf_stability(mf, True, False, verbose=4)
    mf = scf.newton(scf.UHF(mol)).run()
    uhf_stability(mf, True, False, verbose=4)

    mol.spin = 2
    mf = scf.UHF(mol).run()
    uhf_stability(mf, True, True, verbose=4)

    mf = dft.UKS(mol).run()
Esempio n. 26
0
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: Qiming Sun <*****@*****.**>
#

'''
Non-relativistic RKS spin-spin coupling (SSC) constants
'''

# RHF and RKS have the same code for SSC tensors
from pyscf.prop.ssc.rhf import SpinSpinCoupling, SSC
from pyscf.prop.ssc.rhf import make_dso, make_pso

if __name__ == '__main__':
    from pyscf import gto, lib, dft
    mol = gto.M(atom='''
                O 0 0      0
                H 0 -0.757 0.587
                H 0  0.757 0.587''',
                basis='6-31g', verbose=3)

    mf = dft.RKS(mol).set(xc='b3lyp').run()
    ssc = mf.SSC()
    ssc.with_fc = True
    ssc.with_fcsd = True
    jj = ssc.kernel()
    print(lib.finger(jj)*1e8 - -0.33428832201108766)
Esempio n. 27
0
  Na - Ar       80           434
  K  - Kr       90           434
  Rb - Xe       95           434
  Cs - Rn      100           434
  ===================================

See pyscf/dft/gen_grid.py  "class Grids" for more details.
'''

mol = gto.M(verbose=0,
            atom='''
    o    0    0.       0.
    h    0    -0.757   0.587
    h    0    0.757    0.587''',
            basis='6-31g')
method = dft.RKS(mol)
print('Default DFT(LDA).  E = %.12f' % method.kernel())

# See pyscf/dft/radi.py for more radial grid schemes
#grids.radi_method = dft.gauss_chebeshev
#grids.radi_method = dft.delley
method = dft.RKS(mol)
method.grids.radi_method = dft.mura_knowles
print('Changed radial grids for DFT.  E = %.12f' % method.kernel())

# See pyscf/dft/gen_grid.py for detail of the grid weight scheme
#method.grids.becke_scheme = dft.original_becke
# Stratmann-Scuseria weight scheme
method = dft.RKS(mol)
method.grids.becke_scheme = dft.stratmann
print('Changed grid partition funciton.  E = %.12f' % method.kernel())
Esempio n. 28
0
 def test_nr_rks(self):
     mf = cosmo.cosmo_(dft.RKS(mol))
     mf.xc = 'b3lypg'
     mf.conv_tol = 1e-11
     self.assertAlmostEqual(mf.kernel(), -76.407553915, 9)
Esempio n. 29
0
    from pyscf import gto
    from pyscf import scf
    from pyscf import dft
    from pyscf import tddft
    mol = gto.Mole()
    mol.verbose = 0
    mol.output = None

    mol.atom = [
        ['H' , (0. , 0. , 1.804)],
        ['F' , (0. , 0. , 0.)], ]
    mol.unit = 'B'
    mol.basis = '631g'
    mol.build()

    mf = dft.RKS(mol)
    mf.xc = 'LDA,'
    mf.grids.prune = False
    mf.conv_tol = 1e-14
#    mf.grids.level = 6
    mf.scf()

    td = tddft.TDDFT(mf)
    td.nstates = 3
    e, z = td.kernel()
    tdg = td.Gradients()
    g1 = tdg.kernel(state=3)
    print(g1)
# [[ 0  0  -1.31315477e-01]
#  [ 0  0   1.31319442e-01]]
    td_solver = td.as_scanner()
Esempio n. 30
0
def do_scf(inp):
    '''Do the requested SCF.'''

    from pyscf import gto, scf, dft, cc, fci, ci, ao2mo, mcscf, mrpt, lib, mp, tdscf
    from pyscf.cc import ccsd_t, uccsd_t
    import numpy as np
    from .fcidump import fcidump

    # sort out the method
    mol = inp.mol
    method = inp.scf.method.lower()

    # UHF
    if method == 'uhf':
        ehf, mSCF = do_hf(inp, unrestricted=True)
        print_energy('UHF', ehf)

        if inp.scf.exci is not None:
            inp.timer.start('TDHF')
            mtd = do_TDDFT(inp, mSCF)
            inp.timer.end('TDHF')

    # RHF
    elif method in ('rhf', 'hf'):
        ehf, mSCF = do_hf(inp)
        print_energy('RHF', ehf)

        if inp.scf.exci is not None:
            inp.timer.start('TDHF')
            mtd = do_TDDFT(inp, mSCF)
            inp.timer.end('TDHF')

    # CCSD and CCSD(T)
    elif method in ('ccsd', 'ccsd(t)', 'uccsd', 'uccsd(t)', 'eomccsd'):
        if 'u' in method:
            ehf, tSCF = do_hf(inp, unrestricted=True)
            print_energy('UHF', ehf)
        else:
            ehf, tSCF = do_hf(inp)
            print_energy('RHF', ehf)

        inp.timer.start('ccsd')
        frozen = 0
        if inp.scf.freeze is not None: frozen = inp.scf.freeze
        if 'u' in method:
            mSCF = cc.UCCSD(tSCF, frozen=frozen)
        else:
            mSCF = cc.CCSD(tSCF, frozen=frozen)
        mSCF.max_cycle = inp.scf.maxiter
        eccsd, t1, t2 = mSCF.kernel()
        print_energy('CCSD', ehf + eccsd)
        inp.timer.end('ccsd')

        if method == 'eomccsd':
            inp.timer.start('eomccsd')
            ee = mSCF.eomee_ccsd_singlet(nroots=4)[0]
            inp.timer.end('eomccsd')
            for i in range(len(ee)):
                print_energy('EOM-CCSD {0} (eV)'.format(i+1), ee[i] * 27.2114)

        if method in ('ccsd(t)', 'uccsd(t)'):
            inp.timer.start('ccsd(t)')
            eris = mSCF.ao2mo()

            if method == 'ccsd(t)':
                e3 = ccsd_t.kernel(mSCF, eris)
            else:
                e3 = uccsd_t.kernel(mSCF, eris)
            print_energy('CCSD(T)', ehf + eccsd + e3)
            inp.timer.end('ccsd(t)')

    # MP2
    elif method == 'mp2':
        ehf, tSCF = do_hf(inp)
        print_energy('RHF', ehf)

        inp.timer.start('mp2')
        frozen = 0 
        if inp.scf.freeze is not None: frozen = inp.scf.freeze
        mSCF = mp.MP2(tSCF, frozen=frozen)
        emp2, t2 = mSCF.kernel()
        print_energy('MP2', ehf+emp2)
        inp.timer.end('mp2')

    # CISD
    elif method == 'cisd' or method == 'cisd(q)':
        ehf, tSCF = do_hf(inp)
        print_energy('RHF', ehf)

        inp.timer.start('cisd')
        frozen = 0
        if inp.scf.freeze is not None: frozen = inp.scf.freeze
        mSCF = ci.CISD(tSCF, frozen=frozen)
        ecisd = mSCF.kernel()[0]
        print_energy('CISD', ehf + ecisd)
        inp.timer.end('cisd')

        # perform Davison quadruples correction
        c0 = np.max(np.abs(mSCF.ci))
        c02 = c0**2
        ne = mSCF.mol.nelectron
        eq = ( 1.0 - c02 ) * ecisd
        print_energy('CISD(Q) Davidson', ehf + ecisd + eq)
        eq = ( 1.0 - c02 ) / c02 * ecisd
        print_energy('CISD(Q) Renomalized-Davidson', ehf + ecisd + eq)
        eq = ( 1.0 - c02 ) / ( 2.0 * c02 - 1.0 ) * ecisd
        print_energy('CISD(Q) Davison-Silver', ehf + ecisd + eq)
        eq = (( 2.0 * c02 ) / ((2.0*c02-1.0)*(1.0 + np.sqrt(1.0 + (8.0*c02*(1.0-c02))
         / ( ne * (2.0*c02-1.0)**2 )))) - 1.0 ) * ecisd
        print_energy('CISD(Q) PC', ehf + ecisd + eq)
        eq = ( 1.0 - c02 ) / c02 * ((ne-2)*(ne-3.0)) / (ne*(ne-1.0)) * ecisd
        print_energy('CISD(Q) MC', ehf + ecisd + eq)
        if ne > 2:
            eq = ( 2.0 - c02 ) / (2.0 * (ne-1.0)/(ne-2.0) * c02 - 1.0)
        else:
            eq = 0.0
        print_energy('CISD(Q) DD', ehf + ecisd + eq)


    # UKS
    elif method in ('uks' or 'udft'):
        inp.timer.start('uks')
        inp.timer.start('grids')
        grids = dft.gen_grid.Grids(mol)
        grids.level = inp.scf.grid
        grids.build()
        inp.timer.end('grids')
        mSCF = dft.UKS(mol)
        mSCF.grids = grids
        mSCF.xc = inp.scf.xc
        mSCF.conv_tol = inp.scf.conv
        mSCF.conv_tol_grad = inp.scf.grad
        mSCF.max_cycle = inp.scf.maxiter
        mSCF.init_guess = inp.scf.guess
        mSCF.small_rho_cutoff = 1e-20
        eks = mSCF.kernel()
        print_energy('UKS', eks)
        inp.timer.end('uks')

        if inp.scf.exci is not None:
            inp.timer.start('TDDFT')
            mtd = do_TDDFT(inp, mSCF)
            inp.timer.end('TDDFT')

    # RKS
    elif method in ('rks', 'ks', 'rdft', 'dft'):
        inp.timer.start('ks')
        inp.timer.start('grids')
        grids = dft.gen_grid.Grids(mol)
        grids.level = inp.scf.grid
        grids.build()
        inp.timer.end('grids')
        if mol.nelectron%2 == 0:
            mSCF = dft.RKS(mol)
        else:
            mSCF = dft.ROKS(mol)
        mSCF.grids = grids
        mSCF.xc = inp.scf.xc
        mSCF.conv_tol = inp.scf.conv
        mSCF.conv_tol_grad = inp.scf.grad
        mSCF.max_cycle = inp.scf.maxiter
        mSCF.init_guess = inp.scf.guess
        mSCF.small_rho_cutoff = 1e-20
        mSCF.damp = inp.scf.damp
        mSCF.level_shift = inp.scf.shift
        eks = mSCF.kernel()
        print_energy('RKS', eks)
        inp.timer.end('ks')

        if inp.scf.exci is not None:
            inp.timer.start('TDDFT')
            mtd = do_TDDFT(inp, mSCF)
            inp.timer.end('TDDFT')

    # Unrestricted FCI
    elif method == 'ufci':
        ehf, mSCF = do_hf(inp, unrestricted=True)
        print_energy('UHF', ehf)

        inp.timer.start('fci')
        cis = fci.direct_uhf.FCISolver(mol)
        norb = mSCF.mo_energy[0].size
        nea = (mol.nelectron+mol.spin) // 2
        neb = (mol.nelectron-mol.spin) // 2
        nelec = (nea, neb)
        mo_a = mSCF.mo_coeff[0]
        mo_b = mSCF.mo_coeff[1]
        h1e_a = reduce(np.dot, (mo_a.T, mSCF.get_hcore(), mo_a))
        h1e_b = reduce(np.dot, (mo_b.T, mSCF.get_hcore(), mo_b))
        g2e_aa = ao2mo.incore.general(mSCF._eri, (mo_a,)*4, compact=False)
        g2e_aa = g2e_aa.reshape(norb,norb,norb,norb)
        g2e_ab = ao2mo.incore.general(mSCF._eri, (mo_a,mo_a,mo_b,mo_b), compact=False)
        g2e_ab = g2e_ab.reshape(norb,norb,norb,norb)
        g2e_bb = ao2mo.incore.general(mSCF._eri, (mo_b,)*4, compact=False)
        g2e_bb = g2e_bb.reshape(norb,norb,norb,norb)
        h1e = (h1e_a, h1e_b)
        eri = (g2e_aa, g2e_ab, g2e_bb)

        eci = fci.direct_uhf.kernel(h1e, eri, norb, nelec)[0]
        print_energy('FCI', eci)
        inp.timer.end('fci')

    # FCI
    elif method in ('fci'):
        ehf, mSCF = do_hf(inp)
        print_energy('RHF', ehf)

        inp.timer.start('fci')
        if inp.scf.freeze is None:
            mCI = fci.FCI(mSCF)
            if inp.scf.roots is not None:
                mCI.nroots = inp.scf.roots
            mCI.kernel()[0]
            eci = mCI.eci

        else:
            nel  = mol.nelectron - inp.scf.freeze * 2
            ncas = mol.nao_nr() - inp.scf.freeze
            if mol.spin == 0:
                nelecas = nel
                mCI = mcscf.CASCI(mSCF, ncas, nelecas)
                mCI.fcisolver = fci.solver(mol)
            else:
                if mol.spin%2 == 0:
                    nelecas = (nel//2+mol.spin//2, nel//2-mol.spin//2)
                else:
                    nelecas = (nel//2+mol.spin//2+1, nel//2-mol.spin//2)
                mCI = mcscf.CASCI(mSCF, ncas, nelecas)
                mCI.fcisolver = fci.direct_spin1.FCISolver(mol)
            eci = mCI.kernel()[0]
            dm = mCI.make_rdm1()
            dip = mSCF.dip_moment(dm=dm)

        if inp.scf.roots is None:
            print_energy('FCI', eci)
        else:
            for i in range(inp.scf.roots):
                print_energy('FCI {0}'.format(i), eci[i])
        inp.timer.end('fci')

    # CASCI
    elif method == 'casci':
        if inp.scf.cas is None and inp.scf.casorb is None:
            print ('ERROR: Must specify CAS space or CASORB')
            return inp

        ehf, mSCF = do_hf(inp)
        print_energy('RHF', ehf)

        # get cas space
        if inp.scf.cas is not None:
            if mol.spin == 0:
                nelecas = inp.scf.cas[0]
            else:
                nelecas = (inp.scf.cas[0]//2 + mol.spin//2,
                           inp.scf.cas[0]//2 - mol.spin//2)
            ncasorb = inp.scf.cas[1]
        elif inp.scf.casorb is not None:
            ncasorb = len(inp.scf.casorb)
            nelecas = int(np.sum(mSCF.mo_occ[inp.scf.casorb]))
            if inp.scf.casspin is not None:
                nelecas = (nelecas//2 + inp.scf.casspin//2,
                           nelecas//2 - inp.scf.casspin//2)

        inp.timer.start('casci')
        mCI = mcscf.CASCI(mSCF, ncasorb, nelecas)

        if inp.scf.casorb is not None:
            mo = mcscf.addons.sort_mo(mCI, np.copy(mSCF.mo_coeff), inp.scf.casorb, 0)
        else:
            mo = np.copy(mSCF.mo_coeff)

        eci = mCI.kernel(mo)[0]
        print_energy('CASCI', eci)
        inp.timer.end('casci')

    # CASSCF
    elif method == 'casscf' or method == 'ucasscf':
        if inp.scf.cas is None and inp.scf.casorb is None:
            print ('ERROR: Must specify CAS space or CASORB')
            return inp

        lunrestricted = (method == 'ucasscf')
        ehf, mSCF = do_hf(inp, unrestricted=lunrestricted)
        print_energy('HF', ehf)

        # get cas space
        if inp.scf.cas is not None:
            if mol.spin == 0:
                nelecas = inp.scf.cas[0]
            else:
                nelecas = (inp.scf.cas[0]//2 + mol.spin//2,
                           inp.scf.cas[0]//2 - mol.spin//2)
            ncasorb = inp.scf.cas[1]
        elif inp.scf.casorb is not None:
            ncasorb = len(inp.scf.casorb)
            nelecas = int(np.sum(mSCF.mo_occ[inp.scf.casorb]))
            if inp.scf.casspin is not None:
                nelecas = (nelecas//2 + inp.scf.casspin//2,
                           nelecas//2 - inp.scf.casspin//2)

        inp.timer.start('casscf')
        mCI = mcscf.CASSCF(mSCF, ncasorb, nelecas)

        if inp.scf.casorb is not None:
            mo = mcscf.addons.sort_mo(mCI, np.copy(mSCF.mo_coeff), inp.scf.casorb, 0)
        else:
            mo = np.copy(mSCF.mo_coeff)

        eci = mCI.kernel(mo)[0]
        print_energy('CASSCF', eci)
        inp.timer.end('casscf')

    # NEVPT2
    elif method == 'nevpt2' or method == 'unevpt2':
        if inp.scf.cas is None and inp.scf.casorb is None:
            print ('ERROR: Must specify CAS space or CASORB')
            return inp

        ehf, mSCF = do_hf(inp)
        print_energy('RHF', ehf)

        inp.timer.start('casscf')

        # get cas space
        if inp.scf.cas is not None:
            if mol.spin == 0:
                nelecas = inp.scf.cas[0]
            else:
                nelecas = (inp.scf.cas[0]//2 + mol.spin//2,
                           inp.scf.cas[0]//2 - mol.spin//2)
            ncasorb = inp.scf.cas[1]
        elif inp.scf.casorb is not None:
            ncasorb = len(inp.scf.casorb)
            nelecas = int(np.sum(mSCF.mo_occ[inp.scf.casorb]))
            if inp.scf.casspin is not None:
                nelecas = (nelecas//2 + inp.scf.casspin//2,
                           nelecas//2 - inp.scf.casspin//2)

        mCI = mcscf.CASSCF(mSCF, ncasorb, nelecas, frozen=inp.scf.freeze)

        if inp.scf.casorb is not None:
            mo = mcscf.addons.sort_mo(mCI, np.copy(mSCF.mo_coeff), inp.scf.casorb, 0)
        else:
            mo = np.copy(mSCF.mo_coeff)

        eci = mCI.kernel(mo)[0]
        print_energy('CASSCF', eci)
        inp.timer.end('casscf')

        inp.timer.start('nevpt2')
        mpt2 = mrpt.NEVPT(mCI)
        ept2 = mpt2.kernel() + eci
        print_energy('NEVPT2', ept2)
        inp.timer.end('nevpt2')

    else:
        print ('ERROR: Unrecognized SCF method!')
        raise SystemExit

    # dump fcidump file if needed
    if inp.fcidump:
        if inp.filename[-4:].lower() == '.inp':
            fcifile = inp.filename[:-4] + '.fcidump'
        else:
            fcifile = inp.filename + '.fcidump'
        fcidump(mSCF, filename=fcifile, tol=1e-6)

    # plot MOs if needed
    if inp.mo2cube:
        from .mo_2_cube import save_MOs
        save_MOs(inp, mSCF, mSCF.mo_coeff)

    # save molden file if needed
    if inp.molden:
        from pyscf.tools import molden
        molden_file = inp.filename[:-4] + '.molden'
        molden.from_mo(inp.mol, molden_file, mSCF.mo_coeff, ene=mSCF.mo_energy)

    # save and return
    inp.mf = mSCF
    return inp