def test_nr_uhf(self): mol = gto.M( verbose = 5, output = '/dev/null', atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ], basis = '6-31g', charge = 1, spin = 1, ) mf = scf.UHF(mol) mf.max_cycle = 1 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 50 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.58051984397145, 9) mf.max_cycle = 2 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 50 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.58051984397145, 9)
def test_nr_uks(self): from pyscf import dft mol = gto.M( verbose = 5, output = '/dev/null', atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ], basis = '6-31g', charge = 1, spin = 1, ) mf = dft.UKS(mol) mf.xc = 'b3lyp' eref = mf.kernel() mf.max_cycle = 1 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 50 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), eref, 7) mf.max_cycle = 2 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 50 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), eref, 7)
def test_nr_rhf_symm(self): mol = gto.M( verbose = 5, output = '/dev/null', atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ], symmetry = 1, basis = '6-31g') mf = scf.RHF(mol) mf.max_cycle = 1 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 50 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.98394849812, 9) mf.max_cycle = 2 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 50 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.98394849812, 9)
def test_nr_rhf_symm(self): mf = scf.RHF(h2o_z0_s) mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.98394849812, 9)
def test_nr_rhf(self): mf = scf.RHF(h2o_z0) mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.98394849812, 9)
def test_nr_rohf(self): mf = scf.RHF(h2o_z1) mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.5783963795897, 9)
def test_nr_uhf_symm(self): mf = scf.UHF(h2o_z1_s) mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.58051984397145, 9)
def test_nr_rohf(self): mf = scf.RHF(h2o_z1) mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.5783963795897, 9)
def test_nr_uhf_symm(self): mf = scf.UHF(h2o_z1_s) mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.58051984397145, 9)
def test_nr_rohf_symm(self): mf = scf.RHF(h2o_z1_s) mf.irrep_nelec['B2'] = (1,0) mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.578396379589819, 9)
def test_nr_rks_lda(self): mf = dft.RKS(h2o_z0) eref = mf.kernel() mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 3 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), eref, 9)
def test_nr_rohf_symm(self): mf = scf.RHF(h2o_z1_s) mf.irrep_nelec['B2'] = (1, 0) mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.578396379589819, 9)
def test_nr_rks_lda(self): mf = dft.RKS(h2o_z0) eref = mf.kernel() mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 3 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), eref, 9)
def test_nr_uks(self): mf = dft.UKS(h2o_z1) mf.xc = 'b3lyp' eref = mf.kernel() mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 3 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), eref, 9)
def test_nr_rks_rsh(self): '''test range-separated Coulomb''' mf = dft.RKS(h2o_z0) mf.xc = 'wb97x' eref = mf.kernel() mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 3 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), eref, 9)
def test_nr_rks_rsh(self): '''test range-separated Coulomb''' mf = dft.RKS(h2o_z0) mf.xc = 'wb97x' eref = mf.kernel() mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 3 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), eref, 9)
def test_nr_uks(self): mf = dft.UKS(h2o_z1) mf.xc = 'b3lyp' eref = mf.kernel() mf.max_cycle = 1 mf.conv_check = False mf.kernel() nr = scf.newton(mf) nr.max_cycle = 3 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), eref, 9)
def simulate(self, molecule, mean_field=None): """Perform the simulation for the molecule. If the mean field is not provided it is automatically calculated. Args: molecule (pyscf.gto.Mole): The molecule to simulate. mean_field (pyscf.scf.RHF): The mean field of the molecule. """ # Calculate the mean field if the user has not already done it. if not mean_field: mean_field = scf.RHF(molecule) mean_field.verbose = 0 mean_field.scf() if (mean_field.converged == False): orb_temp = mean_field.mo_coeff occ_temp = mean_field.mo_occ nr = scf.newton(mean_field) energy = nr.kernel(orb_temp, occ_temp) mean_field = nr # Check the convergence of the mean field if not mean_field.converged: warnings.warn( "VQESolver simulating with mean field not converged.", RuntimeWarning) # Instantiate the quantum solver backend # It knows what ansatz has been picked and computed preferred values for its parameters self.hardware_backend = self.hardware_backend_type( self.ansatz_type, molecule, mean_field, self.backend_parameters) # The user can provide their own initial variational parameters, otherwise the preferred ones # computed by the underlying quantum solver will be used as initial values # An incorrect number of variational parameters passed by the user will result # in a runtime error in hardware_backend.simulate var_params = self.initial_var_params if self.initial_var_params \ else self.hardware_backend.default_initial_var_parameters() if self.verbose: print("VQE : initial variational parameters: \n", var_params, "\n") # If the user didn't provide an optimizer, then we give them a default one from scipy if not self.optimizer: self.optimizer = self._default_optimizer # Run VQE algorithm # TODO: should return the optimal parameters as well energy = self.optimizer(self.hardware_backend.simulate, var_params) return energy
def test_nr_uhf_cart(self): mol = gto.M( verbose=5, output='/dev/null', atom=[["O", (0., 0., 0.)], [1, (0., -0.757, 0.587)], [1, (0., 0.757, 0.587)]], basis='6-31g', charge=1, spin=1, ) mol.cart = True mf = scf.newton(scf.UHF(mol)) mf.kernel() self.assertAlmostEqual(mf.e_tot, -75.58051984397145, 9)
def test_nr_rhf(self): mol = gto.M(verbose=5, output='/dev/null', atom=[["O", (0., 0., 0.)], [1, (0., -0.757, 0.587)], [1, (0., 0.757, 0.587)]], basis='6-31g') mf = scf.RHF(mol) mf.max_cycle = 1 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.98394849812, 9)
def test_rks_gen_g_hop(self): mf = dft.RKS(h2o_z0) mf.grids.build() mf.xc = 'b3lyp' nao = h2o_z0.nao_nr() numpy.random.seed(1) mo = numpy.random.random((nao,nao)) mo_occ = numpy.zeros(nao) mo_occ[:5] = 2 nocc, nvir = 5, nao-5 dm1 = numpy.random.random(nvir*nocc) nr = scf.newton(mf) g, hop, hdiag = nr.gen_g_hop(mo, mo_occ, mf.get_hcore()) self.assertAlmostEqual(numpy.linalg.norm(hop(dm1)), 40669.392804071264, 7)
def test_rks_gen_g_hop(self): mf = dft.RKS(h2o_z0) mf.grids.build() mf.xc = 'b3lyp' nao = h2o_z0.nao_nr() numpy.random.seed(1) mo = numpy.random.random((nao,nao)) mo_occ = numpy.zeros(nao) mo_occ[:5] = 2 nocc, nvir = 5, nao-5 dm1 = numpy.random.random(nvir*nocc) nr = scf.newton(mf) g, hop, hdiag = nr.gen_g_hop(mo, mo_occ, mf.get_hcore()) self.assertAlmostEqual(numpy.linalg.norm(hop(dm1)), 40669.392804071264, 7)
def test_uks_gen_g_hop(self): mf = dft.UKS(h2o_z0) mf.grids.build() mf.xc = 'b3p86' nao = h2o_z0.nao_nr() numpy.random.seed(1) mo = (numpy.random.random((nao, nao)), numpy.random.random((nao, nao))) mo_occ = numpy.zeros((2, nao)) mo_occ[:, :5] = 1 nocc, nvir = 5, nao - 5 dm1 = numpy.random.random(nvir * nocc * 2) nr = scf.newton(mf) g, hop, hdiag = nr.gen_g_hop(mo, mo_occ, (mf.get_hcore(), ) * 2) self.assertAlmostEqual(numpy.linalg.norm(hop(dm1)), 33565.97987644776, 7)
def test_uks_gen_g_hop(self): mf = dft.UKS(h2o_z0) mf.grids.build() mf.xc = 'b3p86' nao = h2o_z0.nao_nr() numpy.random.seed(1) mo =(numpy.random.random((nao,nao)), numpy.random.random((nao,nao))) mo_occ = numpy.zeros((2,nao)) mo_occ[:,:5] = 1 nocc, nvir = 5, nao-5 dm1 = numpy.random.random(nvir*nocc*2) nr = scf.newton(mf) g, hop, hdiag = nr.gen_g_hop(mo, mo_occ, (mf.get_hcore(),)*2) self.assertAlmostEqual(numpy.linalg.norm(hop(dm1)), 33565.97987644776, 7)
def test_nr_rks_lda(self): mol = gto.M(verbose=5, output='/dev/null', atom=[["O", (0., 0., 0.)], [1, (0., -0.757, 0.587)], [1, (0., 0.757, 0.587)]], basis='6-31g') mf = dft.RKS(mol) eref = mf.kernel() mf.max_cycle = 1 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 3 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), eref, 9)
def RHF_calculation(mol,verbose): mf_mol = scf.RHF(mol) mf_mol.verbose = 4 mf_mol.max_cycle = 5000 mf_mol.conv_tol = 1e-6 mf_mol = scf.newton(mf_mol) mf_mol.kernel() if(verbose): print( 'Total SCF energy',mf_mol.energy_tot()) # from pyscf import cc # ccsolver = cc.CCSD(mf_mol) # ccsolver.verbose = 5 # ccsolver.ccsd() # exit() return mf_mol.mo_coeff
def test_nr_uhf(self): mol = gto.M( verbose=5, output='/dev/null', atom=[["O", (0., 0., 0.)], [1, (0., -0.757, 0.587)], [1, (0., 0.757, 0.587)]], basis='6-31g', charge=1, spin=1, ) mf = scf.UHF(mol) mf.max_cycle = 1 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.58051984397145, 9)
def test_nr_rks_lda(self): mol = gto.M( verbose = 5, output = '/dev/null', atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ], basis = '6-31g') mf = dft.RKS(mol) eref = mf.kernel() mf.max_cycle = 1 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 3 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), eref, 9)
def test_nr_rohf_symm(self): mol = gto.M( verbose=5, output='/dev/null', atom=[["O", (0., 0., 0.)], [1, (0., -0.757, 0.587)], [1, (0., 0.757, 0.587)]], basis='6-31g', charge=1, spin=1, symmetry=1, ) mf = scf.RHF(mol) mf.irrep_nelec['B2'] = (1, 0) mf.max_cycle = 1 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.578396379589819, 9)
def test_nr_uks(self): mol = gto.M( verbose=5, output='/dev/null', atom=[["O", (0., 0., 0.)], [1, (0., -0.757, 0.587)], [1, (0., 0.757, 0.587)]], basis='6-31g', charge=1, spin=1, ) mf = dft.UKS(mol) mf.xc = 'b3lyp' eref = mf.kernel() mf.max_cycle = 1 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 3 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), eref, 9)
def test_rks_gen_g_hop(self): mol = gto.M(verbose=5, output='/dev/null', atom=[["O", (0., 0., 0.)], [1, (0., -0.757, 0.587)], [1, (0., 0.757, 0.587)]], basis='6-31g') mf = dft.RKS(mol) mf.grids.build() mf.xc = 'b3lyp' nao = mol.nao_nr() numpy.random.seed(1) mo = numpy.random.random((nao, nao)) mo_occ = numpy.zeros(nao) mo_occ[:5] = 2 nocc, nvir = 5, nao - 5 dm1 = numpy.random.random(nvir * nocc) nr = scf.newton(mf) g, hop, hdiag = nr.gen_g_hop(mo, mo_occ, mf.get_hcore()) self.assertAlmostEqual(numpy.linalg.norm(hop(dm1)), 40669.392804071264, 7)
def test_uks_gen_g_hop(self): mol = gto.M(verbose=5, output='/dev/null', atom=[["O", (0., 0., 0.)], [1, (0., -0.757, 0.587)], [1, (0., 0.757, 0.587)]], basis='6-31g') mf = dft.UKS(mol) mf.grids.build() mf.xc = 'b3p86' nao = mol.nao_nr() numpy.random.seed(1) mo = (numpy.random.random((nao, nao)), numpy.random.random((nao, nao))) mo_occ = numpy.zeros((2, nao)) mo_occ[:, :5] = 1 nocc, nvir = 5, nao - 5 dm1 = numpy.random.random(nvir * nocc * 2) nr = scf.newton(mf) g, hop, hdiag = nr.gen_g_hop(mo, mo_occ, (mf.get_hcore(), ) * 2) self.assertAlmostEqual(numpy.linalg.norm(hop(dm1)), 33565.97987644776, 7)
def test_nr_rohf_symm(self): mol = gto.M( verbose = 5, output = '/dev/null', atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ], basis = '6-31g', charge = 1, spin = 1, symmetry = 1, ) mf = scf.RHF(mol) mf.irrep_nelec['B2'] = (1,0) mf.max_cycle = 1 mf.kernel() nr = scf.newton(mf) nr.max_cycle = 2 nr.conv_tol_grad = 1e-5 self.assertAlmostEqual(nr.kernel(), -75.578396379589819, 9)
def test_rks_gen_g_hop(self): mol = gto.M( verbose = 5, output = '/dev/null', atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ], basis = '6-31g') mf = dft.RKS(mol) mf.grids.build() mf.xc = 'b3lyp' nao = mol.nao_nr() numpy.random.seed(1) mo = numpy.random.random((nao,nao)) mo_occ = numpy.zeros(nao) mo_occ[:5] = 2 nocc, nvir = 5, nao-5 dm1 = numpy.random.random(nvir*nocc) nr = scf.newton(mf) g, hop, hdiag = nr.gen_g_hop(mo, mo_occ, mf.get_hcore()) self.assertAlmostEqual(numpy.linalg.norm(hop(dm1)), 40669.392804071264, 7)
def test_uks_gen_g_hop(self): mol = gto.M( verbose = 5, output = '/dev/null', atom = [ ["O" , (0. , 0. , 0.)], [1 , (0. , -0.757 , 0.587)], [1 , (0. , 0.757 , 0.587)] ], basis = '6-31g') mf = dft.UKS(mol) mf.grids.build() mf.xc = 'b3lyp' nao = mol.nao_nr() numpy.random.seed(1) mo =(numpy.random.random((nao,nao)), numpy.random.random((nao,nao))) mo_occ = numpy.zeros((2,nao)) mo_occ[:,:5] = 1 nocc, nvir = 5, nao-5 dm1 = numpy.random.random(nvir*nocc*2) nr = scf.newton(mf) g, hop, hdiag = nr.gen_g_hop(mo, mo_occ, (mf.get_hcore(),)*2) self.assertAlmostEqual(numpy.linalg.norm(hop(dm1)), 35542.277987080488, 7)
# # 2. spin-free X2C correction for density-fitting HF. Since X2C correction is # commutable with density fitting operation, it is fully equivalent to case 1. # mf = scf.sfx2c(scf.density_fit(scf.RHF(mol))) energy = mf.kernel() print("E = %.12f, ref = -76.075115837941" % energy) # # 3. Newton method for non-relativistic HF # mo_init = mf.eig(mf.get_hcore(), mf.get_ovlp())[1] mocc_init = numpy.zeros(mo_init.shape[1]) mocc_init[: mol.nelectron // 2] = 2 mf = scf.newton(scf.RHF(mol)) energy = mf.kernel(mo_init, mocc_init) print("E = %.12f, ref = -76.026765673091" % energy) # # 4. Newton method for non-relativistic HF with density fitting for orbital # hessian of newton solver. Note the answer is equal to case 3, but the # solver "mf" is different. # mf = scf.density_fit(scf.newton(scf.RHF(mol))) energy = mf.kernel(mo_init, mocc_init) print("E = %.12f, ref = -76.026765673091" % energy) # # 5. Newton method to solve the density-fitting approximated HF object. There # is no approximation for newton method (orbital hessian). Note the density
def test_nr_uhf_cart(self): mol = h2o_z1.copy() mol.cart = True mf = scf.newton(scf.UHF(mol)) mf.kernel() self.assertAlmostEqual(mf.e_tot, -75.58051984397145, 9)
get_fock = uhf_nmr.get_fock def get_ovlp(self, mol=None, gauge_orig=None): if mol is None: mol = self.mol if gauge_orig is None: gauge_orig = self.gauge_orig return rhf_nmr.get_ovlp(mol, gauge_orig) def align(self, gtensor): return align(gtensor) if __name__ == '__main__': from pyscf import gto, scf mol = gto.M(atom='C 0 0 0; O 0 0 1.25', basis='ccpvdz', spin=1, charge=1, verbose=3) mf = scf.newton(scf.UHF(mol)).run() gobj = GTensor(mf) gobj.para_soc2e = 'SSO+SOO' gobj.dia_soc2e = None gobj.so_eff_charge = False gobj.gauge_orig = (0,0,0) print(gobj.align(gobj.kernel())[0]) mol = gto.M(atom=''' H 0 0 1 ''', basis='ccpvdz', spin=1, charge=0, verbose=3) mf = scf.UHF(mol).run() gobj = GTensor(mf) print(gobj.align(gobj.kernel())[0])
function. (New in PySCF-1.1) Second order SCF method need orthonormal orbitals and the corresponding occupancy as the initial guess. ''' mol = gto.Mole() mol.build( verbose = 0, atom = '''8 0 0. 0 1 0 -0.757 0.587 1 0 0.757 0.587''', basis = 'ccpvdz', ) mf = scf.RHF(mol) mf.conv_tol = 1e-1 mf.kernel() mo_init = mf.mo_coeff mocc_init = mf.mo_occ mf = scf.newton(scf.RHF(mol)) energy = mf.kernel(mo_init, mocc_init) print('E = %.12f, ref = -76.026765672992' % energy) mf = scf.newton(scf.UKS(mol)) energy = mf.kernel((mo_init,mo_init), (mocc_init*.5,mocc_init*.5)) print('E = %.12f, ref = -75.854689662296' % energy)
def test_init(self): from pyscf import dft from pyscf import x2c mol_r = mol mol_u = gto.M(atom='Li', spin=1, verbose=0) mol_r1 = gto.M(atom='H', spin=1, verbose=0) sym_mol_r = molsym sym_mol_u = gto.M(atom='Li', spin=1, symmetry=1, verbose=0) sym_mol_r1 = gto.M(atom='H', spin=1, symmetry=1, verbose=0) self.assertTrue(isinstance(scf.RKS(mol_r), dft.rks.RKS)) self.assertTrue(isinstance(scf.RKS(mol_u), dft.roks.ROKS)) self.assertTrue(isinstance(scf.UKS(mol_r), dft.uks.UKS)) self.assertTrue(isinstance(scf.ROKS(mol_r), dft.roks.ROKS)) self.assertTrue(isinstance(scf.GKS(mol_r), dft.gks.GKS)) self.assertTrue(isinstance(scf.KS(mol_r), dft.rks.RKS)) self.assertTrue(isinstance(scf.KS(mol_u), dft.uks.UKS)) self.assertTrue(isinstance(scf.RHF(mol_r), scf.hf.RHF)) self.assertTrue(isinstance(scf.RHF(mol_u), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.RHF(mol_r1), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.UHF(mol_r), scf.uhf.UHF)) self.assertTrue(isinstance(scf.UHF(mol_u), scf.uhf.UHF)) self.assertTrue(isinstance(scf.UHF(mol_r1), scf.uhf.UHF)) self.assertTrue(isinstance(scf.ROHF(mol_r), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.ROHF(mol_u), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.ROHF(mol_r1), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.HF(mol_r), scf.hf.RHF)) self.assertTrue(isinstance(scf.HF(mol_u), scf.uhf.UHF)) self.assertTrue(isinstance(scf.HF(mol_r1), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.GHF(mol_r), scf.ghf.GHF)) self.assertTrue(isinstance(scf.GHF(mol_u), scf.ghf.GHF)) self.assertTrue(isinstance(scf.GHF(mol_r1), scf.ghf.GHF)) self.assertTrue(not isinstance(scf.DHF(mol_r), scf.dhf.RHF)) self.assertTrue(isinstance(scf.DHF(mol_u), scf.dhf.UHF)) self.assertTrue(isinstance(scf.DHF(mol_r1), scf.dhf.HF1e)) self.assertTrue(isinstance(scf.RHF(sym_mol_r), scf.hf_symm.RHF)) self.assertTrue(isinstance(scf.RHF(sym_mol_u), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.RHF(sym_mol_r1), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.UHF(sym_mol_r), scf.uhf_symm.UHF)) self.assertTrue(isinstance(scf.UHF(sym_mol_u), scf.uhf_symm.UHF)) self.assertTrue(isinstance(scf.UHF(sym_mol_r1), scf.uhf_symm.UHF)) self.assertTrue(isinstance(scf.ROHF(sym_mol_r), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.ROHF(sym_mol_u), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.ROHF(sym_mol_r1), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.HF(sym_mol_r), scf.hf_symm.RHF)) self.assertTrue(isinstance(scf.HF(sym_mol_u), scf.uhf_symm.UHF)) self.assertTrue(isinstance(scf.HF(sym_mol_r1), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.GHF(sym_mol_r), scf.ghf_symm.GHF)) self.assertTrue(isinstance(scf.GHF(sym_mol_u), scf.ghf_symm.GHF)) self.assertTrue(isinstance(scf.GHF(sym_mol_r1), scf.ghf_symm.GHF)) self.assertTrue(isinstance(scf.X2C(mol_r), x2c.x2c.UHF)) self.assertTrue(isinstance(scf.sfx2c1e(scf.HF(mol_r)), scf.rhf.RHF)) self.assertTrue(isinstance(scf.sfx2c1e(scf.HF(mol_u)), scf.uhf.UHF)) self.assertTrue(isinstance(scf.sfx2c1e(scf.HF(mol_r1)), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.sfx2c1e(scf.HF(sym_mol_r)), scf.rhf_symm.RHF)) self.assertTrue(isinstance(scf.sfx2c1e(scf.HF(sym_mol_u)), scf.uhf_symm.UHF)) self.assertTrue(isinstance(scf.sfx2c1e(scf.HF(sym_mol_r1)), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.density_fit(scf.HF(mol_r)), scf.rhf.RHF)) self.assertTrue(isinstance(scf.density_fit(scf.HF(mol_u)), scf.uhf.UHF)) self.assertTrue(isinstance(scf.density_fit(scf.HF(mol_r1)), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.density_fit(scf.HF(sym_mol_r)), scf.rhf_symm.RHF)) self.assertTrue(isinstance(scf.density_fit(scf.HF(sym_mol_u)), scf.uhf_symm.UHF)) self.assertTrue(isinstance(scf.density_fit(scf.HF(sym_mol_r1)), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.newton(scf.HF(mol_r)), scf.rhf.RHF)) self.assertTrue(isinstance(scf.newton(scf.HF(mol_u)), scf.uhf.UHF)) self.assertTrue(isinstance(scf.newton(scf.HF(mol_r1)), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.newton(scf.HF(sym_mol_r)), scf.rhf_symm.RHF)) self.assertTrue(isinstance(scf.newton(scf.HF(sym_mol_u)), scf.uhf_symm.UHF)) self.assertTrue(isinstance(scf.newton(scf.HF(sym_mol_r1)), scf.hf_symm.ROHF))
mol.atom = ''' N 0.0000 0.0000 0.5488 N 0.0000 0.0000 -0.5488 ''' mol.verbose = 4 mol.spin = 0 mol.charge = 0 mol.symmetry = 1 mol.build() #int3c = df.incore.cholesky_eri(mol, auxbasis='aug-cc-pvdz-jkfit') mf = scf.density_fit(scf.RHF(mol)) #mf.with_df._cderi = int3c mf.auxbasis = 'aug-cc-pvtz-jkfit' mf = scf.newton(mf) mf = scf.addons.remove_linear_dep_(mf) mf.chkfile = name+'.chk' #mf.__dict__.update(lib.chkfile.load(name+'.chk', 'scf')) mf.level_shift = 0.5 mf.conv_tol = 1e-8 mf.kernel() dm = mf.make_rdm1() mf.level_shift = 0.0 ehf = mf.kernel(dm) stable_cyc = 3 for i in range(stable_cyc): new_mo_coeff = mf.stability(internal=True, external=False)[0] if numpy.linalg.norm(numpy.array(new_mo_coeff) - numpy.array(mf.mo_coeff)) < 10**-8: lib.logger.info(mf,"* The molecule is stable")
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] mol_ = gto.Mole() mol_.build (verbose=0) mol_.nelectron = nel mol_.incore_anyway = True cfx = cf_gs Sf = mol.intor_symmetric('cint1e_ovlp_sph') Hc = mol.intor_symmetric('cint1e_kin_sph') \ + mol.intor_symmetric('cint1e_nuc_sph') occ = np.zeros((cfx.shape[1],)) occ[:nel/2] = 2. # 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))) # HF calculation mol_.energy_nuc = lambda *args: mol.energy_nuc() + e_core mf = scf.RHF(mol_) #mf.verbose = 4 mf.mo_coeff = cf mf.mo_occ = occ mf.get_ovlp = lambda *args: Sp mf.get_hcore = lambda *args: Hp + jkp - 0.5*chempot*(Np + Np.T) mf._eri = ao2mo.restore (8, intsp, cfx.shape[1]) nt = scf.newton(mf) #nt.verbose = 4 nt.max_cycle_inner = 1 nt.max_stepsize = 0.25 nt.ah_max_cycle = 32 nt.ah_start_tol = 1.0e-12 nt.ah_grad_trust_region = 1.0e8 nt.conv_tol_grad = 1.0e-6 nt.kernel() cf = nt.mo_coeff if not nt.converged: raise RuntimeError ('hf failed to converge') mf.mo_coeff = cf rdm = mf.make_rdm1() jk = mf.get_veff(dm=rdm) ImpEnergy = +0.25*np.trace(np.dot(np.dot(2*Hp+jkp, rdm), Xp)) \ +0.25*np.trace(np.dot(np.dot(2*Hp+jkp, Xp), rdm)) \ +0.25*np.trace(np.dot(np.dot(jk, rdm), Xp)) \ +0.25*np.trace(np.dot(np.dot(jk, Xp), rdm)) Nel = np.trace(np.dot(np.dot(rdm, Sp), Xp)) return Nel, ImpEnergy
def test_nr_uhf_cart(self): mol = h2o_z1.copy() mol.cart = True mf = scf.newton(scf.UHF(mol)) mf.kernel() self.assertAlmostEqual(mf.e_tot, -75.58051984397145, 9)
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] mol_ = gto.Mole() mol_.build(verbose=0) mol_.nelectron = nel mol_.incore_anyway = True cfx = cf_gs Sf = mol.intor_symmetric('cint1e_ovlp_sph') Hc = mol.intor_symmetric('cint1e_kin_sph') \ + mol.intor_symmetric('cint1e_nuc_sph') occ = np.zeros((cfx.shape[1], )) occ[:nel // 2] = 2. # 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))) # HF calculation mol_.energy_nuc = lambda *args: mol.energy_nuc() + e_core mf = scf.RHF(mol_) #mf.verbose = 4 mf.mo_coeff = cf mf.mo_occ = occ mf.get_ovlp = lambda *args: Sp mf.get_hcore = lambda *args: Hp + jkp - 0.5 * chempot * (Np + Np.T) mf._eri = ao2mo.restore(8, intsp, cfx.shape[1]) nt = scf.newton(mf) #nt.verbose = 4 nt.max_cycle_inner = 1 nt.max_stepsize = 0.25 nt.ah_max_cycle = 32 nt.ah_start_tol = 1.0e-12 nt.ah_grad_trust_region = 1.0e8 nt.conv_tol_grad = 1.0e-6 nt.kernel() cf = nt.mo_coeff if not nt.converged: raise RuntimeError('hf failed to converge') mf.mo_coeff = nt.mo_coeff mf.mo_energy = nt.mo_energy mf.mo_occ = nt.mo_occ # FCI solution fcisolver = fci.direct_spin0.FCISolver() _h1 = np.dot(cf.T, np.dot(mf.get_hcore(), cf)) _h2 = ao2mo.incore.full(intsp, cf) fcisolver.verbose = 2 Energy, fcivec = \ fcisolver.kernel (_h1, _h2, cf.shape[1], (nel/2, nel/2)) Energy += mol.energy_nuc() + e_core rdm1, rdm2 = \ fcisolver.make_rdm12 (fcivec, cf.shape[1], (nel/2, nel/2)) # 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
def solve (mol, nel, cf_core, cf_gs, ImpOrbs, chempot=0., n_orth=0, FrozenPot=None, mf_tot=None): # 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] mol_ = gto.Mole() mol_.build (verbose=0) mol_.nelectron = nel mol_.incore_anyway = True cfx = cf_gs print("cfx shape", cfx.shape) Sf = mol.intor_symmetric('cint1e_ovlp_sph') Hc = mol.intor_symmetric('cint1e_kin_sph') \ + mol.intor_symmetric('cint1e_nuc_sph') \ + FrozenPot occ = np.zeros((cfx.shape[1],)) occ[:nel//2] = 2. # 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)) # density fitting ============================================================ # mf = scf.RHF(mol).density_fit() # this should be moved out of to the parent directory, to avoid repetition # mf.with_df._cderi_to_save = 'saved_cderi.h5' # rank-3 decomposition # mf.kernel() ### moved these three lines to orbital_selection_fc auxmol = df.incore.format_aux_basis(mol, auxbasis='weigend') j3c = df.incore.aux_e2(mol, auxmol, intor='cint3c2e_sph', aosym='s1') nao = mol.nao_nr() naoaux = auxmol.nao_nr() j3c = j3c.reshape(nao,nao,naoaux) # (ij|L) print("j3c shape", j3c.shape) j2c = df.incore.fill_2c2e(mol, auxmol) #(L|M) overlap matrix between auxiliary basis functions #the eri is (ij|kl) = \sum_LM (ij|L) (L|M) (M|kl) omega = sla.inv(j2c) eps,U = sla.eigh(omega) #after this transformation the eri is (ij|kl) = \sum_L (ij|L) (L|kl) j3c = np.dot(np.dot(j3c,U),np.diag(np.sqrt(eps))) #this part is slow, as we again store the whole eri_df # conv = np.einsum('prl,pi,rj->ijl', j3c, cfx, cfx) conv = np.einsum('prl,pi->irl',j3c,cfx) conv = np.einsum('irl,rj->ijl',conv,cfx) df_eri = np.einsum('ijm,klm->ijkl',conv,conv) intsp_df = ao2mo.restore(4, df_eri, cfx.shape[1]) print("DF instp", intsp_df.shape) # ============================================================================= # intsp = ao2mo.outcore.full_iofree (mol, cfx) #TODO: this we need to calculate on the fly using generator f'n # print("intsp shape", intsp.shape) # 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))) # HF calculation mol_.energy_nuc = lambda *args: mol.energy_nuc() + e_core mf1 = scf.RHF(mol_) #.density_fit() #mf.verbose = 4 mf1.mo_coeff = cf mf1.mo_occ = occ mf1.get_ovlp = lambda *args: Sp mf1.get_hcore = lambda *args: Hp + jkp - 0.5*chempot*(Np + Np.T) mf1._eri = ao2mo.restore (8, intsp_df, cfx.shape[1]) #trying something nt = scf.newton(mf1) #nt.verbose = 4 nt.max_cycle_inner = 1 nt.max_stepsize = 0.25 nt.ah_max_cycle = 32 nt.ah_start_tol = 1.0e-12 nt.ah_grad_trust_region = 1.0e8 nt.conv_tol_grad = 1.0e-6 nt.kernel() cf = nt.mo_coeff if not nt.converged: raise RuntimeError ('hf failed to converge') mo_coeff = nt.mo_coeff mo_energy = nt.mo_energy mo_occ = nt.mo_occ print("mo_coeff", mo_coeff) # dfMP2 solution nocc = nel//2 # mp2solver = dfmp2_testing.MP2(mf_tot) #(work) #we just pass the mf for the full molecule to dfmp2 mp2solver = dfmp2.DFMP2(mf_tot) #(work) #we just pass the mf for the full molecule to dfmp2 # mp2solver = dfmp2.MP2(mf) #(home) mp2solver.verbose = 5 mp2solver.kernel(mo_energy=mo_energy, mo_coeff=mo_coeff, nocc=nocc) mp2solver.mo_occ=mo_occ.copy() # this is DIRTY def get_t2(mp): '''basically identical to the DFMP2 kernel, returns t2''' from pyscf.mp import mp2 mo_coeff = mp2._mo_without_core(mp, mp.mo_coeff) # print("mo_coeff rdms", mo_coeff) mo_energy = mp2._mo_energy_without_core(mp, mp.mo_energy) nocc = mp.nocc nvir = mp.nmo - nocc eia = mo_energy[:nocc,None] - mo_energy[None,nocc:] emp2 = 0 t2 = [] for istep, qov in enumerate(mp.loop_ao2mo(mo_coeff, nocc)): for i in range(nocc): buf = np.dot(qov[:,i*nvir:(i+1)*nvir].T,qov).reshape(nvir,nocc,nvir) gi = np.array(buf,copy=False) gi = gi.reshape(nvir,nocc,nvir).transpose(1,0,2) t2i = gi.conj()/lib.direct_sum('jb+a->jba',eia,eia[i]) t2.append(t2i) emp2 += np.einsum('jab,jab',t2i,gi) * 2 emp2 -= np.einsum('jab,jba',t2i,gi) return emp2,t2 def make_rdm1(mp2solver): '''rdm1 in the MO basis''' from pyscf.cc import ccsd_rdm doo, dvv = _gamma1_intermediates(mp2solver) nocc = doo.shape[0] nvir = dvv.shape[0] print('nocc', nocc) print('nvir', nvir) dov = np.zeros((nocc,nvir), dtype=doo.dtype) dvo = dov.T return ccsd_rdm._make_rdm1(mp,(doo,dov,dvo,dvv),with_frozen=False) def _gamma1_intermediates(mp,t2=None): nmo = mp.nmo nocc = mp.nocc nvir = nmo - nocc from pyscf.mp import mp2 mo_coeff = mp2._mo_without_core(mp, mp.mo_coeff) print("mo coeff rdms", mo_coeff) print('nmo, nocc, nvir, mo_coeff shape') print(nmo, nocc, nvir, mp.mo_coeff.shape) mo_energy = mp2._mo_energy_without_core(mp, mp.mo_energy) eia = mo_energy[:nocc,None] - mo_energy[None,nocc:] if(t2 is None): for istep, qov in enumerate(mp.loop_ao2mo(mo_coeff, nocc)): if(istep==0): dtype = qov.dtype dm1occ = np.zeros((nocc,nocc), dtype=dtype) dm1vir = np.zeros((nvir,nvir), dtype=dtype) for i in range(nocc): buf = np.dot(qov[:,i*nvir:(i+1)*nvir].T, qov).reshape(nvir,nocc,nvir) gi = np.array(buf, copy=False) gi = gi.reshape(nvir,nocc,nvir).transpose(1,0,2) t2i = gi/lib.direct_sum('jb+a->jba', eia, eia[i]) l2i = t2i.conj() dm1vir += np.einsum('jca,jcb->ba', l2i, t2i) * 2 \ - np.einsum('jca,jbc->ba', l2i, t2i) dm1occ += np.einsum('iab,jab->ij', l2i, t2i) * 2 \ - np.einsum('iab,jba->ij', l2i, t2i) else: dtype = t2[0].dtype dm1occ = np.zeros((nocc,nocc), dtype=dtype) dm1vir = np.zeros((nvir,nvir), dtype=dtype) for i in range(nocc): t2i = t2[i] l2i = t2i.conj() dm1vir += np.einsum('jca,jcb->ba', l2i, t2i) * 2 \ - np.einsum('jca,jbc->ba', l2i, t2i) dm1occ += np.einsum('iab,jab->ij', l2i, t2i) * 2 \ - np.einsum('iab,jba->ij', l2i, t2i) return -dm1occ, dm1vir def make_rdm2(mp2solver): nmo = nmo0 = mp2solver.nmo nocc = nocc0 = mp2solver.nocc nvir = nmo - nocc from pyscf.mp import mp2 mo_coeff = mp2._mo_without_core(mp2solver, mp2solver.mo_coeff) mo_energy = mp2._mo_energy_without_core(mp2solver, mp2solver.mo_energy) eia = mo_energy[:nocc,None] - mo_energy[None,nocc:] moidx = oidx = vidx = None dm1 = make_rdm1(mp2solver) dm1[np.diag_indices(nocc0)] -= 2 dm2 = np.zeros((nmo0,nmo0,nmo0,nmo0), dtype=dm1.dtype) if(t2 is None): for istep, qov in enumerate(mp2solver.loop_ao2mo(mo_coeff, nocc)): for i in range(nocc): buf = np.dot(qov[:,i*nvir:(i+1)*nvir].T,qov).reshape(nvir,nocc,nvir) gi = np.array(buf,copy=False) gi = gi.reshape(nvir,nocc,nvir).transpose(1,0,2) t2i = gi.conj()/lib.direct_sum('jb+a->jba',eia,eia[i]) dovov = t2i.transpose(1,0,2)*2 - t2i.transpose(2,0,1) dovov *= 2 if moidx is None: dm2[i,nocc:,:nocc,nocc:] = dovov dm2[nocc:,i,nocc:,:nocc] = dovov.conj().transpose(0,2,1) else: dm2[oidx[i],vidx[:,None,None],oidx[:,None],vidx] = dovov dm2[vidx[:,None,None],oidx[i],vidx[:,None],oidx] = dovov.conj().transpose(0,2,1) else: for i in range(nocc): t2i = t2[i] dovov = t2i.transpose(1,0,2)*2 - t2i.transpose(2,0,1) dovov *= 2 if moidx is None: dm2[i,nocc:,:nocc,nocc:] = dovov dm2[nocc:,i,nocc:,:nocc] = dovov.conj().transpose(0,2,1) else: dm2[oidx[i],vidx[:,None,None],oidx[:,None],vidx] = dovov dm2[vidx[:,None,None],oidx[i],vidx[:,None],oidx] = dovov.conj().transpose(0,2,1) for i in range(nocc0): dm2[i,i,:,:] += dm1.T * 2 dm2[:,:,i,i] += dm1.T * 2 dm2[:,i,i,:] -= dm1.T dm2[i,:,:,i] -= dm1 for i in range(nocc0): for j in range(nocc0): dm2[i,i,j,j] += 4 dm2[i,j,j,i] -= 2 return dm2 t2 = None rdm1 = make_rdm1(mp2solver) rdm2 = make_rdm2(mp2solver) # # ------------------------------------- # TEST: compare rdm dmet with dfmp2 rdms # atoms_test=\ # [['C',( 0.0000, 0.0000, 0.7680)],\ # ['C',( 0.0000, 0.0000,-0.7680)],\ # ['H',(-1.0192, 0.0000, 1.1573)],\ # ['H',( 0.5096, 0.8826, 1.1573)],\ # ['H',( 0.5096,-0.8826, 1.1573)],\ # ['H',( 1.0192, 0.0000,-1.1573)],\ # ['H',(-0.5096,-0.8826,-1.1573)],\ # ['H',(-0.5096, 0.8826,-1.1573)]] atoms_test = [ ['O' , (0. , 0. , 0.)],\ ['H' , (0. , -0.757 , 0.587)],\ ['H' , (0. , 0.757 , 0.587)]] mol_test = gto.M(atom=atoms_test,basis='cc-pvdz') m_test = scf.RHF(mol_test).density_fit() m_test.kernel() mm_test = dfmp2.DFMP2(m_test) mm_test.kernel() from pyscf.mp import mp2 rdm1_test = mp2.make_rdm1(mm_test) rdm2_test = mp2.make_rdm2(mm_test) # Plot sorted rdm1 values x1 = rdm1 y1 = x1.flatten() y1 = np.sort(y1) import matplotlib.pyplot as plt plt.plot(y1, 'r', label='rdm1 from dmet') plt.ylabel('rdm1') x2 = rdm1_test y2 = x2.flatten() print("rdm1", y2) print(type(y2)) y2 = np.sort(y2) plt.plot(y2, 'b', label='rdm1 for dfmp2') plt.ylabel('rdm1 sorted values') # Place a legend above this subplot, expanding itself to # fully use the given bounding box. plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show() plt.close() print("deviations between sorted 1rdm in MO basis ") print(np.abs(y1-y2).max()) # Plot sorted rdm2 values x1 = rdm2 y1 = x1.flatten() y1 = np.sort(y1) import matplotlib.pyplot as plt plt.plot(y1, 'r', label='rdm2 from dmet') plt.ylabel('rdm2') x2 = rdm2_test y2 = x2.flatten() print("rdm1", y2) print(type(y2)) y2 = np.sort(y2) plt.plot(y2, 'b', label='rdm2 for dfmp2') plt.ylabel('rdm1 sorted values') # Place a legend above this subplot, expanding itself to # fully use the given bounding box. plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.) plt.show() plt.close() print("deviations between sorted 1rdm in MO basis ") print(np.abs(y1-y2).max()) print("deviations between 1rdm,2rdm in MO basis ") print(np.abs(rdm1-rdm1_test).max()) print(np.abs(rdm2-rdm2_test).max()) # # ---------------------------------- # transform rdm's to original basis tei = ao2mo.restore(1, intsp_df, cfx.shape[1]) print("tei shape", tei.shape) 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
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() uhf_stability(mf, True, True, verbose=4) mol = gto.M(atom=''' O1 O2 1 1.2227 O3 1 1.2227 2 114.0451
mol.build() # # X2C correction for relativistic effects # # first pass, to generate initial guess # mf = scf.sfx2c(scf.UHF(mol)) mf.chkfile = 'hs.chk' mf.level_shift = 0.1 mf.conv_tol = 1e-2 mf.kernel() # # second pass to converge SCF calculation # mf = scf.newton(mf) mf.conv_tol = 1e-12 mf.kernel() ################################################## # # Analyze SCF results and make MCSCF initial guess # ################################################## # This parameter to control the call to matplotlib ifplot = False
H 5.612530 2.721618 4.428971 H 4.651591 2.282146 3.180231 H 4.947415 4.665452 0.537824 H 3.725531 3.767789 1.151899 H 3.515369 5.369877 0.896878 H 9.224480 4.780740 3.228456 H 10.002053 5.784964 4.259380 H 9.010897 4.621544 4.842435 H 7.210886 6.878915 6.599377 H 8.578203 7.641391 6.125073 H 7.135300 8.403680 6.011782 H 8.308553 8.287098 2.094287 H 7.797036 9.254716 3.309999 H 9.239940 8.492427 3.423290 ''', basis = 'ccpvdz', charge = 3, spin = 3, verbose = 5, output = 'cu3.out') mf = scf.density_fit(scf.RHF(mol)) mf.diis_start_cycle = 0 mf.conv_tol = .01 mf.kernel() mo0 = mf.mo_coeff mo0occ = mf.mo_occ mf = scf.density_fit(scf.newton(scf.RHF(mol))) mf.kernel(mo0, mo0occ)
mol = gto.Mole() mol.build( verbose=0, atom='''8 0 0. 0 1 0 -0.757 0.587 1 0 0.757 0.587''', basis='ccpvdz', ) mf = scf.RHF(mol) mf.conv_tol = 1e-1 mf.kernel() mo_init = mf.mo_coeff mocc_init = mf.mo_occ mf = scf.newton(scf.RHF(mol)) energy = mf.kernel(mo_init, mocc_init) print('E = %.12f, ref = -76.026765672992' % energy) mf = scf.UKS(mol).newton() # Using stream style # The newton algorithm will automatically generate initial orbitals if initial # guess is not given. energy = mf.kernel() print('E = %.12f, ref = -75.854702461713' % energy) # Note You should first set mf.xc then apply newton method because this will # correctly set up the underlying orbital gradients. If you first create # mf = mf.newton() then change mf.xc, the orbital Hessian will be computed # with the updated xc functional while the orbital gradients are computed with # the old xc functional. # In some scenario, you can use this character to approximate the
# Run stability analysis for the SCF wave function mf.stability() # # This instability is associated to a symmetry broken answer. When point # group symmetry is used, the same wave function is stable. # mol = gto.M(atom='C 0 0 0; O 0 0 1.2', basis='631g*', symmetry=1) mf = scf.RHF(mol).run() mf.stability() # # If the SCF wavefunction is unstable, the stability analysis program will # transform the SCF wavefunction and generate a set of initial guess (orbitals). # The initial guess can be used to make density matrix and fed into a new SCF # iteration (see 15-initial_guess.py). # mol = gto.M(atom='O 0 0 0; O 0 0 1.2222', basis='631g*') mf = scf.UHF(mol).run() mo1 = mf.stability()[0] dm1 = mf.make_rdm1(mo1, mf.mo_occ) mf = mf.run(dm1) mf.stability() # # Also the initial guess orbitals from stability analysis can be used as with # second order SCF solver # mf = scf.newton(mf).run(mo1, mf.mo_occ) mf.stability()
def test_init(self): from pyscf import dft from pyscf import x2c mol_r = mol mol_u = gto.M(atom='Li', spin=1, verbose=0) mol_r1 = gto.M(atom='H', spin=1, verbose=0) sym_mol_r = molsym sym_mol_u = gto.M(atom='Li', spin=1, symmetry=1, verbose=0) sym_mol_r1 = gto.M(atom='H', spin=1, symmetry=1, verbose=0) self.assertTrue(isinstance(scf.RKS(mol_r), dft.rks.RKS)) self.assertTrue(isinstance(scf.RKS(mol_u), dft.roks.ROKS)) self.assertTrue(isinstance(scf.UKS(mol_r), dft.uks.UKS)) self.assertTrue(isinstance(scf.ROKS(mol_r), dft.roks.ROKS)) self.assertTrue(isinstance(scf.GKS(mol_r), dft.gks.GKS)) self.assertTrue(isinstance(scf.KS(mol_r), dft.rks.RKS)) self.assertTrue(isinstance(scf.KS(mol_u), dft.uks.UKS)) self.assertTrue(isinstance(scf.RHF(mol_r), scf.hf.RHF)) self.assertTrue(isinstance(scf.RHF(mol_u), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.RHF(mol_r1), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.UHF(mol_r), scf.uhf.UHF)) self.assertTrue(isinstance(scf.UHF(mol_u), scf.uhf.UHF)) self.assertTrue(isinstance(scf.UHF(mol_r1), scf.uhf.HF1e)) self.assertTrue(isinstance(scf.ROHF(mol_r), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.ROHF(mol_u), scf.rohf.ROHF)) self.assertTrue(isinstance(scf.ROHF(mol_r1), scf.rohf.HF1e)) self.assertTrue(isinstance(scf.HF(mol_r), scf.hf.RHF)) self.assertTrue(isinstance(scf.HF(mol_u), scf.uhf.UHF)) self.assertTrue(isinstance(scf.HF(mol_r1), scf.rohf.HF1e)) self.assertTrue(isinstance(scf.GHF(mol_r), scf.ghf.GHF)) self.assertTrue(isinstance(scf.GHF(mol_u), scf.ghf.GHF)) self.assertTrue(isinstance(scf.GHF(mol_r1), scf.ghf.HF1e)) #TODO: self.assertTrue(isinstance(scf.DHF(mol_r), scf.dhf.RHF)) self.assertTrue(isinstance(scf.DHF(mol_u), scf.dhf.UHF)) self.assertTrue(isinstance(scf.DHF(mol_r1), scf.dhf.HF1e)) self.assertTrue(isinstance(scf.RHF(sym_mol_r), scf.hf_symm.RHF)) self.assertTrue(isinstance(scf.RHF(sym_mol_u), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.RHF(sym_mol_r1), scf.hf_symm.HF1e)) self.assertTrue(isinstance(scf.UHF(sym_mol_r), scf.uhf_symm.UHF)) self.assertTrue(isinstance(scf.UHF(sym_mol_u), scf.uhf_symm.UHF)) self.assertTrue(isinstance(scf.UHF(sym_mol_r1), scf.uhf_symm.HF1e)) self.assertTrue(isinstance(scf.ROHF(sym_mol_r), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.ROHF(sym_mol_u), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.ROHF(sym_mol_r1), scf.hf_symm.HF1e)) self.assertTrue(isinstance(scf.HF(sym_mol_r), scf.hf_symm.RHF)) self.assertTrue(isinstance(scf.HF(sym_mol_u), scf.uhf_symm.UHF)) self.assertTrue(isinstance(scf.HF(sym_mol_r1), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.GHF(sym_mol_r), scf.ghf_symm.GHF)) self.assertTrue(isinstance(scf.GHF(sym_mol_u), scf.ghf_symm.GHF)) self.assertTrue(isinstance(scf.GHF(sym_mol_r1), scf.ghf_symm.HF1e)) self.assertTrue(isinstance(scf.X2C(mol_r), x2c.x2c.UHF)) self.assertTrue(isinstance(scf.sfx2c1e(scf.HF(mol_r)), scf.rhf.RHF)) self.assertTrue(isinstance(scf.sfx2c1e(scf.HF(mol_u)), scf.uhf.UHF)) self.assertTrue(isinstance(scf.sfx2c1e(scf.HF(mol_r1)), scf.rohf.ROHF)) self.assertTrue( isinstance(scf.sfx2c1e(scf.HF(sym_mol_r)), scf.rhf_symm.RHF)) self.assertTrue( isinstance(scf.sfx2c1e(scf.HF(sym_mol_u)), scf.uhf_symm.UHF)) self.assertTrue( isinstance(scf.sfx2c1e(scf.HF(sym_mol_r1)), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.density_fit(scf.HF(mol_r)), scf.rhf.RHF)) self.assertTrue(isinstance(scf.density_fit(scf.HF(mol_u)), scf.uhf.UHF)) self.assertTrue( isinstance(scf.density_fit(scf.HF(mol_r1)), scf.rohf.ROHF)) self.assertTrue( isinstance(scf.density_fit(scf.HF(sym_mol_r)), scf.rhf_symm.RHF)) self.assertTrue( isinstance(scf.density_fit(scf.HF(sym_mol_u)), scf.uhf_symm.UHF)) self.assertTrue( isinstance(scf.density_fit(scf.HF(sym_mol_r1)), scf.hf_symm.ROHF)) self.assertTrue(isinstance(scf.newton(scf.HF(mol_r)), scf.rhf.RHF)) self.assertTrue(isinstance(scf.newton(scf.HF(mol_u)), scf.uhf.UHF)) self.assertTrue(isinstance(scf.newton(scf.HF(mol_r1)), scf.rohf.ROHF)) self.assertTrue( isinstance(scf.newton(scf.HF(sym_mol_r)), scf.rhf_symm.RHF)) self.assertTrue( isinstance(scf.newton(scf.HF(sym_mol_u)), scf.uhf_symm.UHF)) self.assertTrue( isinstance(scf.newton(scf.HF(sym_mol_r1)), scf.hf_symm.ROHF))
def orbital_partitioning(mol, fragments, shells, verbose): at_species, at_orbitals, species = [], [], [] natom = 0 for i, (sh0, sh1, ao0, ao1) in enumerate(mol.offset_nr_by_atom()): name = mol.atom[i][0] if (name not in species): species.append(name) at_orbitals.append((ao0, ao1)) at_species.append(species.index(name)) natom += 1 # print("at species", at_species) # print("at orbitals", at_orbitals) # print("shells", shells) # exit() if (verbose): print("number of atoms ", natom) if (verbose): print("atomic species ", species) T_atom, n_core, n_vale, n_virt = [], [], [], [] for s in species: orbitals = [] nc = core_orbitals(s) nsh = len(shells[s]) for ib in range(nsh): pmol = gto.Mole() pmol.atom = [[s, (0.0, 0.0, 0.0)]] pmol.basis = {s: shells[s][ib]} pmol.charge = 0 pmol.spin = atomic_spins(s) pmol.symmetry = False pmol.build() nbasis = pmol.nao_nr() orbitals.append(nbasis - nc) pmf = scf.ROHF(pmol) pmf.max_cycle = 5000 pmf.conv_tol = 1e-6 pmf = scf.newton(pmf) pmf.scf() T_atom.append(pmf.mo_coeff) n_core.append(nc) n_vale.append(orbitals[0]) n_virt.append(orbitals[0:]) #print("orbitals", orbitals, orbitals[0], orbitals[0:]) #print("nvirt", n_virt) #print("t-atom", T_atom) for i in range(natom): j = at_species[i] if (verbose): print ( "atom ",i," species ",species[j], \ " AOs ",at_orbitals[i], \ " core,vale,virt ",n_core[j],n_vale[j],n_virt[j] ) #=============================================================== nbasis = mol.nao_nr() n_core_tot, n_vale_tot, n_virt_tot = 0, 0, 0 for i in range(natom): j = at_species[i] n_core_tot += n_core[j] n_vale_tot += n_vale[j] n_virt_tot += n_virt[j][nsh - 1] - n_vale[j] if (verbose): print("number of basis orbitals: ", nbasis) if (verbose): print("number of core,vale,virt orbitals: ", n_core_tot, n_vale_tot, n_virt_tot) if (n_core_tot == 0): Cf_core = None else: Cf_core = numpy.zeros((nbasis, n_core_tot), dtype=float) imin, imax = 0, 0 for i in range(natom): j = at_species[i] (ao0, ao1) = at_orbitals[i] nc = n_core[j] if (nc > 0): if (verbose): print ( "atom ",i," AOs ",ao0," to ",ao1, \ "CORE block (",ao0,",",ao1-1,") x (",imin,",",imin+nc,")" ) imax = imin + nc Cf_core[ao0:ao1, imin:imax] = T_atom[j][:, :nc] imin = imax #print("cf_core", Cf_core) Cf_vale = numpy.zeros((nbasis, n_vale_tot), dtype=float) imin, imax = 0, 0 for i in range(natom): j = at_species[i] (ao0, ao1) = at_orbitals[i] nc = n_core[j] nv = n_vale[j] imax = imin + nv if (verbose): print ( "atom ",i," AOs ",ao0," to ",ao1, \ "VALE block (",ao0,",",ao1-1,") x (",imin,",",imax-1,")" ) Cf_vale[ao0:ao1, imin:imax] = T_atom[j][:, nc:nv + nc] imin = imax #print("cf_vale", Cf_vale) #print("cf_vale", Cf_vale) Cf_virt = numpy.zeros((nbasis, n_virt_tot), dtype=float) imin, imax = 0, 0 for i in range(natom): j = at_species[i] (ao0, ao1) = at_orbitals[i] ncr = n_core[j] nva = n_vale[j] nvt = n_virt[j][nsh - 1] imax = imin + nvt - nva if (verbose): print ( "atom ",i," AOs ",ao0," to ",ao1, \ "VIRT block (",ao0,",",ao1-1,") x (",imin,",",imax-1,")" ) Cf_virt[ao0:ao1, imin:imax] = T_atom[j][:, nva + ncr:] imin = imax #print("cf vrt", Cf_virt) return Cf_core, Cf_vale, Cf_virt
self.mo10, self.mo_e10 = self.solve_mo1() mo10 = self.mo10 return para(self, mo10, mo_coeff, mo_occ) make_dia_gc2e = make_dia_gc2e make_para_soc2e = make_para_soc2e def align(self, gtensor): return align(gtensor) if __name__ == '__main__': from pyscf import gto, scf mol = gto.M(atom='C 0 0 0; O 0 0 1.25', basis='ccpvdz', spin=1, charge=1, verbose=3) mf = scf.newton(scf.UHF(mol)).run() gobj = GTensor(mf) gobj.para_soc2e = 'SSO+SOO' gobj.dia_soc2e = None gobj.so_eff_charge = False gobj.gauge_orig = (0,0,0) print(gobj.align(gobj.kernel())[0]) mol = gto.M(atom=''' H 0 0 1 ''', basis='ccpvdz', spin=1, charge=0, verbose=3) mf = scf.UHF(mol).run() gobj = GTensor(mf) print(gobj.align(gobj.kernel())[0])
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() uhf_stability(mf, True, True, verbose=4) mol = gto.M(atom=''' O1 O2 1 1.2227 O3 1 1.2227 2 114.0451